blob: f11ead816b3559d6dc737ba5671d7872dc56e754 [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
187 QualType ReturnTy = CE->getCallReturnType();
188 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;
John McCallbebede42011-02-26 05:39:39 +0000322
323 case Builtin::BI__builtin_classify_type:
324 if (checkArgCount(*this, TheCall, 1)) return true;
325 TheCall->setType(Context.IntTy);
326 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000327 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000328 if (checkArgCount(*this, TheCall, 1)) return true;
329 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000330 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000331 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000332 case Builtin::BI__sync_fetch_and_add_1:
333 case Builtin::BI__sync_fetch_and_add_2:
334 case Builtin::BI__sync_fetch_and_add_4:
335 case Builtin::BI__sync_fetch_and_add_8:
336 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000337 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000338 case Builtin::BI__sync_fetch_and_sub_1:
339 case Builtin::BI__sync_fetch_and_sub_2:
340 case Builtin::BI__sync_fetch_and_sub_4:
341 case Builtin::BI__sync_fetch_and_sub_8:
342 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000343 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000344 case Builtin::BI__sync_fetch_and_or_1:
345 case Builtin::BI__sync_fetch_and_or_2:
346 case Builtin::BI__sync_fetch_and_or_4:
347 case Builtin::BI__sync_fetch_and_or_8:
348 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000349 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000350 case Builtin::BI__sync_fetch_and_and_1:
351 case Builtin::BI__sync_fetch_and_and_2:
352 case Builtin::BI__sync_fetch_and_and_4:
353 case Builtin::BI__sync_fetch_and_and_8:
354 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000355 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000356 case Builtin::BI__sync_fetch_and_xor_1:
357 case Builtin::BI__sync_fetch_and_xor_2:
358 case Builtin::BI__sync_fetch_and_xor_4:
359 case Builtin::BI__sync_fetch_and_xor_8:
360 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000361 case Builtin::BI__sync_fetch_and_nand:
362 case Builtin::BI__sync_fetch_and_nand_1:
363 case Builtin::BI__sync_fetch_and_nand_2:
364 case Builtin::BI__sync_fetch_and_nand_4:
365 case Builtin::BI__sync_fetch_and_nand_8:
366 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000367 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000368 case Builtin::BI__sync_add_and_fetch_1:
369 case Builtin::BI__sync_add_and_fetch_2:
370 case Builtin::BI__sync_add_and_fetch_4:
371 case Builtin::BI__sync_add_and_fetch_8:
372 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000373 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000374 case Builtin::BI__sync_sub_and_fetch_1:
375 case Builtin::BI__sync_sub_and_fetch_2:
376 case Builtin::BI__sync_sub_and_fetch_4:
377 case Builtin::BI__sync_sub_and_fetch_8:
378 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000379 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000380 case Builtin::BI__sync_and_and_fetch_1:
381 case Builtin::BI__sync_and_and_fetch_2:
382 case Builtin::BI__sync_and_and_fetch_4:
383 case Builtin::BI__sync_and_and_fetch_8:
384 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000385 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000386 case Builtin::BI__sync_or_and_fetch_1:
387 case Builtin::BI__sync_or_and_fetch_2:
388 case Builtin::BI__sync_or_and_fetch_4:
389 case Builtin::BI__sync_or_and_fetch_8:
390 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000391 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000392 case Builtin::BI__sync_xor_and_fetch_1:
393 case Builtin::BI__sync_xor_and_fetch_2:
394 case Builtin::BI__sync_xor_and_fetch_4:
395 case Builtin::BI__sync_xor_and_fetch_8:
396 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000397 case Builtin::BI__sync_nand_and_fetch:
398 case Builtin::BI__sync_nand_and_fetch_1:
399 case Builtin::BI__sync_nand_and_fetch_2:
400 case Builtin::BI__sync_nand_and_fetch_4:
401 case Builtin::BI__sync_nand_and_fetch_8:
402 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000403 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000404 case Builtin::BI__sync_val_compare_and_swap_1:
405 case Builtin::BI__sync_val_compare_and_swap_2:
406 case Builtin::BI__sync_val_compare_and_swap_4:
407 case Builtin::BI__sync_val_compare_and_swap_8:
408 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000409 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000410 case Builtin::BI__sync_bool_compare_and_swap_1:
411 case Builtin::BI__sync_bool_compare_and_swap_2:
412 case Builtin::BI__sync_bool_compare_and_swap_4:
413 case Builtin::BI__sync_bool_compare_and_swap_8:
414 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000415 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000416 case Builtin::BI__sync_lock_test_and_set_1:
417 case Builtin::BI__sync_lock_test_and_set_2:
418 case Builtin::BI__sync_lock_test_and_set_4:
419 case Builtin::BI__sync_lock_test_and_set_8:
420 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000421 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000422 case Builtin::BI__sync_lock_release_1:
423 case Builtin::BI__sync_lock_release_2:
424 case Builtin::BI__sync_lock_release_4:
425 case Builtin::BI__sync_lock_release_8:
426 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000427 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000428 case Builtin::BI__sync_swap_1:
429 case Builtin::BI__sync_swap_2:
430 case Builtin::BI__sync_swap_4:
431 case Builtin::BI__sync_swap_8:
432 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000433 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000434#define BUILTIN(ID, TYPE, ATTRS)
435#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
436 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000437 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000438#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000439 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000440 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000441 return ExprError();
442 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000443 case Builtin::BI__builtin_addressof:
444 if (SemaBuiltinAddressof(*this, TheCall))
445 return ExprError();
446 break;
Richard Smith760520b2014-06-03 23:27:44 +0000447 case Builtin::BI__builtin_operator_new:
448 case Builtin::BI__builtin_operator_delete:
449 if (!getLangOpts().CPlusPlus) {
450 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
451 << (BuiltinID == Builtin::BI__builtin_operator_new
452 ? "__builtin_operator_new"
453 : "__builtin_operator_delete")
454 << "C++";
455 return ExprError();
456 }
457 // CodeGen assumes it can find the global new and delete to call,
458 // so ensure that they are declared.
459 DeclareGlobalNewDelete();
460 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000461
462 // check secure string manipulation functions where overflows
463 // are detectable at compile time
464 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000465 case Builtin::BI__builtin___memmove_chk:
466 case Builtin::BI__builtin___memset_chk:
467 case Builtin::BI__builtin___strlcat_chk:
468 case Builtin::BI__builtin___strlcpy_chk:
469 case Builtin::BI__builtin___strncat_chk:
470 case Builtin::BI__builtin___strncpy_chk:
471 case Builtin::BI__builtin___stpncpy_chk:
472 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
473 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000474 case Builtin::BI__builtin___memccpy_chk:
475 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
476 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000477 case Builtin::BI__builtin___snprintf_chk:
478 case Builtin::BI__builtin___vsnprintf_chk:
479 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
480 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000481
482 case Builtin::BI__builtin_call_with_static_chain:
483 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
484 return ExprError();
485 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000486
487 case Builtin::BI__exception_code:
488 case Builtin::BI_exception_code: {
489 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
490 diag::err_seh___except_block))
491 return ExprError();
492 break;
493 }
494 case Builtin::BI__exception_info:
495 case Builtin::BI_exception_info: {
496 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
497 diag::err_seh___except_filter))
498 return ExprError();
499 break;
500 }
501
Nate Begeman4904e322010-06-08 02:47:44 +0000502 }
Richard Smith760520b2014-06-03 23:27:44 +0000503
Nate Begeman4904e322010-06-08 02:47:44 +0000504 // Since the target specific builtins for each arch overlap, only check those
505 // of the arch we are compiling for.
506 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000507 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000508 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000509 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000510 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000511 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000512 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
513 return ExprError();
514 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000515 case llvm::Triple::aarch64:
516 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000517 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000518 return ExprError();
519 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000520 case llvm::Triple::mips:
521 case llvm::Triple::mipsel:
522 case llvm::Triple::mips64:
523 case llvm::Triple::mips64el:
524 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
525 return ExprError();
526 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000527 case llvm::Triple::x86:
528 case llvm::Triple::x86_64:
529 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
530 return ExprError();
531 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000532 default:
533 break;
534 }
535 }
536
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000537 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000538}
539
Nate Begeman91e1fea2010-06-14 05:21:25 +0000540// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000541static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000542 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000543 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000544 switch (Type.getEltType()) {
545 case NeonTypeFlags::Int8:
546 case NeonTypeFlags::Poly8:
547 return shift ? 7 : (8 << IsQuad) - 1;
548 case NeonTypeFlags::Int16:
549 case NeonTypeFlags::Poly16:
550 return shift ? 15 : (4 << IsQuad) - 1;
551 case NeonTypeFlags::Int32:
552 return shift ? 31 : (2 << IsQuad) - 1;
553 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000554 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000555 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000556 case NeonTypeFlags::Poly128:
557 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000558 case NeonTypeFlags::Float16:
559 assert(!shift && "cannot shift float types!");
560 return (4 << IsQuad) - 1;
561 case NeonTypeFlags::Float32:
562 assert(!shift && "cannot shift float types!");
563 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000564 case NeonTypeFlags::Float64:
565 assert(!shift && "cannot shift float types!");
566 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000567 }
David Blaikie8a40f702012-01-17 06:56:22 +0000568 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000569}
570
Bob Wilsone4d77232011-11-08 05:04:11 +0000571/// getNeonEltType - Return the QualType corresponding to the elements of
572/// the vector type specified by the NeonTypeFlags. This is used to check
573/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000574static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000575 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000576 switch (Flags.getEltType()) {
577 case NeonTypeFlags::Int8:
578 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
579 case NeonTypeFlags::Int16:
580 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
581 case NeonTypeFlags::Int32:
582 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
583 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000584 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000585 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
586 else
587 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
588 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000589 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000590 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000591 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000592 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000593 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000594 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000595 case NeonTypeFlags::Poly128:
596 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000597 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000598 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000599 case NeonTypeFlags::Float32:
600 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000601 case NeonTypeFlags::Float64:
602 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000603 }
David Blaikie8a40f702012-01-17 06:56:22 +0000604 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000605}
606
Tim Northover12670412014-02-19 10:37:05 +0000607bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000608 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000609 uint64_t mask = 0;
610 unsigned TV = 0;
611 int PtrArgNum = -1;
612 bool HasConstPtr = false;
613 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000614#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000615#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000616#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000617 }
618
619 // For NEON intrinsics which are overloaded on vector element type, validate
620 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000621 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000622 if (mask) {
623 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
624 return true;
625
626 TV = Result.getLimitedValue(64);
627 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
628 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000629 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000630 }
631
632 if (PtrArgNum >= 0) {
633 // Check that pointer arguments have the specified type.
634 Expr *Arg = TheCall->getArg(PtrArgNum);
635 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
636 Arg = ICE->getSubExpr();
637 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
638 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000639
Tim Northovera2ee4332014-03-29 15:09:45 +0000640 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000641 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000642 bool IsInt64Long =
643 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
644 QualType EltTy =
645 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000646 if (HasConstPtr)
647 EltTy = EltTy.withConst();
648 QualType LHSTy = Context.getPointerType(EltTy);
649 AssignConvertType ConvTy;
650 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
651 if (RHS.isInvalid())
652 return true;
653 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
654 RHS.get(), AA_Assigning))
655 return true;
656 }
657
658 // For NEON intrinsics which take an immediate value as part of the
659 // instruction, range check them here.
660 unsigned i = 0, l = 0, u = 0;
661 switch (BuiltinID) {
662 default:
663 return false;
Tim Northover12670412014-02-19 10:37:05 +0000664#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000665#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000666#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000667 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000668
Richard Sandiford28940af2014-04-16 08:47:51 +0000669 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000670}
671
Tim Northovera2ee4332014-03-29 15:09:45 +0000672bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
673 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000674 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000675 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000676 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000677 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000678 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000679 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
680 BuiltinID == AArch64::BI__builtin_arm_strex ||
681 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000682 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000683 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000684 BuiltinID == ARM::BI__builtin_arm_ldaex ||
685 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
686 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000687
688 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
689
690 // Ensure that we have the proper number of arguments.
691 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
692 return true;
693
694 // Inspect the pointer argument of the atomic builtin. This should always be
695 // a pointer type, whose element is an integral scalar or pointer type.
696 // Because it is a pointer type, we don't have to worry about any implicit
697 // casts here.
698 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
699 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
700 if (PointerArgRes.isInvalid())
701 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000702 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000703
704 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
705 if (!pointerType) {
706 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
707 << PointerArg->getType() << PointerArg->getSourceRange();
708 return true;
709 }
710
711 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
712 // task is to insert the appropriate casts into the AST. First work out just
713 // what the appropriate type is.
714 QualType ValType = pointerType->getPointeeType();
715 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
716 if (IsLdrex)
717 AddrType.addConst();
718
719 // Issue a warning if the cast is dodgy.
720 CastKind CastNeeded = CK_NoOp;
721 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
722 CastNeeded = CK_BitCast;
723 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
724 << PointerArg->getType()
725 << Context.getPointerType(AddrType)
726 << AA_Passing << PointerArg->getSourceRange();
727 }
728
729 // Finally, do the cast and replace the argument with the corrected version.
730 AddrType = Context.getPointerType(AddrType);
731 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
732 if (PointerArgRes.isInvalid())
733 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000734 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000735
736 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
737
738 // In general, we allow ints, floats and pointers to be loaded and stored.
739 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
740 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
741 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
742 << PointerArg->getType() << PointerArg->getSourceRange();
743 return true;
744 }
745
746 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000747 if (Context.getTypeSize(ValType) > MaxWidth) {
748 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000749 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
750 << PointerArg->getType() << PointerArg->getSourceRange();
751 return true;
752 }
753
754 switch (ValType.getObjCLifetime()) {
755 case Qualifiers::OCL_None:
756 case Qualifiers::OCL_ExplicitNone:
757 // okay
758 break;
759
760 case Qualifiers::OCL_Weak:
761 case Qualifiers::OCL_Strong:
762 case Qualifiers::OCL_Autoreleasing:
763 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
764 << ValType << PointerArg->getSourceRange();
765 return true;
766 }
767
768
769 if (IsLdrex) {
770 TheCall->setType(ValType);
771 return false;
772 }
773
774 // Initialize the argument to be stored.
775 ExprResult ValArg = TheCall->getArg(0);
776 InitializedEntity Entity = InitializedEntity::InitializeParameter(
777 Context, ValType, /*consume*/ false);
778 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
779 if (ValArg.isInvalid())
780 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000781 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000782
783 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
784 // but the custom checker bypasses all default analysis.
785 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000786 return false;
787}
788
Nate Begeman4904e322010-06-08 02:47:44 +0000789bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000790 llvm::APSInt Result;
791
Tim Northover6aacd492013-07-16 09:47:53 +0000792 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000793 BuiltinID == ARM::BI__builtin_arm_ldaex ||
794 BuiltinID == ARM::BI__builtin_arm_strex ||
795 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000796 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000797 }
798
Yi Kong26d104a2014-08-13 19:18:14 +0000799 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
800 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
801 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
802 }
803
Tim Northover12670412014-02-19 10:37:05 +0000804 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
805 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000806
Yi Kong4efadfb2014-07-03 16:01:25 +0000807 // For intrinsics which take an immediate value as part of the instruction,
808 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000809 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000810 switch (BuiltinID) {
811 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000812 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
813 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000814 case ARM::BI__builtin_arm_vcvtr_f:
815 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000816 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000817 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000818 case ARM::BI__builtin_arm_isb:
819 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000820 }
Nate Begemand773fe62010-06-13 04:47:52 +0000821
Nate Begemanf568b072010-08-03 21:32:34 +0000822 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000823 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000824}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000825
Tim Northover573cbee2014-05-24 12:52:07 +0000826bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000827 CallExpr *TheCall) {
828 llvm::APSInt Result;
829
Tim Northover573cbee2014-05-24 12:52:07 +0000830 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000831 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
832 BuiltinID == AArch64::BI__builtin_arm_strex ||
833 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000834 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
835 }
836
Yi Konga5548432014-08-13 19:18:20 +0000837 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
838 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
839 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
840 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
841 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
842 }
843
Tim Northovera2ee4332014-03-29 15:09:45 +0000844 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
845 return true;
846
Yi Kong19a29ac2014-07-17 10:52:06 +0000847 // For intrinsics which take an immediate value as part of the instruction,
848 // range check them here.
849 unsigned i = 0, l = 0, u = 0;
850 switch (BuiltinID) {
851 default: return false;
852 case AArch64::BI__builtin_arm_dmb:
853 case AArch64::BI__builtin_arm_dsb:
854 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
855 }
856
Yi Kong19a29ac2014-07-17 10:52:06 +0000857 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000858}
859
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000860bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
861 unsigned i = 0, l = 0, u = 0;
862 switch (BuiltinID) {
863 default: return false;
864 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
865 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000866 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
867 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
868 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
869 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
870 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000871 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000872
Richard Sandiford28940af2014-04-16 08:47:51 +0000873 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000874}
875
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000876bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000877 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000878 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000879 default: return false;
880 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +0000881 case X86::BI__builtin_ia32_vextractf128_pd256:
882 case X86::BI__builtin_ia32_vextractf128_ps256:
883 case X86::BI__builtin_ia32_vextractf128_si256:
884 case X86::BI__builtin_ia32_extract128i256: i = 1, l = 0, u = 1; break;
885 case X86::BI__builtin_ia32_vinsertf128_pd256:
886 case X86::BI__builtin_ia32_vinsertf128_ps256:
887 case X86::BI__builtin_ia32_vinsertf128_si256:
888 case X86::BI__builtin_ia32_insert128i256:
889 case X86::BI__builtin_ia32_blendpd: i = 2, l = 0; u = 1; break;
890 case X86::BI__builtin_ia32_blendps:
891 case X86::BI__builtin_ia32_blendpd256:
892 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +0000893 case X86::BI__builtin_ia32_cmpb128_mask:
894 case X86::BI__builtin_ia32_cmpw128_mask:
895 case X86::BI__builtin_ia32_cmpd128_mask:
896 case X86::BI__builtin_ia32_cmpq128_mask:
897 case X86::BI__builtin_ia32_cmpb256_mask:
898 case X86::BI__builtin_ia32_cmpw256_mask:
899 case X86::BI__builtin_ia32_cmpd256_mask:
900 case X86::BI__builtin_ia32_cmpq256_mask:
901 case X86::BI__builtin_ia32_cmpb512_mask:
902 case X86::BI__builtin_ia32_cmpw512_mask:
903 case X86::BI__builtin_ia32_cmpd512_mask:
904 case X86::BI__builtin_ia32_cmpq512_mask:
905 case X86::BI__builtin_ia32_ucmpb128_mask:
906 case X86::BI__builtin_ia32_ucmpw128_mask:
907 case X86::BI__builtin_ia32_ucmpd128_mask:
908 case X86::BI__builtin_ia32_ucmpq128_mask:
909 case X86::BI__builtin_ia32_ucmpb256_mask:
910 case X86::BI__builtin_ia32_ucmpw256_mask:
911 case X86::BI__builtin_ia32_ucmpd256_mask:
912 case X86::BI__builtin_ia32_ucmpq256_mask:
913 case X86::BI__builtin_ia32_ucmpb512_mask:
914 case X86::BI__builtin_ia32_ucmpw512_mask:
915 case X86::BI__builtin_ia32_ucmpd512_mask:
916 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +0000917 case X86::BI__builtin_ia32_roundps:
918 case X86::BI__builtin_ia32_roundpd:
919 case X86::BI__builtin_ia32_roundps256:
920 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
921 case X86::BI__builtin_ia32_roundss:
922 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
923 case X86::BI__builtin_ia32_cmpps:
924 case X86::BI__builtin_ia32_cmpss:
925 case X86::BI__builtin_ia32_cmppd:
926 case X86::BI__builtin_ia32_cmpsd:
927 case X86::BI__builtin_ia32_cmpps256:
928 case X86::BI__builtin_ia32_cmppd256:
929 case X86::BI__builtin_ia32_cmpps512_mask:
930 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000931 }
Craig Topperdd84ec52014-12-27 07:00:08 +0000932 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000933}
934
Richard Smith55ce3522012-06-25 20:30:08 +0000935/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
936/// parameter with the FormatAttr's correct format_idx and firstDataArg.
937/// Returns true when the format fits the function and the FormatStringInfo has
938/// been populated.
939bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
940 FormatStringInfo *FSI) {
941 FSI->HasVAListArg = Format->getFirstArg() == 0;
942 FSI->FormatIdx = Format->getFormatIdx() - 1;
943 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000944
Richard Smith55ce3522012-06-25 20:30:08 +0000945 // The way the format attribute works in GCC, the implicit this argument
946 // of member functions is counted. However, it doesn't appear in our own
947 // lists, so decrement format_idx in that case.
948 if (IsCXXMember) {
949 if(FSI->FormatIdx == 0)
950 return false;
951 --FSI->FormatIdx;
952 if (FSI->FirstDataArg != 0)
953 --FSI->FirstDataArg;
954 }
955 return true;
956}
Mike Stump11289f42009-09-09 15:08:12 +0000957
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000958/// Checks if a the given expression evaluates to null.
959///
960/// \brief Returns true if the value evaluates to null.
961static bool CheckNonNullExpr(Sema &S,
962 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000963 // As a special case, transparent unions initialized with zero are
964 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000965 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000966 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
967 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000968 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000969 if (const InitListExpr *ILE =
970 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000971 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000972 }
973
974 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000975 return (!Expr->isValueDependent() &&
976 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
977 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000978}
979
980static void CheckNonNullArgument(Sema &S,
981 const Expr *ArgExpr,
982 SourceLocation CallSiteLoc) {
983 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000984 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
985}
986
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000987bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
988 FormatStringInfo FSI;
989 if ((GetFormatStringType(Format) == FST_NSString) &&
990 getFormatStringInfo(Format, false, &FSI)) {
991 Idx = FSI.FormatIdx;
992 return true;
993 }
994 return false;
995}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000996/// \brief Diagnose use of %s directive in an NSString which is being passed
997/// as formatting string to formatting method.
998static void
999DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1000 const NamedDecl *FDecl,
1001 Expr **Args,
1002 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001003 unsigned Idx = 0;
1004 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001005 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1006 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001007 Idx = 2;
1008 Format = true;
1009 }
1010 else
1011 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1012 if (S.GetFormatNSStringIdx(I, Idx)) {
1013 Format = true;
1014 break;
1015 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001016 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001017 if (!Format || NumArgs <= Idx)
1018 return;
1019 const Expr *FormatExpr = Args[Idx];
1020 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1021 FormatExpr = CSCE->getSubExpr();
1022 const StringLiteral *FormatString;
1023 if (const ObjCStringLiteral *OSL =
1024 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1025 FormatString = OSL->getString();
1026 else
1027 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1028 if (!FormatString)
1029 return;
1030 if (S.FormatStringHasSArg(FormatString)) {
1031 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1032 << "%s" << 1 << 1;
1033 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1034 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001035 }
1036}
1037
Ted Kremenek2bc73332014-01-17 06:24:43 +00001038static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001039 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +00001040 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001041 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001042 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001043 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001044 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001045 if (!NonNull->args_size()) {
1046 // Easy case: all pointer arguments are nonnull.
1047 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +00001048 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +00001049 CheckNonNullArgument(S, Arg, CallSiteLoc);
1050 return;
1051 }
1052
1053 for (unsigned Val : NonNull->args()) {
1054 if (Val >= Args.size())
1055 continue;
1056 if (NonNullArgs.empty())
1057 NonNullArgs.resize(Args.size());
1058 NonNullArgs.set(Val);
1059 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001060 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001061
1062 // Check the attributes on the parameters.
1063 ArrayRef<ParmVarDecl*> parms;
1064 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1065 parms = FD->parameters();
1066 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1067 parms = MD->parameters();
1068
Richard Smith588bd9b2014-08-27 04:59:42 +00001069 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001070 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +00001071 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001072 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +00001073 if (PVD->hasAttr<NonNullAttr>() ||
1074 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1075 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +00001076 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001077
1078 // In case this is a variadic call, check any remaining arguments.
1079 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1080 if (NonNullArgs[ArgIndex])
1081 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +00001082}
1083
Richard Smith55ce3522012-06-25 20:30:08 +00001084/// Handles the checks for format strings, non-POD arguments to vararg
1085/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00001086void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1087 unsigned NumParams, bool IsMemberFunction,
1088 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001089 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001090 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001091 if (CurContext->isDependentContext())
1092 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001093
Ted Kremenekb8176da2010-09-09 04:33:05 +00001094 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001095 llvm::SmallBitVector CheckedVarArgs;
1096 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001097 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001098 // Only create vector if there are format attributes.
1099 CheckedVarArgs.resize(Args.size());
1100
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001101 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001102 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001103 }
Richard Smithd7293d72013-08-05 18:49:43 +00001104 }
Richard Smith55ce3522012-06-25 20:30:08 +00001105
1106 // Refuse POD arguments that weren't caught by the format string
1107 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001108 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001109 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001110 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001111 if (const Expr *Arg = Args[ArgIdx]) {
1112 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1113 checkVariadicArgument(Arg, CallType);
1114 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001115 }
Richard Smithd7293d72013-08-05 18:49:43 +00001116 }
Mike Stump11289f42009-09-09 15:08:12 +00001117
Richard Trieu41bc0992013-06-22 00:20:41 +00001118 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001119 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001120
Richard Trieu41bc0992013-06-22 00:20:41 +00001121 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001122 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1123 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001124 }
Richard Smith55ce3522012-06-25 20:30:08 +00001125}
1126
1127/// CheckConstructorCall - Check a constructor call for correctness and safety
1128/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001129void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1130 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001131 const FunctionProtoType *Proto,
1132 SourceLocation Loc) {
1133 VariadicCallType CallType =
1134 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +00001135 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +00001136 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1137}
1138
1139/// CheckFunctionCall - Check a direct function call for various correctness
1140/// and safety properties not strictly enforced by the C type system.
1141bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1142 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001143 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1144 isa<CXXMethodDecl>(FDecl);
1145 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1146 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001147 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1148 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001149 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +00001150 Expr** Args = TheCall->getArgs();
1151 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001152 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001153 // If this is a call to a member operator, hide the first argument
1154 // from checkCall.
1155 // FIXME: Our choice of AST representation here is less than ideal.
1156 ++Args;
1157 --NumArgs;
1158 }
Craig Topper8c2a2a02014-08-30 16:55:39 +00001159 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +00001160 IsMemberFunction, TheCall->getRParenLoc(),
1161 TheCall->getCallee()->getSourceRange(), CallType);
1162
1163 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1164 // None of the checks below are needed for functions that don't have
1165 // simple names (e.g., C++ conversion functions).
1166 if (!FnInfo)
1167 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001168
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001169 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001170 if (getLangOpts().ObjC1)
1171 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001172
Anna Zaks22122702012-01-17 00:37:07 +00001173 unsigned CMId = FDecl->getMemoryFunctionKind();
1174 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001175 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001176
Anna Zaks201d4892012-01-13 21:52:01 +00001177 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001178 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001179 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001180 else if (CMId == Builtin::BIstrncat)
1181 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001182 else
Anna Zaks22122702012-01-17 00:37:07 +00001183 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001184
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001185 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001186}
1187
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001188bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001189 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001190 VariadicCallType CallType =
1191 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001192
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001193 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001194 /*IsMemberFunction=*/false,
1195 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001196
1197 return false;
1198}
1199
Richard Trieu664c4c62013-06-20 21:03:13 +00001200bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1201 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001202 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1203 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001204 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001205
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001206 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +00001207 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001208 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001209
Richard Trieu664c4c62013-06-20 21:03:13 +00001210 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001211 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001212 CallType = VariadicDoesNotApply;
1213 } else if (Ty->isBlockPointerType()) {
1214 CallType = VariadicBlock;
1215 } else { // Ty->isFunctionPointerType()
1216 CallType = VariadicFunction;
1217 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001218 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001219
Craig Topper8c2a2a02014-08-30 16:55:39 +00001220 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1221 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001222 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001223 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001224
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001225 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001226}
1227
Richard Trieu41bc0992013-06-22 00:20:41 +00001228/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1229/// such as function pointers returned from functions.
1230bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001231 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001232 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001233 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001234
Craig Topperc3ec1492014-05-26 06:22:03 +00001235 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001236 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001237 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001238 TheCall->getCallee()->getSourceRange(), CallType);
1239
1240 return false;
1241}
1242
Tim Northovere94a34c2014-03-11 10:49:14 +00001243static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1244 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1245 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1246 return false;
1247
1248 switch (Op) {
1249 case AtomicExpr::AO__c11_atomic_init:
1250 llvm_unreachable("There is no ordering argument for an init");
1251
1252 case AtomicExpr::AO__c11_atomic_load:
1253 case AtomicExpr::AO__atomic_load_n:
1254 case AtomicExpr::AO__atomic_load:
1255 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1256 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1257
1258 case AtomicExpr::AO__c11_atomic_store:
1259 case AtomicExpr::AO__atomic_store:
1260 case AtomicExpr::AO__atomic_store_n:
1261 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1262 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1263 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1264
1265 default:
1266 return true;
1267 }
1268}
1269
Richard Smithfeea8832012-04-12 05:08:17 +00001270ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1271 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001272 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1273 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001274
Richard Smithfeea8832012-04-12 05:08:17 +00001275 // All these operations take one of the following forms:
1276 enum {
1277 // C __c11_atomic_init(A *, C)
1278 Init,
1279 // C __c11_atomic_load(A *, int)
1280 Load,
1281 // void __atomic_load(A *, CP, int)
1282 Copy,
1283 // C __c11_atomic_add(A *, M, int)
1284 Arithmetic,
1285 // C __atomic_exchange_n(A *, CP, int)
1286 Xchg,
1287 // void __atomic_exchange(A *, C *, CP, int)
1288 GNUXchg,
1289 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1290 C11CmpXchg,
1291 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1292 GNUCmpXchg
1293 } Form = Init;
1294 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1295 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1296 // where:
1297 // C is an appropriate type,
1298 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1299 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1300 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1301 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001302
Richard Smithfeea8832012-04-12 05:08:17 +00001303 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1304 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1305 && "need to update code for modified C11 atomics");
1306 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1307 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1308 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1309 Op == AtomicExpr::AO__atomic_store_n ||
1310 Op == AtomicExpr::AO__atomic_exchange_n ||
1311 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1312 bool IsAddSub = false;
1313
1314 switch (Op) {
1315 case AtomicExpr::AO__c11_atomic_init:
1316 Form = Init;
1317 break;
1318
1319 case AtomicExpr::AO__c11_atomic_load:
1320 case AtomicExpr::AO__atomic_load_n:
1321 Form = Load;
1322 break;
1323
1324 case AtomicExpr::AO__c11_atomic_store:
1325 case AtomicExpr::AO__atomic_load:
1326 case AtomicExpr::AO__atomic_store:
1327 case AtomicExpr::AO__atomic_store_n:
1328 Form = Copy;
1329 break;
1330
1331 case AtomicExpr::AO__c11_atomic_fetch_add:
1332 case AtomicExpr::AO__c11_atomic_fetch_sub:
1333 case AtomicExpr::AO__atomic_fetch_add:
1334 case AtomicExpr::AO__atomic_fetch_sub:
1335 case AtomicExpr::AO__atomic_add_fetch:
1336 case AtomicExpr::AO__atomic_sub_fetch:
1337 IsAddSub = true;
1338 // Fall through.
1339 case AtomicExpr::AO__c11_atomic_fetch_and:
1340 case AtomicExpr::AO__c11_atomic_fetch_or:
1341 case AtomicExpr::AO__c11_atomic_fetch_xor:
1342 case AtomicExpr::AO__atomic_fetch_and:
1343 case AtomicExpr::AO__atomic_fetch_or:
1344 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001345 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001346 case AtomicExpr::AO__atomic_and_fetch:
1347 case AtomicExpr::AO__atomic_or_fetch:
1348 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001349 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001350 Form = Arithmetic;
1351 break;
1352
1353 case AtomicExpr::AO__c11_atomic_exchange:
1354 case AtomicExpr::AO__atomic_exchange_n:
1355 Form = Xchg;
1356 break;
1357
1358 case AtomicExpr::AO__atomic_exchange:
1359 Form = GNUXchg;
1360 break;
1361
1362 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1363 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1364 Form = C11CmpXchg;
1365 break;
1366
1367 case AtomicExpr::AO__atomic_compare_exchange:
1368 case AtomicExpr::AO__atomic_compare_exchange_n:
1369 Form = GNUCmpXchg;
1370 break;
1371 }
1372
1373 // Check we have the right number of arguments.
1374 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001375 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001376 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001377 << TheCall->getCallee()->getSourceRange();
1378 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001379 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1380 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001381 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001382 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001383 << TheCall->getCallee()->getSourceRange();
1384 return ExprError();
1385 }
1386
Richard Smithfeea8832012-04-12 05:08:17 +00001387 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001388 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001389 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1390 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1391 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001392 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001393 << Ptr->getType() << Ptr->getSourceRange();
1394 return ExprError();
1395 }
1396
Richard Smithfeea8832012-04-12 05:08:17 +00001397 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1398 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1399 QualType ValType = AtomTy; // 'C'
1400 if (IsC11) {
1401 if (!AtomTy->isAtomicType()) {
1402 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1403 << Ptr->getType() << Ptr->getSourceRange();
1404 return ExprError();
1405 }
Richard Smithe00921a2012-09-15 06:09:58 +00001406 if (AtomTy.isConstQualified()) {
1407 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1408 << Ptr->getType() << Ptr->getSourceRange();
1409 return ExprError();
1410 }
Richard Smithfeea8832012-04-12 05:08:17 +00001411 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001412 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001413
Richard Smithfeea8832012-04-12 05:08:17 +00001414 // For an arithmetic operation, the implied arithmetic must be well-formed.
1415 if (Form == Arithmetic) {
1416 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1417 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1418 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1419 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1420 return ExprError();
1421 }
1422 if (!IsAddSub && !ValType->isIntegerType()) {
1423 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1424 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1425 return ExprError();
1426 }
David Majnemere85cff82015-01-28 05:48:06 +00001427 if (IsC11 && ValType->isPointerType() &&
1428 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1429 diag::err_incomplete_type)) {
1430 return ExprError();
1431 }
Richard Smithfeea8832012-04-12 05:08:17 +00001432 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1433 // For __atomic_*_n operations, the value type must be a scalar integral or
1434 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001435 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001436 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1437 return ExprError();
1438 }
1439
Eli Friedmanaa769812013-09-11 03:49:34 +00001440 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1441 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001442 // For GNU atomics, require a trivially-copyable type. This is not part of
1443 // the GNU atomics specification, but we enforce it for sanity.
1444 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001445 << Ptr->getType() << Ptr->getSourceRange();
1446 return ExprError();
1447 }
1448
Richard Smithfeea8832012-04-12 05:08:17 +00001449 // FIXME: For any builtin other than a load, the ValType must not be
1450 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001451
1452 switch (ValType.getObjCLifetime()) {
1453 case Qualifiers::OCL_None:
1454 case Qualifiers::OCL_ExplicitNone:
1455 // okay
1456 break;
1457
1458 case Qualifiers::OCL_Weak:
1459 case Qualifiers::OCL_Strong:
1460 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001461 // FIXME: Can this happen? By this point, ValType should be known
1462 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001463 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1464 << ValType << Ptr->getSourceRange();
1465 return ExprError();
1466 }
1467
1468 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001469 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001470 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001471 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001472 ResultType = Context.BoolTy;
1473
Richard Smithfeea8832012-04-12 05:08:17 +00001474 // The type of a parameter passed 'by value'. In the GNU atomics, such
1475 // arguments are actually passed as pointers.
1476 QualType ByValType = ValType; // 'CP'
1477 if (!IsC11 && !IsN)
1478 ByValType = Ptr->getType();
1479
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001480 // The first argument --- the pointer --- has a fixed type; we
1481 // deduce the types of the rest of the arguments accordingly. Walk
1482 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001483 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001484 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001485 if (i < NumVals[Form] + 1) {
1486 switch (i) {
1487 case 1:
1488 // The second argument is the non-atomic operand. For arithmetic, this
1489 // is always passed by value, and for a compare_exchange it is always
1490 // passed by address. For the rest, GNU uses by-address and C11 uses
1491 // by-value.
1492 assert(Form != Load);
1493 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1494 Ty = ValType;
1495 else if (Form == Copy || Form == Xchg)
1496 Ty = ByValType;
1497 else if (Form == Arithmetic)
1498 Ty = Context.getPointerDiffType();
1499 else
1500 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1501 break;
1502 case 2:
1503 // The third argument to compare_exchange / GNU exchange is a
1504 // (pointer to a) desired value.
1505 Ty = ByValType;
1506 break;
1507 case 3:
1508 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1509 Ty = Context.BoolTy;
1510 break;
1511 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001512 } else {
1513 // The order(s) are always converted to int.
1514 Ty = Context.IntTy;
1515 }
Richard Smithfeea8832012-04-12 05:08:17 +00001516
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001517 InitializedEntity Entity =
1518 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001519 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001520 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1521 if (Arg.isInvalid())
1522 return true;
1523 TheCall->setArg(i, Arg.get());
1524 }
1525
Richard Smithfeea8832012-04-12 05:08:17 +00001526 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001527 SmallVector<Expr*, 5> SubExprs;
1528 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001529 switch (Form) {
1530 case Init:
1531 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001532 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001533 break;
1534 case Load:
1535 SubExprs.push_back(TheCall->getArg(1)); // Order
1536 break;
1537 case Copy:
1538 case Arithmetic:
1539 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001540 SubExprs.push_back(TheCall->getArg(2)); // Order
1541 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001542 break;
1543 case GNUXchg:
1544 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1545 SubExprs.push_back(TheCall->getArg(3)); // Order
1546 SubExprs.push_back(TheCall->getArg(1)); // Val1
1547 SubExprs.push_back(TheCall->getArg(2)); // Val2
1548 break;
1549 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001550 SubExprs.push_back(TheCall->getArg(3)); // Order
1551 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001552 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001553 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001554 break;
1555 case GNUCmpXchg:
1556 SubExprs.push_back(TheCall->getArg(4)); // Order
1557 SubExprs.push_back(TheCall->getArg(1)); // Val1
1558 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1559 SubExprs.push_back(TheCall->getArg(2)); // Val2
1560 SubExprs.push_back(TheCall->getArg(3)); // Weak
1561 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001562 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001563
1564 if (SubExprs.size() >= 2 && Form != Init) {
1565 llvm::APSInt Result(32);
1566 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1567 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001568 Diag(SubExprs[1]->getLocStart(),
1569 diag::warn_atomic_op_has_invalid_memory_order)
1570 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001571 }
1572
Fariborz Jahanian615de762013-05-28 17:37:39 +00001573 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1574 SubExprs, ResultType, Op,
1575 TheCall->getRParenLoc());
1576
1577 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1578 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1579 Context.AtomicUsesUnsupportedLibcall(AE))
1580 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1581 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001582
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001583 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001584}
1585
1586
John McCall29ad95b2011-08-27 01:09:30 +00001587/// checkBuiltinArgument - Given a call to a builtin function, perform
1588/// normal type-checking on the given argument, updating the call in
1589/// place. This is useful when a builtin function requires custom
1590/// type-checking for some of its arguments but not necessarily all of
1591/// them.
1592///
1593/// Returns true on error.
1594static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1595 FunctionDecl *Fn = E->getDirectCallee();
1596 assert(Fn && "builtin call without direct callee!");
1597
1598 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1599 InitializedEntity Entity =
1600 InitializedEntity::InitializeParameter(S.Context, Param);
1601
1602 ExprResult Arg = E->getArg(0);
1603 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1604 if (Arg.isInvalid())
1605 return true;
1606
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001607 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001608 return false;
1609}
1610
Chris Lattnerdc046542009-05-08 06:58:22 +00001611/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1612/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1613/// type of its first argument. The main ActOnCallExpr routines have already
1614/// promoted the types of arguments because all of these calls are prototyped as
1615/// void(...).
1616///
1617/// This function goes through and does final semantic checking for these
1618/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001619ExprResult
1620Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001621 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001622 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1623 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1624
1625 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001626 if (TheCall->getNumArgs() < 1) {
1627 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1628 << 0 << 1 << TheCall->getNumArgs()
1629 << TheCall->getCallee()->getSourceRange();
1630 return ExprError();
1631 }
Mike Stump11289f42009-09-09 15:08:12 +00001632
Chris Lattnerdc046542009-05-08 06:58:22 +00001633 // Inspect the first argument of the atomic builtin. This should always be
1634 // a pointer type, whose element is an integral scalar or pointer type.
1635 // Because it is a pointer type, we don't have to worry about any implicit
1636 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001637 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001638 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001639 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1640 if (FirstArgResult.isInvalid())
1641 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001642 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001643 TheCall->setArg(0, FirstArg);
1644
John McCall31168b02011-06-15 23:02:42 +00001645 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1646 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001647 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1648 << FirstArg->getType() << FirstArg->getSourceRange();
1649 return ExprError();
1650 }
Mike Stump11289f42009-09-09 15:08:12 +00001651
John McCall31168b02011-06-15 23:02:42 +00001652 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001653 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001654 !ValType->isBlockPointerType()) {
1655 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1656 << FirstArg->getType() << FirstArg->getSourceRange();
1657 return ExprError();
1658 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001659
John McCall31168b02011-06-15 23:02:42 +00001660 switch (ValType.getObjCLifetime()) {
1661 case Qualifiers::OCL_None:
1662 case Qualifiers::OCL_ExplicitNone:
1663 // okay
1664 break;
1665
1666 case Qualifiers::OCL_Weak:
1667 case Qualifiers::OCL_Strong:
1668 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001669 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001670 << ValType << FirstArg->getSourceRange();
1671 return ExprError();
1672 }
1673
John McCallb50451a2011-10-05 07:41:44 +00001674 // Strip any qualifiers off ValType.
1675 ValType = ValType.getUnqualifiedType();
1676
Chandler Carruth3973af72010-07-18 20:54:12 +00001677 // The majority of builtins return a value, but a few have special return
1678 // types, so allow them to override appropriately below.
1679 QualType ResultType = ValType;
1680
Chris Lattnerdc046542009-05-08 06:58:22 +00001681 // We need to figure out which concrete builtin this maps onto. For example,
1682 // __sync_fetch_and_add with a 2 byte object turns into
1683 // __sync_fetch_and_add_2.
1684#define BUILTIN_ROW(x) \
1685 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1686 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001687
Chris Lattnerdc046542009-05-08 06:58:22 +00001688 static const unsigned BuiltinIndices[][5] = {
1689 BUILTIN_ROW(__sync_fetch_and_add),
1690 BUILTIN_ROW(__sync_fetch_and_sub),
1691 BUILTIN_ROW(__sync_fetch_and_or),
1692 BUILTIN_ROW(__sync_fetch_and_and),
1693 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001694 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001695
Chris Lattnerdc046542009-05-08 06:58:22 +00001696 BUILTIN_ROW(__sync_add_and_fetch),
1697 BUILTIN_ROW(__sync_sub_and_fetch),
1698 BUILTIN_ROW(__sync_and_and_fetch),
1699 BUILTIN_ROW(__sync_or_and_fetch),
1700 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001701 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001702
Chris Lattnerdc046542009-05-08 06:58:22 +00001703 BUILTIN_ROW(__sync_val_compare_and_swap),
1704 BUILTIN_ROW(__sync_bool_compare_and_swap),
1705 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001706 BUILTIN_ROW(__sync_lock_release),
1707 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001708 };
Mike Stump11289f42009-09-09 15:08:12 +00001709#undef BUILTIN_ROW
1710
Chris Lattnerdc046542009-05-08 06:58:22 +00001711 // Determine the index of the size.
1712 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001713 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001714 case 1: SizeIndex = 0; break;
1715 case 2: SizeIndex = 1; break;
1716 case 4: SizeIndex = 2; break;
1717 case 8: SizeIndex = 3; break;
1718 case 16: SizeIndex = 4; break;
1719 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001720 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1721 << FirstArg->getType() << FirstArg->getSourceRange();
1722 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001723 }
Mike Stump11289f42009-09-09 15:08:12 +00001724
Chris Lattnerdc046542009-05-08 06:58:22 +00001725 // Each of these builtins has one pointer argument, followed by some number of
1726 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1727 // that we ignore. Find out which row of BuiltinIndices to read from as well
1728 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001729 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001730 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001731 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001732 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001733 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001734 case Builtin::BI__sync_fetch_and_add:
1735 case Builtin::BI__sync_fetch_and_add_1:
1736 case Builtin::BI__sync_fetch_and_add_2:
1737 case Builtin::BI__sync_fetch_and_add_4:
1738 case Builtin::BI__sync_fetch_and_add_8:
1739 case Builtin::BI__sync_fetch_and_add_16:
1740 BuiltinIndex = 0;
1741 break;
1742
1743 case Builtin::BI__sync_fetch_and_sub:
1744 case Builtin::BI__sync_fetch_and_sub_1:
1745 case Builtin::BI__sync_fetch_and_sub_2:
1746 case Builtin::BI__sync_fetch_and_sub_4:
1747 case Builtin::BI__sync_fetch_and_sub_8:
1748 case Builtin::BI__sync_fetch_and_sub_16:
1749 BuiltinIndex = 1;
1750 break;
1751
1752 case Builtin::BI__sync_fetch_and_or:
1753 case Builtin::BI__sync_fetch_and_or_1:
1754 case Builtin::BI__sync_fetch_and_or_2:
1755 case Builtin::BI__sync_fetch_and_or_4:
1756 case Builtin::BI__sync_fetch_and_or_8:
1757 case Builtin::BI__sync_fetch_and_or_16:
1758 BuiltinIndex = 2;
1759 break;
1760
1761 case Builtin::BI__sync_fetch_and_and:
1762 case Builtin::BI__sync_fetch_and_and_1:
1763 case Builtin::BI__sync_fetch_and_and_2:
1764 case Builtin::BI__sync_fetch_and_and_4:
1765 case Builtin::BI__sync_fetch_and_and_8:
1766 case Builtin::BI__sync_fetch_and_and_16:
1767 BuiltinIndex = 3;
1768 break;
Mike Stump11289f42009-09-09 15:08:12 +00001769
Douglas Gregor73722482011-11-28 16:30:08 +00001770 case Builtin::BI__sync_fetch_and_xor:
1771 case Builtin::BI__sync_fetch_and_xor_1:
1772 case Builtin::BI__sync_fetch_and_xor_2:
1773 case Builtin::BI__sync_fetch_and_xor_4:
1774 case Builtin::BI__sync_fetch_and_xor_8:
1775 case Builtin::BI__sync_fetch_and_xor_16:
1776 BuiltinIndex = 4;
1777 break;
1778
Hal Finkeld2208b52014-10-02 20:53:50 +00001779 case Builtin::BI__sync_fetch_and_nand:
1780 case Builtin::BI__sync_fetch_and_nand_1:
1781 case Builtin::BI__sync_fetch_and_nand_2:
1782 case Builtin::BI__sync_fetch_and_nand_4:
1783 case Builtin::BI__sync_fetch_and_nand_8:
1784 case Builtin::BI__sync_fetch_and_nand_16:
1785 BuiltinIndex = 5;
1786 WarnAboutSemanticsChange = true;
1787 break;
1788
Douglas Gregor73722482011-11-28 16:30:08 +00001789 case Builtin::BI__sync_add_and_fetch:
1790 case Builtin::BI__sync_add_and_fetch_1:
1791 case Builtin::BI__sync_add_and_fetch_2:
1792 case Builtin::BI__sync_add_and_fetch_4:
1793 case Builtin::BI__sync_add_and_fetch_8:
1794 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001795 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00001796 break;
1797
1798 case Builtin::BI__sync_sub_and_fetch:
1799 case Builtin::BI__sync_sub_and_fetch_1:
1800 case Builtin::BI__sync_sub_and_fetch_2:
1801 case Builtin::BI__sync_sub_and_fetch_4:
1802 case Builtin::BI__sync_sub_and_fetch_8:
1803 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001804 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00001805 break;
1806
1807 case Builtin::BI__sync_and_and_fetch:
1808 case Builtin::BI__sync_and_and_fetch_1:
1809 case Builtin::BI__sync_and_and_fetch_2:
1810 case Builtin::BI__sync_and_and_fetch_4:
1811 case Builtin::BI__sync_and_and_fetch_8:
1812 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001813 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00001814 break;
1815
1816 case Builtin::BI__sync_or_and_fetch:
1817 case Builtin::BI__sync_or_and_fetch_1:
1818 case Builtin::BI__sync_or_and_fetch_2:
1819 case Builtin::BI__sync_or_and_fetch_4:
1820 case Builtin::BI__sync_or_and_fetch_8:
1821 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001822 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00001823 break;
1824
1825 case Builtin::BI__sync_xor_and_fetch:
1826 case Builtin::BI__sync_xor_and_fetch_1:
1827 case Builtin::BI__sync_xor_and_fetch_2:
1828 case Builtin::BI__sync_xor_and_fetch_4:
1829 case Builtin::BI__sync_xor_and_fetch_8:
1830 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001831 BuiltinIndex = 10;
1832 break;
1833
1834 case Builtin::BI__sync_nand_and_fetch:
1835 case Builtin::BI__sync_nand_and_fetch_1:
1836 case Builtin::BI__sync_nand_and_fetch_2:
1837 case Builtin::BI__sync_nand_and_fetch_4:
1838 case Builtin::BI__sync_nand_and_fetch_8:
1839 case Builtin::BI__sync_nand_and_fetch_16:
1840 BuiltinIndex = 11;
1841 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00001842 break;
Mike Stump11289f42009-09-09 15:08:12 +00001843
Chris Lattnerdc046542009-05-08 06:58:22 +00001844 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001845 case Builtin::BI__sync_val_compare_and_swap_1:
1846 case Builtin::BI__sync_val_compare_and_swap_2:
1847 case Builtin::BI__sync_val_compare_and_swap_4:
1848 case Builtin::BI__sync_val_compare_and_swap_8:
1849 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001850 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00001851 NumFixed = 2;
1852 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001853
Chris Lattnerdc046542009-05-08 06:58:22 +00001854 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001855 case Builtin::BI__sync_bool_compare_and_swap_1:
1856 case Builtin::BI__sync_bool_compare_and_swap_2:
1857 case Builtin::BI__sync_bool_compare_and_swap_4:
1858 case Builtin::BI__sync_bool_compare_and_swap_8:
1859 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001860 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001861 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001862 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001863 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001864
1865 case Builtin::BI__sync_lock_test_and_set:
1866 case Builtin::BI__sync_lock_test_and_set_1:
1867 case Builtin::BI__sync_lock_test_and_set_2:
1868 case Builtin::BI__sync_lock_test_and_set_4:
1869 case Builtin::BI__sync_lock_test_and_set_8:
1870 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001871 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00001872 break;
1873
Chris Lattnerdc046542009-05-08 06:58:22 +00001874 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001875 case Builtin::BI__sync_lock_release_1:
1876 case Builtin::BI__sync_lock_release_2:
1877 case Builtin::BI__sync_lock_release_4:
1878 case Builtin::BI__sync_lock_release_8:
1879 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001880 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00001881 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001882 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001883 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001884
1885 case Builtin::BI__sync_swap:
1886 case Builtin::BI__sync_swap_1:
1887 case Builtin::BI__sync_swap_2:
1888 case Builtin::BI__sync_swap_4:
1889 case Builtin::BI__sync_swap_8:
1890 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001891 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00001892 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001893 }
Mike Stump11289f42009-09-09 15:08:12 +00001894
Chris Lattnerdc046542009-05-08 06:58:22 +00001895 // Now that we know how many fixed arguments we expect, first check that we
1896 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001897 if (TheCall->getNumArgs() < 1+NumFixed) {
1898 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1899 << 0 << 1+NumFixed << TheCall->getNumArgs()
1900 << TheCall->getCallee()->getSourceRange();
1901 return ExprError();
1902 }
Mike Stump11289f42009-09-09 15:08:12 +00001903
Hal Finkeld2208b52014-10-02 20:53:50 +00001904 if (WarnAboutSemanticsChange) {
1905 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1906 << TheCall->getCallee()->getSourceRange();
1907 }
1908
Chris Lattner5b9241b2009-05-08 15:36:58 +00001909 // Get the decl for the concrete builtin from this, we can tell what the
1910 // concrete integer type we should convert to is.
1911 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1912 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001913 FunctionDecl *NewBuiltinDecl;
1914 if (NewBuiltinID == BuiltinID)
1915 NewBuiltinDecl = FDecl;
1916 else {
1917 // Perform builtin lookup to avoid redeclaring it.
1918 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1919 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1920 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1921 assert(Res.getFoundDecl());
1922 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001923 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001924 return ExprError();
1925 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001926
John McCallcf142162010-08-07 06:22:56 +00001927 // The first argument --- the pointer --- has a fixed type; we
1928 // deduce the types of the rest of the arguments accordingly. Walk
1929 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001930 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001931 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001932
Chris Lattnerdc046542009-05-08 06:58:22 +00001933 // GCC does an implicit conversion to the pointer or integer ValType. This
1934 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001935 // Initialize the argument.
1936 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1937 ValType, /*consume*/ false);
1938 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001939 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001940 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001941
Chris Lattnerdc046542009-05-08 06:58:22 +00001942 // Okay, we have something that *can* be converted to the right type. Check
1943 // to see if there is a potentially weird extension going on here. This can
1944 // happen when you do an atomic operation on something like an char* and
1945 // pass in 42. The 42 gets converted to char. This is even more strange
1946 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001947 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001948 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001949 }
Mike Stump11289f42009-09-09 15:08:12 +00001950
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001951 ASTContext& Context = this->getASTContext();
1952
1953 // Create a new DeclRefExpr to refer to the new decl.
1954 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1955 Context,
1956 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001957 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001958 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001959 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001960 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001961 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001962 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001963
Chris Lattnerdc046542009-05-08 06:58:22 +00001964 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001965 // FIXME: This loses syntactic information.
1966 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1967 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1968 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001969 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001970
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001971 // Change the result type of the call to match the original value type. This
1972 // is arbitrary, but the codegen for these builtins ins design to handle it
1973 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001974 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001975
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001976 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001977}
1978
Chris Lattner6436fb62009-02-18 06:01:06 +00001979/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001980/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001981/// Note: It might also make sense to do the UTF-16 conversion here (would
1982/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001983bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001984 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001985 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1986
Douglas Gregorfb65e592011-07-27 05:40:30 +00001987 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001988 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1989 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001990 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001991 }
Mike Stump11289f42009-09-09 15:08:12 +00001992
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001993 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001994 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001995 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001996 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001997 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001998 UTF16 *ToPtr = &ToBuf[0];
1999
2000 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2001 &ToPtr, ToPtr + NumBytes,
2002 strictConversion);
2003 // Check for conversion failure.
2004 if (Result != conversionOK)
2005 Diag(Arg->getLocStart(),
2006 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2007 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002008 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002009}
2010
Chris Lattnere202e6a2007-12-20 00:05:45 +00002011/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2012/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00002013bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2014 Expr *Fn = TheCall->getCallee();
2015 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002016 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002017 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002018 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2019 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002020 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002021 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002022 return true;
2023 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002024
2025 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002026 return Diag(TheCall->getLocEnd(),
2027 diag::err_typecheck_call_too_few_args_at_least)
2028 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002029 }
2030
John McCall29ad95b2011-08-27 01:09:30 +00002031 // Type-check the first argument normally.
2032 if (checkBuiltinArgument(*this, TheCall, 0))
2033 return true;
2034
Chris Lattnere202e6a2007-12-20 00:05:45 +00002035 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002036 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002037 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002038 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002039 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002040 else if (FunctionDecl *FD = getCurFunctionDecl())
2041 isVariadic = FD->isVariadic();
2042 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002043 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002044
Chris Lattnere202e6a2007-12-20 00:05:45 +00002045 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002046 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2047 return true;
2048 }
Mike Stump11289f42009-09-09 15:08:12 +00002049
Chris Lattner43be2e62007-12-19 23:59:04 +00002050 // Verify that the second argument to the builtin is the last argument of the
2051 // current function or method.
2052 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002053 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002054
Nico Weber9eea7642013-05-24 23:31:57 +00002055 // These are valid if SecondArgIsLastNamedArgument is false after the next
2056 // block.
2057 QualType Type;
2058 SourceLocation ParamLoc;
2059
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002060 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2061 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002062 // FIXME: This isn't correct for methods (results in bogus warning).
2063 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002064 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002065 if (CurBlock)
2066 LastArg = *(CurBlock->TheDecl->param_end()-1);
2067 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002068 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002069 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002070 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002071 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002072
2073 Type = PV->getType();
2074 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002075 }
2076 }
Mike Stump11289f42009-09-09 15:08:12 +00002077
Chris Lattner43be2e62007-12-19 23:59:04 +00002078 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002079 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002080 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002081 else if (Type->isReferenceType()) {
2082 Diag(Arg->getLocStart(),
2083 diag::warn_va_start_of_reference_type_is_undefined);
2084 Diag(ParamLoc, diag::note_parameter_type) << Type;
2085 }
2086
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002087 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002088 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002089}
Chris Lattner43be2e62007-12-19 23:59:04 +00002090
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002091bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2092 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2093 // const char *named_addr);
2094
2095 Expr *Func = Call->getCallee();
2096
2097 if (Call->getNumArgs() < 3)
2098 return Diag(Call->getLocEnd(),
2099 diag::err_typecheck_call_too_few_args_at_least)
2100 << 0 /*function call*/ << 3 << Call->getNumArgs();
2101
2102 // Determine whether the current function is variadic or not.
2103 bool IsVariadic;
2104 if (BlockScopeInfo *CurBlock = getCurBlock())
2105 IsVariadic = CurBlock->TheDecl->isVariadic();
2106 else if (FunctionDecl *FD = getCurFunctionDecl())
2107 IsVariadic = FD->isVariadic();
2108 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2109 IsVariadic = MD->isVariadic();
2110 else
2111 llvm_unreachable("unexpected statement type");
2112
2113 if (!IsVariadic) {
2114 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2115 return true;
2116 }
2117
2118 // Type-check the first argument normally.
2119 if (checkBuiltinArgument(*this, Call, 0))
2120 return true;
2121
2122 static const struct {
2123 unsigned ArgNo;
2124 QualType Type;
2125 } ArgumentTypes[] = {
2126 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2127 { 2, Context.getSizeType() },
2128 };
2129
2130 for (const auto &AT : ArgumentTypes) {
2131 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2132 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2133 continue;
2134 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2135 << Arg->getType() << AT.Type << 1 /* different class */
2136 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2137 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2138 }
2139
2140 return false;
2141}
2142
Chris Lattner2da14fb2007-12-20 00:26:33 +00002143/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2144/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002145bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2146 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002147 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002148 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002149 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002150 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002151 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002152 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002153 << SourceRange(TheCall->getArg(2)->getLocStart(),
2154 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002155
John Wiegley01296292011-04-08 18:41:53 +00002156 ExprResult OrigArg0 = TheCall->getArg(0);
2157 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002158
Chris Lattner2da14fb2007-12-20 00:26:33 +00002159 // Do standard promotions between the two arguments, returning their common
2160 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002161 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002162 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2163 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002164
2165 // Make sure any conversions are pushed back into the call; this is
2166 // type safe since unordered compare builtins are declared as "_Bool
2167 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002168 TheCall->setArg(0, OrigArg0.get());
2169 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002170
John Wiegley01296292011-04-08 18:41:53 +00002171 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002172 return false;
2173
Chris Lattner2da14fb2007-12-20 00:26:33 +00002174 // If the common type isn't a real floating type, then the arguments were
2175 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002176 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002177 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002178 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002179 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2180 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002181
Chris Lattner2da14fb2007-12-20 00:26:33 +00002182 return false;
2183}
2184
Benjamin Kramer634fc102010-02-15 22:42:31 +00002185/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2186/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002187/// to check everything. We expect the last argument to be a floating point
2188/// value.
2189bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2190 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002191 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002192 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002193 if (TheCall->getNumArgs() > NumArgs)
2194 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002195 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002196 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002197 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002198 (*(TheCall->arg_end()-1))->getLocEnd());
2199
Benjamin Kramer64aae502010-02-16 10:07:31 +00002200 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002201
Eli Friedman7e4faac2009-08-31 20:06:00 +00002202 if (OrigArg->isTypeDependent())
2203 return false;
2204
Chris Lattner68784ef2010-05-06 05:50:07 +00002205 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002206 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002207 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002208 diag::err_typecheck_call_invalid_unary_fp)
2209 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002210
Chris Lattner68784ef2010-05-06 05:50:07 +00002211 // If this is an implicit conversion from float -> double, remove it.
2212 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2213 Expr *CastArg = Cast->getSubExpr();
2214 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2215 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2216 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002217 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002218 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002219 }
2220 }
2221
Eli Friedman7e4faac2009-08-31 20:06:00 +00002222 return false;
2223}
2224
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002225/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2226// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002227ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002228 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002229 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002230 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002231 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2232 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002233
Nate Begemana0110022010-06-08 00:16:34 +00002234 // Determine which of the following types of shufflevector we're checking:
2235 // 1) unary, vector mask: (lhs, mask)
2236 // 2) binary, vector mask: (lhs, rhs, mask)
2237 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2238 QualType resType = TheCall->getArg(0)->getType();
2239 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002240
Douglas Gregorc25f7662009-05-19 22:10:17 +00002241 if (!TheCall->getArg(0)->isTypeDependent() &&
2242 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002243 QualType LHSType = TheCall->getArg(0)->getType();
2244 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002245
Craig Topperbaca3892013-07-29 06:47:04 +00002246 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2247 return ExprError(Diag(TheCall->getLocStart(),
2248 diag::err_shufflevector_non_vector)
2249 << SourceRange(TheCall->getArg(0)->getLocStart(),
2250 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002251
Nate Begemana0110022010-06-08 00:16:34 +00002252 numElements = LHSType->getAs<VectorType>()->getNumElements();
2253 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002254
Nate Begemana0110022010-06-08 00:16:34 +00002255 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2256 // with mask. If so, verify that RHS is an integer vector type with the
2257 // same number of elts as lhs.
2258 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002259 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002260 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002261 return ExprError(Diag(TheCall->getLocStart(),
2262 diag::err_shufflevector_incompatible_vector)
2263 << SourceRange(TheCall->getArg(1)->getLocStart(),
2264 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002265 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002266 return ExprError(Diag(TheCall->getLocStart(),
2267 diag::err_shufflevector_incompatible_vector)
2268 << SourceRange(TheCall->getArg(0)->getLocStart(),
2269 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002270 } else if (numElements != numResElements) {
2271 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002272 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002273 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002274 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002275 }
2276
2277 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002278 if (TheCall->getArg(i)->isTypeDependent() ||
2279 TheCall->getArg(i)->isValueDependent())
2280 continue;
2281
Nate Begemana0110022010-06-08 00:16:34 +00002282 llvm::APSInt Result(32);
2283 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2284 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002285 diag::err_shufflevector_nonconstant_argument)
2286 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002287
Craig Topper50ad5b72013-08-03 17:40:38 +00002288 // Allow -1 which will be translated to undef in the IR.
2289 if (Result.isSigned() && Result.isAllOnesValue())
2290 continue;
2291
Chris Lattner7ab824e2008-08-10 02:05:13 +00002292 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002293 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002294 diag::err_shufflevector_argument_too_large)
2295 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002296 }
2297
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002298 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002299
Chris Lattner7ab824e2008-08-10 02:05:13 +00002300 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002301 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002302 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002303 }
2304
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002305 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2306 TheCall->getCallee()->getLocStart(),
2307 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002308}
Chris Lattner43be2e62007-12-19 23:59:04 +00002309
Hal Finkelc4d7c822013-09-18 03:29:45 +00002310/// SemaConvertVectorExpr - Handle __builtin_convertvector
2311ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2312 SourceLocation BuiltinLoc,
2313 SourceLocation RParenLoc) {
2314 ExprValueKind VK = VK_RValue;
2315 ExprObjectKind OK = OK_Ordinary;
2316 QualType DstTy = TInfo->getType();
2317 QualType SrcTy = E->getType();
2318
2319 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2320 return ExprError(Diag(BuiltinLoc,
2321 diag::err_convertvector_non_vector)
2322 << E->getSourceRange());
2323 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2324 return ExprError(Diag(BuiltinLoc,
2325 diag::err_convertvector_non_vector_type));
2326
2327 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2328 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2329 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2330 if (SrcElts != DstElts)
2331 return ExprError(Diag(BuiltinLoc,
2332 diag::err_convertvector_incompatible_vector)
2333 << E->getSourceRange());
2334 }
2335
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002336 return new (Context)
2337 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002338}
2339
Daniel Dunbarb7257262008-07-21 22:59:13 +00002340/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2341// This is declared to take (const void*, ...) and can take two
2342// optional constant int args.
2343bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002344 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002345
Chris Lattner3b054132008-11-19 05:08:23 +00002346 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002347 return Diag(TheCall->getLocEnd(),
2348 diag::err_typecheck_call_too_many_args_at_most)
2349 << 0 /*function call*/ << 3 << NumArgs
2350 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002351
2352 // Argument 0 is checked for us and the remaining arguments must be
2353 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002354 for (unsigned i = 1; i != NumArgs; ++i)
2355 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002356 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002357
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002358 return false;
2359}
2360
Hal Finkelf0417332014-07-17 14:25:55 +00002361/// SemaBuiltinAssume - Handle __assume (MS Extension).
2362// __assume does not evaluate its arguments, and should warn if its argument
2363// has side effects.
2364bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2365 Expr *Arg = TheCall->getArg(0);
2366 if (Arg->isInstantiationDependent()) return false;
2367
2368 if (Arg->HasSideEffects(Context))
2369 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002370 << Arg->getSourceRange()
2371 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2372
2373 return false;
2374}
2375
2376/// Handle __builtin_assume_aligned. This is declared
2377/// as (const void*, size_t, ...) and can take one optional constant int arg.
2378bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2379 unsigned NumArgs = TheCall->getNumArgs();
2380
2381 if (NumArgs > 3)
2382 return Diag(TheCall->getLocEnd(),
2383 diag::err_typecheck_call_too_many_args_at_most)
2384 << 0 /*function call*/ << 3 << NumArgs
2385 << TheCall->getSourceRange();
2386
2387 // The alignment must be a constant integer.
2388 Expr *Arg = TheCall->getArg(1);
2389
2390 // We can't check the value of a dependent argument.
2391 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2392 llvm::APSInt Result;
2393 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2394 return true;
2395
2396 if (!Result.isPowerOf2())
2397 return Diag(TheCall->getLocStart(),
2398 diag::err_alignment_not_power_of_two)
2399 << Arg->getSourceRange();
2400 }
2401
2402 if (NumArgs > 2) {
2403 ExprResult Arg(TheCall->getArg(2));
2404 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2405 Context.getSizeType(), false);
2406 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2407 if (Arg.isInvalid()) return true;
2408 TheCall->setArg(2, Arg.get());
2409 }
Hal Finkelf0417332014-07-17 14:25:55 +00002410
2411 return false;
2412}
2413
Eric Christopher8d0c6212010-04-17 02:26:23 +00002414/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2415/// TheCall is a constant expression.
2416bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2417 llvm::APSInt &Result) {
2418 Expr *Arg = TheCall->getArg(ArgNum);
2419 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2420 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2421
2422 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2423
2424 if (!Arg->isIntegerConstantExpr(Result, Context))
2425 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002426 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002427
Chris Lattnerd545ad12009-09-23 06:06:36 +00002428 return false;
2429}
2430
Richard Sandiford28940af2014-04-16 08:47:51 +00002431/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2432/// TheCall is a constant expression in the range [Low, High].
2433bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2434 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002435 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002436
2437 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002438 Expr *Arg = TheCall->getArg(ArgNum);
2439 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002440 return false;
2441
Eric Christopher8d0c6212010-04-17 02:26:23 +00002442 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002443 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002444 return true;
2445
Richard Sandiford28940af2014-04-16 08:47:51 +00002446 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002447 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002448 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002449
2450 return false;
2451}
2452
Eli Friedmanc97d0142009-05-03 06:04:26 +00002453/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002454/// This checks that val is a constant 1.
2455bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2456 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002457 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002458
Eric Christopher8d0c6212010-04-17 02:26:23 +00002459 // TODO: This is less than ideal. Overload this to take a value.
2460 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2461 return true;
2462
2463 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002464 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2465 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2466
2467 return false;
2468}
2469
Richard Smithd7293d72013-08-05 18:49:43 +00002470namespace {
2471enum StringLiteralCheckType {
2472 SLCT_NotALiteral,
2473 SLCT_UncheckedLiteral,
2474 SLCT_CheckedLiteral
2475};
2476}
2477
Richard Smith55ce3522012-06-25 20:30:08 +00002478// Determine if an expression is a string literal or constant string.
2479// If this function returns false on the arguments to a function expecting a
2480// format string, we will usually need to emit a warning.
2481// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002482static StringLiteralCheckType
2483checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2484 bool HasVAListArg, unsigned format_idx,
2485 unsigned firstDataArg, Sema::FormatStringType Type,
2486 Sema::VariadicCallType CallType, bool InFunctionCall,
2487 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002488 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002489 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002490 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002491
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002492 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002493
Richard Smithd7293d72013-08-05 18:49:43 +00002494 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002495 // Technically -Wformat-nonliteral does not warn about this case.
2496 // The behavior of printf and friends in this case is implementation
2497 // dependent. Ideally if the format string cannot be null then
2498 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002499 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002500
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002501 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002502 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002503 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002504 // The expression is a literal if both sub-expressions were, and it was
2505 // completely checked only if both sub-expressions were checked.
2506 const AbstractConditionalOperator *C =
2507 cast<AbstractConditionalOperator>(E);
2508 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002509 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002510 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002511 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002512 if (Left == SLCT_NotALiteral)
2513 return SLCT_NotALiteral;
2514 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002515 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002516 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002517 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002518 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002519 }
2520
2521 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002522 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2523 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002524 }
2525
John McCallc07a0c72011-02-17 10:25:35 +00002526 case Stmt::OpaqueValueExprClass:
2527 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2528 E = src;
2529 goto tryAgain;
2530 }
Richard Smith55ce3522012-06-25 20:30:08 +00002531 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002532
Ted Kremeneka8890832011-02-24 23:03:04 +00002533 case Stmt::PredefinedExprClass:
2534 // While __func__, etc., are technically not string literals, they
2535 // cannot contain format specifiers and thus are not a security
2536 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002537 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002538
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002539 case Stmt::DeclRefExprClass: {
2540 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002541
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002542 // As an exception, do not flag errors for variables binding to
2543 // const string literals.
2544 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2545 bool isConstant = false;
2546 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002547
Richard Smithd7293d72013-08-05 18:49:43 +00002548 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2549 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002550 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002551 isConstant = T.isConstant(S.Context) &&
2552 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002553 } else if (T->isObjCObjectPointerType()) {
2554 // In ObjC, there is usually no "const ObjectPointer" type,
2555 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002556 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002557 }
Mike Stump11289f42009-09-09 15:08:12 +00002558
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002559 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002560 if (const Expr *Init = VD->getAnyInitializer()) {
2561 // Look through initializers like const char c[] = { "foo" }
2562 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2563 if (InitList->isStringLiteralInit())
2564 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2565 }
Richard Smithd7293d72013-08-05 18:49:43 +00002566 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002567 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002568 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002569 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002570 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002571 }
Mike Stump11289f42009-09-09 15:08:12 +00002572
Anders Carlssonb012ca92009-06-28 19:55:58 +00002573 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2574 // special check to see if the format string is a function parameter
2575 // of the function calling the printf function. If the function
2576 // has an attribute indicating it is a printf-like function, then we
2577 // should suppress warnings concerning non-literals being used in a call
2578 // to a vprintf function. For example:
2579 //
2580 // void
2581 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2582 // va_list ap;
2583 // va_start(ap, fmt);
2584 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2585 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002586 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002587 if (HasVAListArg) {
2588 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2589 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2590 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002591 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002592 // adjust for implicit parameter
2593 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2594 if (MD->isInstance())
2595 ++PVIndex;
2596 // We also check if the formats are compatible.
2597 // We can't pass a 'scanf' string to a 'printf' function.
2598 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002599 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002600 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002601 }
2602 }
2603 }
2604 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002605 }
Mike Stump11289f42009-09-09 15:08:12 +00002606
Richard Smith55ce3522012-06-25 20:30:08 +00002607 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002608 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002609
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002610 case Stmt::CallExprClass:
2611 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002612 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002613 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2614 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2615 unsigned ArgIndex = FA->getFormatIdx();
2616 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2617 if (MD->isInstance())
2618 --ArgIndex;
2619 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002620
Richard Smithd7293d72013-08-05 18:49:43 +00002621 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002622 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002623 Type, CallType, InFunctionCall,
2624 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002625 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2626 unsigned BuiltinID = FD->getBuiltinID();
2627 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2628 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2629 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002630 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002631 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002632 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002633 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002634 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002635 }
2636 }
Mike Stump11289f42009-09-09 15:08:12 +00002637
Richard Smith55ce3522012-06-25 20:30:08 +00002638 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002639 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002640 case Stmt::ObjCStringLiteralClass:
2641 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002642 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002643
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002644 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002645 StrE = ObjCFExpr->getString();
2646 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002647 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002648
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002649 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002650 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2651 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002652 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002653 }
Mike Stump11289f42009-09-09 15:08:12 +00002654
Richard Smith55ce3522012-06-25 20:30:08 +00002655 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002656 }
Mike Stump11289f42009-09-09 15:08:12 +00002657
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002658 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002659 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002660 }
2661}
2662
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002663Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002664 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002665 .Case("scanf", FST_Scanf)
2666 .Cases("printf", "printf0", FST_Printf)
2667 .Cases("NSString", "CFString", FST_NSString)
2668 .Case("strftime", FST_Strftime)
2669 .Case("strfmon", FST_Strfmon)
2670 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2671 .Default(FST_Unknown);
2672}
2673
Jordan Rose3e0ec582012-07-19 18:10:23 +00002674/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002675/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002676/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002677bool Sema::CheckFormatArguments(const FormatAttr *Format,
2678 ArrayRef<const Expr *> Args,
2679 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002680 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002681 SourceLocation Loc, SourceRange Range,
2682 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002683 FormatStringInfo FSI;
2684 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002685 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002686 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002687 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002688 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002689}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002690
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002691bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002692 bool HasVAListArg, unsigned format_idx,
2693 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002694 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002695 SourceLocation Loc, SourceRange Range,
2696 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002697 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002698 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002699 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002700 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002701 }
Mike Stump11289f42009-09-09 15:08:12 +00002702
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002703 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002704
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002705 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002706 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002707 // Dynamically generated format strings are difficult to
2708 // automatically vet at compile time. Requiring that format strings
2709 // are string literals: (1) permits the checking of format strings by
2710 // the compiler and thereby (2) can practically remove the source of
2711 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002712
Mike Stump11289f42009-09-09 15:08:12 +00002713 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002714 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002715 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002716 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002717 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002718 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2719 format_idx, firstDataArg, Type, CallType,
2720 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002721 if (CT != SLCT_NotALiteral)
2722 // Literal format string found, check done!
2723 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002724
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002725 // Strftime is particular as it always uses a single 'time' argument,
2726 // so it is safe to pass a non-literal string.
2727 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002728 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002729
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002730 // Do not emit diag when the string param is a macro expansion and the
2731 // format is either NSString or CFString. This is a hack to prevent
2732 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2733 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002734 if (Type == FST_NSString &&
2735 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002736 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002737
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002738 // If there are no arguments specified, warn with -Wformat-security, otherwise
2739 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002740 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002741 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002742 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002743 << OrigFormatExpr->getSourceRange();
2744 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002745 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002746 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002747 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002748 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002749}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002750
Ted Kremenekab278de2010-01-28 23:39:18 +00002751namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002752class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2753protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002754 Sema &S;
2755 const StringLiteral *FExpr;
2756 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002757 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002758 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002759 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002760 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002761 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002762 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002763 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002764 bool usesPositionalArgs;
2765 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002766 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002767 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002768 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002769public:
Ted Kremenek02087932010-07-16 02:11:22 +00002770 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002771 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002772 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002773 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002774 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002775 Sema::VariadicCallType callType,
2776 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002777 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002778 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2779 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002780 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002781 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002782 inFunctionCall(inFunctionCall), CallType(callType),
2783 CheckedVarArgs(CheckedVarArgs) {
2784 CoveredArgs.resize(numDataArgs);
2785 CoveredArgs.reset();
2786 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002787
Ted Kremenek019d2242010-01-29 01:50:07 +00002788 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002789
Ted Kremenek02087932010-07-16 02:11:22 +00002790 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002791 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002792
Jordan Rose92303592012-09-08 04:00:03 +00002793 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002794 const analyze_format_string::FormatSpecifier &FS,
2795 const analyze_format_string::ConversionSpecifier &CS,
2796 const char *startSpecifier, unsigned specifierLen,
2797 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002798
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002799 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002800 const analyze_format_string::FormatSpecifier &FS,
2801 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002802
2803 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002804 const analyze_format_string::ConversionSpecifier &CS,
2805 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002806
Craig Toppere14c0f82014-03-12 04:55:44 +00002807 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002808
Craig Toppere14c0f82014-03-12 04:55:44 +00002809 void HandleInvalidPosition(const char *startSpecifier,
2810 unsigned specifierLen,
2811 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002812
Craig Toppere14c0f82014-03-12 04:55:44 +00002813 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002814
Craig Toppere14c0f82014-03-12 04:55:44 +00002815 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002816
Richard Trieu03cf7b72011-10-28 00:41:25 +00002817 template <typename Range>
2818 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2819 const Expr *ArgumentExpr,
2820 PartialDiagnostic PDiag,
2821 SourceLocation StringLoc,
2822 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002823 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002824
Ted Kremenek02087932010-07-16 02:11:22 +00002825protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002826 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2827 const char *startSpec,
2828 unsigned specifierLen,
2829 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002830
2831 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2832 const char *startSpec,
2833 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002834
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002835 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002836 CharSourceRange getSpecifierRange(const char *startSpecifier,
2837 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002838 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002839
Ted Kremenek5739de72010-01-29 01:06:55 +00002840 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002841
2842 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2843 const analyze_format_string::ConversionSpecifier &CS,
2844 const char *startSpecifier, unsigned specifierLen,
2845 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002846
2847 template <typename Range>
2848 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2849 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002850 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002851};
2852}
2853
Ted Kremenek02087932010-07-16 02:11:22 +00002854SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002855 return OrigFormatExpr->getSourceRange();
2856}
2857
Ted Kremenek02087932010-07-16 02:11:22 +00002858CharSourceRange CheckFormatHandler::
2859getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002860 SourceLocation Start = getLocationOfByte(startSpecifier);
2861 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2862
2863 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002864 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002865
2866 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002867}
2868
Ted Kremenek02087932010-07-16 02:11:22 +00002869SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002870 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002871}
2872
Ted Kremenek02087932010-07-16 02:11:22 +00002873void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2874 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002875 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2876 getLocationOfByte(startSpecifier),
2877 /*IsStringLocation*/true,
2878 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002879}
2880
Jordan Rose92303592012-09-08 04:00:03 +00002881void CheckFormatHandler::HandleInvalidLengthModifier(
2882 const analyze_format_string::FormatSpecifier &FS,
2883 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002884 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002885 using namespace analyze_format_string;
2886
2887 const LengthModifier &LM = FS.getLengthModifier();
2888 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2889
2890 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002891 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002892 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002893 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002894 getLocationOfByte(LM.getStart()),
2895 /*IsStringLocation*/true,
2896 getSpecifierRange(startSpecifier, specifierLen));
2897
2898 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2899 << FixedLM->toString()
2900 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2901
2902 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002903 FixItHint Hint;
2904 if (DiagID == diag::warn_format_nonsensical_length)
2905 Hint = FixItHint::CreateRemoval(LMRange);
2906
2907 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002908 getLocationOfByte(LM.getStart()),
2909 /*IsStringLocation*/true,
2910 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002911 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002912 }
2913}
2914
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002915void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002916 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002917 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002918 using namespace analyze_format_string;
2919
2920 const LengthModifier &LM = FS.getLengthModifier();
2921 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2922
2923 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002924 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002925 if (FixedLM) {
2926 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2927 << LM.toString() << 0,
2928 getLocationOfByte(LM.getStart()),
2929 /*IsStringLocation*/true,
2930 getSpecifierRange(startSpecifier, specifierLen));
2931
2932 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2933 << FixedLM->toString()
2934 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2935
2936 } else {
2937 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2938 << LM.toString() << 0,
2939 getLocationOfByte(LM.getStart()),
2940 /*IsStringLocation*/true,
2941 getSpecifierRange(startSpecifier, specifierLen));
2942 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002943}
2944
2945void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2946 const analyze_format_string::ConversionSpecifier &CS,
2947 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002948 using namespace analyze_format_string;
2949
2950 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002951 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002952 if (FixedCS) {
2953 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2954 << CS.toString() << /*conversion specifier*/1,
2955 getLocationOfByte(CS.getStart()),
2956 /*IsStringLocation*/true,
2957 getSpecifierRange(startSpecifier, specifierLen));
2958
2959 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2960 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2961 << FixedCS->toString()
2962 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2963 } else {
2964 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2965 << CS.toString() << /*conversion specifier*/1,
2966 getLocationOfByte(CS.getStart()),
2967 /*IsStringLocation*/true,
2968 getSpecifierRange(startSpecifier, specifierLen));
2969 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002970}
2971
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002972void CheckFormatHandler::HandlePosition(const char *startPos,
2973 unsigned posLen) {
2974 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2975 getLocationOfByte(startPos),
2976 /*IsStringLocation*/true,
2977 getSpecifierRange(startPos, posLen));
2978}
2979
Ted Kremenekd1668192010-02-27 01:41:03 +00002980void
Ted Kremenek02087932010-07-16 02:11:22 +00002981CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2982 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002983 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2984 << (unsigned) p,
2985 getLocationOfByte(startPos), /*IsStringLocation*/true,
2986 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002987}
2988
Ted Kremenek02087932010-07-16 02:11:22 +00002989void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002990 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002991 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2992 getLocationOfByte(startPos),
2993 /*IsStringLocation*/true,
2994 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002995}
2996
Ted Kremenek02087932010-07-16 02:11:22 +00002997void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002998 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002999 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003000 EmitFormatDiagnostic(
3001 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3002 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3003 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003004 }
Ted Kremenek02087932010-07-16 02:11:22 +00003005}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003006
Jordan Rose58bbe422012-07-19 18:10:08 +00003007// Note that this may return NULL if there was an error parsing or building
3008// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003009const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003010 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003011}
3012
3013void CheckFormatHandler::DoneProcessing() {
3014 // Does the number of data arguments exceed the number of
3015 // format conversions in the format string?
3016 if (!HasVAListArg) {
3017 // Find any arguments that weren't covered.
3018 CoveredArgs.flip();
3019 signed notCoveredArg = CoveredArgs.find_first();
3020 if (notCoveredArg >= 0) {
3021 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003022 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3023 SourceLocation Loc = E->getLocStart();
3024 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3025 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3026 Loc, /*IsStringLocation*/false,
3027 getFormatStringRange());
3028 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003029 }
Ted Kremenek02087932010-07-16 02:11:22 +00003030 }
3031 }
3032}
3033
Ted Kremenekce815422010-07-19 21:25:57 +00003034bool
3035CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3036 SourceLocation Loc,
3037 const char *startSpec,
3038 unsigned specifierLen,
3039 const char *csStart,
3040 unsigned csLen) {
3041
3042 bool keepGoing = true;
3043 if (argIndex < NumDataArgs) {
3044 // Consider the argument coverered, even though the specifier doesn't
3045 // make sense.
3046 CoveredArgs.set(argIndex);
3047 }
3048 else {
3049 // If argIndex exceeds the number of data arguments we
3050 // don't issue a warning because that is just a cascade of warnings (and
3051 // they may have intended '%%' anyway). We don't want to continue processing
3052 // the format string after this point, however, as we will like just get
3053 // gibberish when trying to match arguments.
3054 keepGoing = false;
3055 }
3056
Richard Trieu03cf7b72011-10-28 00:41:25 +00003057 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3058 << StringRef(csStart, csLen),
3059 Loc, /*IsStringLocation*/true,
3060 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003061
3062 return keepGoing;
3063}
3064
Richard Trieu03cf7b72011-10-28 00:41:25 +00003065void
3066CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3067 const char *startSpec,
3068 unsigned specifierLen) {
3069 EmitFormatDiagnostic(
3070 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3071 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3072}
3073
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003074bool
3075CheckFormatHandler::CheckNumArgs(
3076 const analyze_format_string::FormatSpecifier &FS,
3077 const analyze_format_string::ConversionSpecifier &CS,
3078 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3079
3080 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003081 PartialDiagnostic PDiag = FS.usesPositionalArg()
3082 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3083 << (argIndex+1) << NumDataArgs)
3084 : S.PDiag(diag::warn_printf_insufficient_data_args);
3085 EmitFormatDiagnostic(
3086 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3087 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003088 return false;
3089 }
3090 return true;
3091}
3092
Richard Trieu03cf7b72011-10-28 00:41:25 +00003093template<typename Range>
3094void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3095 SourceLocation Loc,
3096 bool IsStringLocation,
3097 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003098 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003099 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003100 Loc, IsStringLocation, StringRange, FixIt);
3101}
3102
3103/// \brief If the format string is not within the funcion call, emit a note
3104/// so that the function call and string are in diagnostic messages.
3105///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003106/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003107/// call and only one diagnostic message will be produced. Otherwise, an
3108/// extra note will be emitted pointing to location of the format string.
3109///
3110/// \param ArgumentExpr the expression that is passed as the format string
3111/// argument in the function call. Used for getting locations when two
3112/// diagnostics are emitted.
3113///
3114/// \param PDiag the callee should already have provided any strings for the
3115/// diagnostic message. This function only adds locations and fixits
3116/// to diagnostics.
3117///
3118/// \param Loc primary location for diagnostic. If two diagnostics are
3119/// required, one will be at Loc and a new SourceLocation will be created for
3120/// the other one.
3121///
3122/// \param IsStringLocation if true, Loc points to the format string should be
3123/// used for the note. Otherwise, Loc points to the argument list and will
3124/// be used with PDiag.
3125///
3126/// \param StringRange some or all of the string to highlight. This is
3127/// templated so it can accept either a CharSourceRange or a SourceRange.
3128///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003129/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003130template<typename Range>
3131void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3132 const Expr *ArgumentExpr,
3133 PartialDiagnostic PDiag,
3134 SourceLocation Loc,
3135 bool IsStringLocation,
3136 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003137 ArrayRef<FixItHint> FixIt) {
3138 if (InFunctionCall) {
3139 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3140 D << StringRange;
3141 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3142 I != E; ++I) {
3143 D << *I;
3144 }
3145 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003146 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3147 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003148
3149 const Sema::SemaDiagnosticBuilder &Note =
3150 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3151 diag::note_format_string_defined);
3152
3153 Note << StringRange;
3154 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3155 I != E; ++I) {
3156 Note << *I;
3157 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00003158 }
3159}
3160
Ted Kremenek02087932010-07-16 02:11:22 +00003161//===--- CHECK: Printf format string checking ------------------------------===//
3162
3163namespace {
3164class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003165 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003166public:
3167 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3168 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003169 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003170 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003171 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003172 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003173 Sema::VariadicCallType CallType,
3174 llvm::SmallBitVector &CheckedVarArgs)
3175 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3176 numDataArgs, beg, hasVAListArg, Args,
3177 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3178 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003179 {}
3180
Craig Toppere14c0f82014-03-12 04:55:44 +00003181
Ted Kremenek02087932010-07-16 02:11:22 +00003182 bool HandleInvalidPrintfConversionSpecifier(
3183 const analyze_printf::PrintfSpecifier &FS,
3184 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003185 unsigned specifierLen) override;
3186
Ted Kremenek02087932010-07-16 02:11:22 +00003187 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3188 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003189 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003190 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3191 const char *StartSpecifier,
3192 unsigned SpecifierLen,
3193 const Expr *E);
3194
Ted Kremenek02087932010-07-16 02:11:22 +00003195 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3196 const char *startSpecifier, unsigned specifierLen);
3197 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3198 const analyze_printf::OptionalAmount &Amt,
3199 unsigned type,
3200 const char *startSpecifier, unsigned specifierLen);
3201 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3202 const analyze_printf::OptionalFlag &flag,
3203 const char *startSpecifier, unsigned specifierLen);
3204 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3205 const analyze_printf::OptionalFlag &ignoredFlag,
3206 const analyze_printf::OptionalFlag &flag,
3207 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003208 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003209 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003210
Ted Kremenek02087932010-07-16 02:11:22 +00003211};
3212}
3213
3214bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3215 const analyze_printf::PrintfSpecifier &FS,
3216 const char *startSpecifier,
3217 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003218 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003219 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003220
Ted Kremenekce815422010-07-19 21:25:57 +00003221 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3222 getLocationOfByte(CS.getStart()),
3223 startSpecifier, specifierLen,
3224 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003225}
3226
Ted Kremenek02087932010-07-16 02:11:22 +00003227bool CheckPrintfHandler::HandleAmount(
3228 const analyze_format_string::OptionalAmount &Amt,
3229 unsigned k, const char *startSpecifier,
3230 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003231
3232 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003233 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003234 unsigned argIndex = Amt.getArgIndex();
3235 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003236 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3237 << k,
3238 getLocationOfByte(Amt.getStart()),
3239 /*IsStringLocation*/true,
3240 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003241 // Don't do any more checking. We will just emit
3242 // spurious errors.
3243 return false;
3244 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003245
Ted Kremenek5739de72010-01-29 01:06:55 +00003246 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003247 // Although not in conformance with C99, we also allow the argument to be
3248 // an 'unsigned int' as that is a reasonably safe case. GCC also
3249 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003250 CoveredArgs.set(argIndex);
3251 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003252 if (!Arg)
3253 return false;
3254
Ted Kremenek5739de72010-01-29 01:06:55 +00003255 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003256
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003257 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3258 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003259
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003260 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003261 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003262 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003263 << T << Arg->getSourceRange(),
3264 getLocationOfByte(Amt.getStart()),
3265 /*IsStringLocation*/true,
3266 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003267 // Don't do any more checking. We will just emit
3268 // spurious errors.
3269 return false;
3270 }
3271 }
3272 }
3273 return true;
3274}
Ted Kremenek5739de72010-01-29 01:06:55 +00003275
Tom Careb49ec692010-06-17 19:00:27 +00003276void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003277 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003278 const analyze_printf::OptionalAmount &Amt,
3279 unsigned type,
3280 const char *startSpecifier,
3281 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003282 const analyze_printf::PrintfConversionSpecifier &CS =
3283 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003284
Richard Trieu03cf7b72011-10-28 00:41:25 +00003285 FixItHint fixit =
3286 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3287 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3288 Amt.getConstantLength()))
3289 : FixItHint();
3290
3291 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3292 << type << CS.toString(),
3293 getLocationOfByte(Amt.getStart()),
3294 /*IsStringLocation*/true,
3295 getSpecifierRange(startSpecifier, specifierLen),
3296 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003297}
3298
Ted Kremenek02087932010-07-16 02:11:22 +00003299void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003300 const analyze_printf::OptionalFlag &flag,
3301 const char *startSpecifier,
3302 unsigned specifierLen) {
3303 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003304 const analyze_printf::PrintfConversionSpecifier &CS =
3305 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003306 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3307 << flag.toString() << CS.toString(),
3308 getLocationOfByte(flag.getPosition()),
3309 /*IsStringLocation*/true,
3310 getSpecifierRange(startSpecifier, specifierLen),
3311 FixItHint::CreateRemoval(
3312 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003313}
3314
3315void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003316 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003317 const analyze_printf::OptionalFlag &ignoredFlag,
3318 const analyze_printf::OptionalFlag &flag,
3319 const char *startSpecifier,
3320 unsigned specifierLen) {
3321 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003322 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3323 << ignoredFlag.toString() << flag.toString(),
3324 getLocationOfByte(ignoredFlag.getPosition()),
3325 /*IsStringLocation*/true,
3326 getSpecifierRange(startSpecifier, specifierLen),
3327 FixItHint::CreateRemoval(
3328 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003329}
3330
Richard Smith55ce3522012-06-25 20:30:08 +00003331// Determines if the specified is a C++ class or struct containing
3332// a member with the specified name and kind (e.g. a CXXMethodDecl named
3333// "c_str()").
3334template<typename MemberKind>
3335static llvm::SmallPtrSet<MemberKind*, 1>
3336CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3337 const RecordType *RT = Ty->getAs<RecordType>();
3338 llvm::SmallPtrSet<MemberKind*, 1> Results;
3339
3340 if (!RT)
3341 return Results;
3342 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003343 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003344 return Results;
3345
Alp Tokerb6cc5922014-05-03 03:45:55 +00003346 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003347 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003348 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003349
3350 // We just need to include all members of the right kind turned up by the
3351 // filter, at this point.
3352 if (S.LookupQualifiedName(R, RT->getDecl()))
3353 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3354 NamedDecl *decl = (*I)->getUnderlyingDecl();
3355 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3356 Results.insert(FK);
3357 }
3358 return Results;
3359}
3360
Richard Smith2868a732014-02-28 01:36:39 +00003361/// Check if we could call '.c_str()' on an object.
3362///
3363/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3364/// allow the call, or if it would be ambiguous).
3365bool Sema::hasCStrMethod(const Expr *E) {
3366 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3367 MethodSet Results =
3368 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3369 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3370 MI != ME; ++MI)
3371 if ((*MI)->getMinRequiredArguments() == 0)
3372 return true;
3373 return false;
3374}
3375
Richard Smith55ce3522012-06-25 20:30:08 +00003376// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003377// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003378// Returns true when a c_str() conversion method is found.
3379bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003380 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003381 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3382
3383 MethodSet Results =
3384 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3385
3386 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3387 MI != ME; ++MI) {
3388 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003389 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003390 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003391 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003392 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003393 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3394 << "c_str()"
3395 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3396 return true;
3397 }
3398 }
3399
3400 return false;
3401}
3402
Ted Kremenekab278de2010-01-28 23:39:18 +00003403bool
Ted Kremenek02087932010-07-16 02:11:22 +00003404CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003405 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003406 const char *startSpecifier,
3407 unsigned specifierLen) {
3408
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003409 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003410 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003411 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003412
Ted Kremenek6cd69422010-07-19 22:01:06 +00003413 if (FS.consumesDataArgument()) {
3414 if (atFirstArg) {
3415 atFirstArg = false;
3416 usesPositionalArgs = FS.usesPositionalArg();
3417 }
3418 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003419 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3420 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003421 return false;
3422 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003423 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003424
Ted Kremenekd1668192010-02-27 01:41:03 +00003425 // First check if the field width, precision, and conversion specifier
3426 // have matching data arguments.
3427 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3428 startSpecifier, specifierLen)) {
3429 return false;
3430 }
3431
3432 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3433 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003434 return false;
3435 }
3436
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003437 if (!CS.consumesDataArgument()) {
3438 // FIXME: Technically specifying a precision or field width here
3439 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003440 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003441 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003442
Ted Kremenek4a49d982010-02-26 19:18:41 +00003443 // Consume the argument.
3444 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003445 if (argIndex < NumDataArgs) {
3446 // The check to see if the argIndex is valid will come later.
3447 // We set the bit here because we may exit early from this
3448 // function if we encounter some other error.
3449 CoveredArgs.set(argIndex);
3450 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003451
3452 // Check for using an Objective-C specific conversion specifier
3453 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003454 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003455 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3456 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003457 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003458
Tom Careb49ec692010-06-17 19:00:27 +00003459 // Check for invalid use of field width
3460 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003461 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003462 startSpecifier, specifierLen);
3463 }
3464
3465 // Check for invalid use of precision
3466 if (!FS.hasValidPrecision()) {
3467 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3468 startSpecifier, specifierLen);
3469 }
3470
3471 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003472 if (!FS.hasValidThousandsGroupingPrefix())
3473 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003474 if (!FS.hasValidLeadingZeros())
3475 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3476 if (!FS.hasValidPlusPrefix())
3477 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003478 if (!FS.hasValidSpacePrefix())
3479 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003480 if (!FS.hasValidAlternativeForm())
3481 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3482 if (!FS.hasValidLeftJustified())
3483 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3484
3485 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003486 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3487 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3488 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003489 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3490 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3491 startSpecifier, specifierLen);
3492
3493 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003494 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003495 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3496 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003497 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003498 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003499 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003500 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3501 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003502
Jordan Rose92303592012-09-08 04:00:03 +00003503 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3504 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3505
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003506 // The remaining checks depend on the data arguments.
3507 if (HasVAListArg)
3508 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003509
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003510 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003511 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003512
Jordan Rose58bbe422012-07-19 18:10:08 +00003513 const Expr *Arg = getDataArg(argIndex);
3514 if (!Arg)
3515 return true;
3516
3517 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003518}
3519
Jordan Roseaee34382012-09-05 22:56:26 +00003520static bool requiresParensToAddCast(const Expr *E) {
3521 // FIXME: We should have a general way to reason about operator
3522 // precedence and whether parens are actually needed here.
3523 // Take care of a few common cases where they aren't.
3524 const Expr *Inside = E->IgnoreImpCasts();
3525 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3526 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3527
3528 switch (Inside->getStmtClass()) {
3529 case Stmt::ArraySubscriptExprClass:
3530 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003531 case Stmt::CharacterLiteralClass:
3532 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003533 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003534 case Stmt::FloatingLiteralClass:
3535 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003536 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003537 case Stmt::ObjCArrayLiteralClass:
3538 case Stmt::ObjCBoolLiteralExprClass:
3539 case Stmt::ObjCBoxedExprClass:
3540 case Stmt::ObjCDictionaryLiteralClass:
3541 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003542 case Stmt::ObjCIvarRefExprClass:
3543 case Stmt::ObjCMessageExprClass:
3544 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003545 case Stmt::ObjCStringLiteralClass:
3546 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003547 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003548 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003549 case Stmt::UnaryOperatorClass:
3550 return false;
3551 default:
3552 return true;
3553 }
3554}
3555
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003556static std::pair<QualType, StringRef>
3557shouldNotPrintDirectly(const ASTContext &Context,
3558 QualType IntendedTy,
3559 const Expr *E) {
3560 // Use a 'while' to peel off layers of typedefs.
3561 QualType TyTy = IntendedTy;
3562 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3563 StringRef Name = UserTy->getDecl()->getName();
3564 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3565 .Case("NSInteger", Context.LongTy)
3566 .Case("NSUInteger", Context.UnsignedLongTy)
3567 .Case("SInt32", Context.IntTy)
3568 .Case("UInt32", Context.UnsignedIntTy)
3569 .Default(QualType());
3570
3571 if (!CastTy.isNull())
3572 return std::make_pair(CastTy, Name);
3573
3574 TyTy = UserTy->desugar();
3575 }
3576
3577 // Strip parens if necessary.
3578 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3579 return shouldNotPrintDirectly(Context,
3580 PE->getSubExpr()->getType(),
3581 PE->getSubExpr());
3582
3583 // If this is a conditional expression, then its result type is constructed
3584 // via usual arithmetic conversions and thus there might be no necessary
3585 // typedef sugar there. Recurse to operands to check for NSInteger &
3586 // Co. usage condition.
3587 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3588 QualType TrueTy, FalseTy;
3589 StringRef TrueName, FalseName;
3590
3591 std::tie(TrueTy, TrueName) =
3592 shouldNotPrintDirectly(Context,
3593 CO->getTrueExpr()->getType(),
3594 CO->getTrueExpr());
3595 std::tie(FalseTy, FalseName) =
3596 shouldNotPrintDirectly(Context,
3597 CO->getFalseExpr()->getType(),
3598 CO->getFalseExpr());
3599
3600 if (TrueTy == FalseTy)
3601 return std::make_pair(TrueTy, TrueName);
3602 else if (TrueTy.isNull())
3603 return std::make_pair(FalseTy, FalseName);
3604 else if (FalseTy.isNull())
3605 return std::make_pair(TrueTy, TrueName);
3606 }
3607
3608 return std::make_pair(QualType(), StringRef());
3609}
3610
Richard Smith55ce3522012-06-25 20:30:08 +00003611bool
3612CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3613 const char *StartSpecifier,
3614 unsigned SpecifierLen,
3615 const Expr *E) {
3616 using namespace analyze_format_string;
3617 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003618 // Now type check the data expression that matches the
3619 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003620 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3621 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003622 if (!AT.isValid())
3623 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003624
Jordan Rose598ec092012-12-05 18:44:40 +00003625 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003626 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3627 ExprTy = TET->getUnderlyingExpr()->getType();
3628 }
3629
Jordan Rose598ec092012-12-05 18:44:40 +00003630 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003631 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003632
Jordan Rose22b74712012-09-05 22:56:19 +00003633 // Look through argument promotions for our error message's reported type.
3634 // This includes the integral and floating promotions, but excludes array
3635 // and function pointer decay; seeing that an argument intended to be a
3636 // string has type 'char [6]' is probably more confusing than 'char *'.
3637 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3638 if (ICE->getCastKind() == CK_IntegralCast ||
3639 ICE->getCastKind() == CK_FloatingCast) {
3640 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003641 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003642
3643 // Check if we didn't match because of an implicit cast from a 'char'
3644 // or 'short' to an 'int'. This is done because printf is a varargs
3645 // function.
3646 if (ICE->getType() == S.Context.IntTy ||
3647 ICE->getType() == S.Context.UnsignedIntTy) {
3648 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003649 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003650 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003651 }
Jordan Rose98709982012-06-04 22:48:57 +00003652 }
Jordan Rose598ec092012-12-05 18:44:40 +00003653 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3654 // Special case for 'a', which has type 'int' in C.
3655 // Note, however, that we do /not/ want to treat multibyte constants like
3656 // 'MooV' as characters! This form is deprecated but still exists.
3657 if (ExprTy == S.Context.IntTy)
3658 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3659 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003660 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003661
Jordan Rosebc53ed12014-05-31 04:12:14 +00003662 // Look through enums to their underlying type.
3663 bool IsEnum = false;
3664 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3665 ExprTy = EnumTy->getDecl()->getIntegerType();
3666 IsEnum = true;
3667 }
3668
Jordan Rose0e5badd2012-12-05 18:44:49 +00003669 // %C in an Objective-C context prints a unichar, not a wchar_t.
3670 // If the argument is an integer of some kind, believe the %C and suggest
3671 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003672 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003673 if (ObjCContext &&
3674 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3675 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3676 !ExprTy->isCharType()) {
3677 // 'unichar' is defined as a typedef of unsigned short, but we should
3678 // prefer using the typedef if it is visible.
3679 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003680
3681 // While we are here, check if the value is an IntegerLiteral that happens
3682 // to be within the valid range.
3683 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3684 const llvm::APInt &V = IL->getValue();
3685 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3686 return true;
3687 }
3688
Jordan Rose0e5badd2012-12-05 18:44:49 +00003689 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3690 Sema::LookupOrdinaryName);
3691 if (S.LookupName(Result, S.getCurScope())) {
3692 NamedDecl *ND = Result.getFoundDecl();
3693 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3694 if (TD->getUnderlyingType() == IntendedTy)
3695 IntendedTy = S.Context.getTypedefType(TD);
3696 }
3697 }
3698 }
3699
3700 // Special-case some of Darwin's platform-independence types by suggesting
3701 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003702 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00003703 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003704 QualType CastTy;
3705 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3706 if (!CastTy.isNull()) {
3707 IntendedTy = CastTy;
3708 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00003709 }
3710 }
3711
Jordan Rose22b74712012-09-05 22:56:19 +00003712 // We may be able to offer a FixItHint if it is a supported type.
3713 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003714 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003715 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003716
Jordan Rose22b74712012-09-05 22:56:19 +00003717 if (success) {
3718 // Get the fix string from the fixed format specifier
3719 SmallString<16> buf;
3720 llvm::raw_svector_ostream os(buf);
3721 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003722
Jordan Roseaee34382012-09-05 22:56:26 +00003723 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3724
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003725 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Jordan Rose0e5badd2012-12-05 18:44:49 +00003726 // In this case, the specifier is wrong and should be changed to match
3727 // the argument.
3728 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003729 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3730 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003731 << E->getSourceRange(),
3732 E->getLocStart(),
3733 /*IsStringLocation*/false,
3734 SpecRange,
3735 FixItHint::CreateReplacement(SpecRange, os.str()));
3736
3737 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003738 // The canonical type for formatting this value is different from the
3739 // actual type of the expression. (This occurs, for example, with Darwin's
3740 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3741 // should be printed as 'long' for 64-bit compatibility.)
3742 // Rather than emitting a normal format/argument mismatch, we want to
3743 // add a cast to the recommended type (and correct the format string
3744 // if necessary).
3745 SmallString<16> CastBuf;
3746 llvm::raw_svector_ostream CastFix(CastBuf);
3747 CastFix << "(";
3748 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3749 CastFix << ")";
3750
3751 SmallVector<FixItHint,4> Hints;
3752 if (!AT.matchesType(S.Context, IntendedTy))
3753 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3754
3755 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3756 // If there's already a cast present, just replace it.
3757 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3758 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3759
3760 } else if (!requiresParensToAddCast(E)) {
3761 // If the expression has high enough precedence,
3762 // just write the C-style cast.
3763 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3764 CastFix.str()));
3765 } else {
3766 // Otherwise, add parens around the expression as well as the cast.
3767 CastFix << "(";
3768 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3769 CastFix.str()));
3770
Alp Tokerb6cc5922014-05-03 03:45:55 +00003771 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003772 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3773 }
3774
Jordan Rose0e5badd2012-12-05 18:44:49 +00003775 if (ShouldNotPrintDirectly) {
3776 // The expression has a type that should not be printed directly.
3777 // We extract the name from the typedef because we don't want to show
3778 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003779 StringRef Name;
3780 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3781 Name = TypedefTy->getDecl()->getName();
3782 else
3783 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003784 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003785 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003786 << E->getSourceRange(),
3787 E->getLocStart(), /*IsStringLocation=*/false,
3788 SpecRange, Hints);
3789 } else {
3790 // In this case, the expression could be printed using a different
3791 // specifier, but we've decided that the specifier is probably correct
3792 // and we should cast instead. Just use the normal warning message.
3793 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003794 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3795 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003796 << E->getSourceRange(),
3797 E->getLocStart(), /*IsStringLocation*/false,
3798 SpecRange, Hints);
3799 }
Jordan Roseaee34382012-09-05 22:56:26 +00003800 }
Jordan Rose22b74712012-09-05 22:56:19 +00003801 } else {
3802 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3803 SpecifierLen);
3804 // Since the warning for passing non-POD types to variadic functions
3805 // was deferred until now, we emit a warning for non-POD
3806 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003807 switch (S.isValidVarArgType(ExprTy)) {
3808 case Sema::VAK_Valid:
3809 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003810 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003811 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3812 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003813 << CSR
3814 << E->getSourceRange(),
3815 E->getLocStart(), /*IsStringLocation*/false, CSR);
3816 break;
3817
3818 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00003819 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00003820 EmitFormatDiagnostic(
3821 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003822 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003823 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003824 << CallType
3825 << AT.getRepresentativeTypeName(S.Context)
3826 << CSR
3827 << E->getSourceRange(),
3828 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003829 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003830 break;
3831
3832 case Sema::VAK_Invalid:
3833 if (ExprTy->isObjCObjectType())
3834 EmitFormatDiagnostic(
3835 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3836 << S.getLangOpts().CPlusPlus11
3837 << ExprTy
3838 << CallType
3839 << AT.getRepresentativeTypeName(S.Context)
3840 << CSR
3841 << E->getSourceRange(),
3842 E->getLocStart(), /*IsStringLocation*/false, CSR);
3843 else
3844 // FIXME: If this is an initializer list, suggest removing the braces
3845 // or inserting a cast to the target type.
3846 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3847 << isa<InitListExpr>(E) << ExprTy << CallType
3848 << AT.getRepresentativeTypeName(S.Context)
3849 << E->getSourceRange();
3850 break;
3851 }
3852
3853 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3854 "format string specifier index out of range");
3855 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003856 }
3857
Ted Kremenekab278de2010-01-28 23:39:18 +00003858 return true;
3859}
3860
Ted Kremenek02087932010-07-16 02:11:22 +00003861//===--- CHECK: Scanf format string checking ------------------------------===//
3862
3863namespace {
3864class CheckScanfHandler : public CheckFormatHandler {
3865public:
3866 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3867 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003868 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003869 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003870 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003871 Sema::VariadicCallType CallType,
3872 llvm::SmallBitVector &CheckedVarArgs)
3873 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3874 numDataArgs, beg, hasVAListArg,
3875 Args, formatIdx, inFunctionCall, CallType,
3876 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003877 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003878
3879 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3880 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003881 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003882
3883 bool HandleInvalidScanfConversionSpecifier(
3884 const analyze_scanf::ScanfSpecifier &FS,
3885 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003886 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003887
Craig Toppere14c0f82014-03-12 04:55:44 +00003888 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003889};
Ted Kremenek019d2242010-01-29 01:50:07 +00003890}
Ted Kremenekab278de2010-01-28 23:39:18 +00003891
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003892void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3893 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003894 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3895 getLocationOfByte(end), /*IsStringLocation*/true,
3896 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003897}
3898
Ted Kremenekce815422010-07-19 21:25:57 +00003899bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3900 const analyze_scanf::ScanfSpecifier &FS,
3901 const char *startSpecifier,
3902 unsigned specifierLen) {
3903
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003904 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003905 FS.getConversionSpecifier();
3906
3907 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3908 getLocationOfByte(CS.getStart()),
3909 startSpecifier, specifierLen,
3910 CS.getStart(), CS.getLength());
3911}
3912
Ted Kremenek02087932010-07-16 02:11:22 +00003913bool CheckScanfHandler::HandleScanfSpecifier(
3914 const analyze_scanf::ScanfSpecifier &FS,
3915 const char *startSpecifier,
3916 unsigned specifierLen) {
3917
3918 using namespace analyze_scanf;
3919 using namespace analyze_format_string;
3920
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003921 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003922
Ted Kremenek6cd69422010-07-19 22:01:06 +00003923 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3924 // be used to decide if we are using positional arguments consistently.
3925 if (FS.consumesDataArgument()) {
3926 if (atFirstArg) {
3927 atFirstArg = false;
3928 usesPositionalArgs = FS.usesPositionalArg();
3929 }
3930 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003931 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3932 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003933 return false;
3934 }
Ted Kremenek02087932010-07-16 02:11:22 +00003935 }
3936
3937 // Check if the field with is non-zero.
3938 const OptionalAmount &Amt = FS.getFieldWidth();
3939 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3940 if (Amt.getConstantAmount() == 0) {
3941 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3942 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003943 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3944 getLocationOfByte(Amt.getStart()),
3945 /*IsStringLocation*/true, R,
3946 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003947 }
3948 }
3949
3950 if (!FS.consumesDataArgument()) {
3951 // FIXME: Technically specifying a precision or field width here
3952 // makes no sense. Worth issuing a warning at some point.
3953 return true;
3954 }
3955
3956 // Consume the argument.
3957 unsigned argIndex = FS.getArgIndex();
3958 if (argIndex < NumDataArgs) {
3959 // The check to see if the argIndex is valid will come later.
3960 // We set the bit here because we may exit early from this
3961 // function if we encounter some other error.
3962 CoveredArgs.set(argIndex);
3963 }
3964
Ted Kremenek4407ea42010-07-20 20:04:47 +00003965 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003966 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003967 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3968 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003969 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003970 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003971 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003972 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3973 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003974
Jordan Rose92303592012-09-08 04:00:03 +00003975 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3976 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3977
Ted Kremenek02087932010-07-16 02:11:22 +00003978 // The remaining checks depend on the data arguments.
3979 if (HasVAListArg)
3980 return true;
3981
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003982 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003983 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003984
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003985 // Check that the argument type matches the format specifier.
3986 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003987 if (!Ex)
3988 return true;
3989
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003990 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3991 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003992 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003993 bool success = fixedFS.fixType(Ex->getType(),
3994 Ex->IgnoreImpCasts()->getType(),
3995 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003996
3997 if (success) {
3998 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003999 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004000 llvm::raw_svector_ostream os(buf);
4001 fixedFS.toString(os);
4002
4003 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004004 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4005 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004006 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00004007 Ex->getLocStart(),
4008 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004009 getSpecifierRange(startSpecifier, specifierLen),
4010 FixItHint::CreateReplacement(
4011 getSpecifierRange(startSpecifier, specifierLen),
4012 os.str()));
4013 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00004014 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004015 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4016 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00004017 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00004018 Ex->getLocStart(),
4019 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00004020 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004021 }
4022 }
4023
Ted Kremenek02087932010-07-16 02:11:22 +00004024 return true;
4025}
4026
4027void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004028 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004029 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004030 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004031 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004032 bool inFunctionCall, VariadicCallType CallType,
4033 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004034
Ted Kremenekab278de2010-01-28 23:39:18 +00004035 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004036 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004037 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004038 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004039 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4040 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004041 return;
4042 }
Ted Kremenek02087932010-07-16 02:11:22 +00004043
Ted Kremenekab278de2010-01-28 23:39:18 +00004044 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004045 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004046 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004047 // Account for cases where the string literal is truncated in a declaration.
4048 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4049 assert(T && "String literal not of constant array type!");
4050 size_t TypeSize = T->getSize().getZExtValue();
4051 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004052 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004053
4054 // Emit a warning if the string literal is truncated and does not contain an
4055 // embedded null character.
4056 if (TypeSize <= StrRef.size() &&
4057 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4058 CheckFormatHandler::EmitFormatDiagnostic(
4059 *this, inFunctionCall, Args[format_idx],
4060 PDiag(diag::warn_printf_format_string_not_null_terminated),
4061 FExpr->getLocStart(),
4062 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4063 return;
4064 }
4065
Ted Kremenekab278de2010-01-28 23:39:18 +00004066 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004067 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004068 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004069 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004070 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4071 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004072 return;
4073 }
Ted Kremenek02087932010-07-16 02:11:22 +00004074
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004075 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00004076 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004077 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004078 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004079 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004080
Hans Wennborg23926bd2011-12-15 10:25:47 +00004081 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004082 getLangOpts(),
4083 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004084 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004085 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004086 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004087 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004088 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004089
Hans Wennborg23926bd2011-12-15 10:25:47 +00004090 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004091 getLangOpts(),
4092 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004093 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004094 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004095}
4096
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004097bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4098 // Str - The format string. NOTE: this is NOT null-terminated!
4099 StringRef StrRef = FExpr->getString();
4100 const char *Str = StrRef.data();
4101 // Account for cases where the string literal is truncated in a declaration.
4102 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4103 assert(T && "String literal not of constant array type!");
4104 size_t TypeSize = T->getSize().getZExtValue();
4105 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4106 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4107 getLangOpts(),
4108 Context.getTargetInfo());
4109}
4110
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004111//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4112
4113// Returns the related absolute value function that is larger, of 0 if one
4114// does not exist.
4115static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4116 switch (AbsFunction) {
4117 default:
4118 return 0;
4119
4120 case Builtin::BI__builtin_abs:
4121 return Builtin::BI__builtin_labs;
4122 case Builtin::BI__builtin_labs:
4123 return Builtin::BI__builtin_llabs;
4124 case Builtin::BI__builtin_llabs:
4125 return 0;
4126
4127 case Builtin::BI__builtin_fabsf:
4128 return Builtin::BI__builtin_fabs;
4129 case Builtin::BI__builtin_fabs:
4130 return Builtin::BI__builtin_fabsl;
4131 case Builtin::BI__builtin_fabsl:
4132 return 0;
4133
4134 case Builtin::BI__builtin_cabsf:
4135 return Builtin::BI__builtin_cabs;
4136 case Builtin::BI__builtin_cabs:
4137 return Builtin::BI__builtin_cabsl;
4138 case Builtin::BI__builtin_cabsl:
4139 return 0;
4140
4141 case Builtin::BIabs:
4142 return Builtin::BIlabs;
4143 case Builtin::BIlabs:
4144 return Builtin::BIllabs;
4145 case Builtin::BIllabs:
4146 return 0;
4147
4148 case Builtin::BIfabsf:
4149 return Builtin::BIfabs;
4150 case Builtin::BIfabs:
4151 return Builtin::BIfabsl;
4152 case Builtin::BIfabsl:
4153 return 0;
4154
4155 case Builtin::BIcabsf:
4156 return Builtin::BIcabs;
4157 case Builtin::BIcabs:
4158 return Builtin::BIcabsl;
4159 case Builtin::BIcabsl:
4160 return 0;
4161 }
4162}
4163
4164// Returns the argument type of the absolute value function.
4165static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4166 unsigned AbsType) {
4167 if (AbsType == 0)
4168 return QualType();
4169
4170 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4171 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4172 if (Error != ASTContext::GE_None)
4173 return QualType();
4174
4175 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4176 if (!FT)
4177 return QualType();
4178
4179 if (FT->getNumParams() != 1)
4180 return QualType();
4181
4182 return FT->getParamType(0);
4183}
4184
4185// Returns the best absolute value function, or zero, based on type and
4186// current absolute value function.
4187static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4188 unsigned AbsFunctionKind) {
4189 unsigned BestKind = 0;
4190 uint64_t ArgSize = Context.getTypeSize(ArgType);
4191 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4192 Kind = getLargerAbsoluteValueFunction(Kind)) {
4193 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4194 if (Context.getTypeSize(ParamType) >= ArgSize) {
4195 if (BestKind == 0)
4196 BestKind = Kind;
4197 else if (Context.hasSameType(ParamType, ArgType)) {
4198 BestKind = Kind;
4199 break;
4200 }
4201 }
4202 }
4203 return BestKind;
4204}
4205
4206enum AbsoluteValueKind {
4207 AVK_Integer,
4208 AVK_Floating,
4209 AVK_Complex
4210};
4211
4212static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4213 if (T->isIntegralOrEnumerationType())
4214 return AVK_Integer;
4215 if (T->isRealFloatingType())
4216 return AVK_Floating;
4217 if (T->isAnyComplexType())
4218 return AVK_Complex;
4219
4220 llvm_unreachable("Type not integer, floating, or complex");
4221}
4222
4223// Changes the absolute value function to a different type. Preserves whether
4224// the function is a builtin.
4225static unsigned changeAbsFunction(unsigned AbsKind,
4226 AbsoluteValueKind ValueKind) {
4227 switch (ValueKind) {
4228 case AVK_Integer:
4229 switch (AbsKind) {
4230 default:
4231 return 0;
4232 case Builtin::BI__builtin_fabsf:
4233 case Builtin::BI__builtin_fabs:
4234 case Builtin::BI__builtin_fabsl:
4235 case Builtin::BI__builtin_cabsf:
4236 case Builtin::BI__builtin_cabs:
4237 case Builtin::BI__builtin_cabsl:
4238 return Builtin::BI__builtin_abs;
4239 case Builtin::BIfabsf:
4240 case Builtin::BIfabs:
4241 case Builtin::BIfabsl:
4242 case Builtin::BIcabsf:
4243 case Builtin::BIcabs:
4244 case Builtin::BIcabsl:
4245 return Builtin::BIabs;
4246 }
4247 case AVK_Floating:
4248 switch (AbsKind) {
4249 default:
4250 return 0;
4251 case Builtin::BI__builtin_abs:
4252 case Builtin::BI__builtin_labs:
4253 case Builtin::BI__builtin_llabs:
4254 case Builtin::BI__builtin_cabsf:
4255 case Builtin::BI__builtin_cabs:
4256 case Builtin::BI__builtin_cabsl:
4257 return Builtin::BI__builtin_fabsf;
4258 case Builtin::BIabs:
4259 case Builtin::BIlabs:
4260 case Builtin::BIllabs:
4261 case Builtin::BIcabsf:
4262 case Builtin::BIcabs:
4263 case Builtin::BIcabsl:
4264 return Builtin::BIfabsf;
4265 }
4266 case AVK_Complex:
4267 switch (AbsKind) {
4268 default:
4269 return 0;
4270 case Builtin::BI__builtin_abs:
4271 case Builtin::BI__builtin_labs:
4272 case Builtin::BI__builtin_llabs:
4273 case Builtin::BI__builtin_fabsf:
4274 case Builtin::BI__builtin_fabs:
4275 case Builtin::BI__builtin_fabsl:
4276 return Builtin::BI__builtin_cabsf;
4277 case Builtin::BIabs:
4278 case Builtin::BIlabs:
4279 case Builtin::BIllabs:
4280 case Builtin::BIfabsf:
4281 case Builtin::BIfabs:
4282 case Builtin::BIfabsl:
4283 return Builtin::BIcabsf;
4284 }
4285 }
4286 llvm_unreachable("Unable to convert function");
4287}
4288
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004289static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004290 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4291 if (!FnInfo)
4292 return 0;
4293
4294 switch (FDecl->getBuiltinID()) {
4295 default:
4296 return 0;
4297 case Builtin::BI__builtin_abs:
4298 case Builtin::BI__builtin_fabs:
4299 case Builtin::BI__builtin_fabsf:
4300 case Builtin::BI__builtin_fabsl:
4301 case Builtin::BI__builtin_labs:
4302 case Builtin::BI__builtin_llabs:
4303 case Builtin::BI__builtin_cabs:
4304 case Builtin::BI__builtin_cabsf:
4305 case Builtin::BI__builtin_cabsl:
4306 case Builtin::BIabs:
4307 case Builtin::BIlabs:
4308 case Builtin::BIllabs:
4309 case Builtin::BIfabs:
4310 case Builtin::BIfabsf:
4311 case Builtin::BIfabsl:
4312 case Builtin::BIcabs:
4313 case Builtin::BIcabsf:
4314 case Builtin::BIcabsl:
4315 return FDecl->getBuiltinID();
4316 }
4317 llvm_unreachable("Unknown Builtin type");
4318}
4319
4320// If the replacement is valid, emit a note with replacement function.
4321// Additionally, suggest including the proper header if not already included.
4322static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004323 unsigned AbsKind, QualType ArgType) {
4324 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004325 const char *HeaderName = nullptr;
4326 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004327 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4328 FunctionName = "std::abs";
4329 if (ArgType->isIntegralOrEnumerationType()) {
4330 HeaderName = "cstdlib";
4331 } else if (ArgType->isRealFloatingType()) {
4332 HeaderName = "cmath";
4333 } else {
4334 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004335 }
Richard Trieubeffb832014-04-15 23:47:53 +00004336
4337 // Lookup all std::abs
4338 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004339 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004340 R.suppressDiagnostics();
4341 S.LookupQualifiedName(R, Std);
4342
4343 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004344 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004345 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4346 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4347 } else {
4348 FDecl = dyn_cast<FunctionDecl>(I);
4349 }
4350 if (!FDecl)
4351 continue;
4352
4353 // Found std::abs(), check that they are the right ones.
4354 if (FDecl->getNumParams() != 1)
4355 continue;
4356
4357 // Check that the parameter type can handle the argument.
4358 QualType ParamType = FDecl->getParamDecl(0)->getType();
4359 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4360 S.Context.getTypeSize(ArgType) <=
4361 S.Context.getTypeSize(ParamType)) {
4362 // Found a function, don't need the header hint.
4363 EmitHeaderHint = false;
4364 break;
4365 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004366 }
Richard Trieubeffb832014-04-15 23:47:53 +00004367 }
4368 } else {
4369 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4370 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4371
4372 if (HeaderName) {
4373 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4374 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4375 R.suppressDiagnostics();
4376 S.LookupName(R, S.getCurScope());
4377
4378 if (R.isSingleResult()) {
4379 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4380 if (FD && FD->getBuiltinID() == AbsKind) {
4381 EmitHeaderHint = false;
4382 } else {
4383 return;
4384 }
4385 } else if (!R.empty()) {
4386 return;
4387 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004388 }
4389 }
4390
4391 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004392 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004393
Richard Trieubeffb832014-04-15 23:47:53 +00004394 if (!HeaderName)
4395 return;
4396
4397 if (!EmitHeaderHint)
4398 return;
4399
Alp Toker5d96e0a2014-07-11 20:53:51 +00004400 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4401 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004402}
4403
4404static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4405 if (!FDecl)
4406 return false;
4407
4408 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4409 return false;
4410
4411 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4412
4413 while (ND && ND->isInlineNamespace()) {
4414 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004415 }
Richard Trieubeffb832014-04-15 23:47:53 +00004416
4417 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4418 return false;
4419
4420 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4421 return false;
4422
4423 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004424}
4425
4426// Warn when using the wrong abs() function.
4427void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4428 const FunctionDecl *FDecl,
4429 IdentifierInfo *FnInfo) {
4430 if (Call->getNumArgs() != 1)
4431 return;
4432
4433 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004434 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4435 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004436 return;
4437
4438 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4439 QualType ParamType = Call->getArg(0)->getType();
4440
Alp Toker5d96e0a2014-07-11 20:53:51 +00004441 // Unsigned types cannot be negative. Suggest removing the absolute value
4442 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004443 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004444 const char *FunctionName =
4445 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004446 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4447 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004448 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004449 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4450 return;
4451 }
4452
Richard Trieubeffb832014-04-15 23:47:53 +00004453 // std::abs has overloads which prevent most of the absolute value problems
4454 // from occurring.
4455 if (IsStdAbs)
4456 return;
4457
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004458 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4459 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4460
4461 // The argument and parameter are the same kind. Check if they are the right
4462 // size.
4463 if (ArgValueKind == ParamValueKind) {
4464 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4465 return;
4466
4467 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4468 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4469 << FDecl << ArgType << ParamType;
4470
4471 if (NewAbsKind == 0)
4472 return;
4473
4474 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004475 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004476 return;
4477 }
4478
4479 // ArgValueKind != ParamValueKind
4480 // The wrong type of absolute value function was used. Attempt to find the
4481 // proper one.
4482 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4483 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4484 if (NewAbsKind == 0)
4485 return;
4486
4487 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4488 << FDecl << ParamValueKind << ArgValueKind;
4489
4490 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004491 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004492 return;
4493}
4494
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004495//===--- CHECK: Standard memory functions ---------------------------------===//
4496
Nico Weber0e6daef2013-12-26 23:38:39 +00004497/// \brief Takes the expression passed to the size_t parameter of functions
4498/// such as memcmp, strncat, etc and warns if it's a comparison.
4499///
4500/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4501static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4502 IdentifierInfo *FnName,
4503 SourceLocation FnLoc,
4504 SourceLocation RParenLoc) {
4505 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4506 if (!Size)
4507 return false;
4508
4509 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4510 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4511 return false;
4512
Nico Weber0e6daef2013-12-26 23:38:39 +00004513 SourceRange SizeRange = Size->getSourceRange();
4514 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4515 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004516 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004517 << FnName << FixItHint::CreateInsertion(
4518 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004519 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004520 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004521 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004522 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4523 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004524
4525 return true;
4526}
4527
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004528/// \brief Determine whether the given type is or contains a dynamic class type
4529/// (e.g., whether it has a vtable).
4530static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4531 bool &IsContained) {
4532 // Look through array types while ignoring qualifiers.
4533 const Type *Ty = T->getBaseElementTypeUnsafe();
4534 IsContained = false;
4535
4536 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4537 RD = RD ? RD->getDefinition() : nullptr;
4538 if (!RD)
4539 return nullptr;
4540
4541 if (RD->isDynamicClass())
4542 return RD;
4543
4544 // Check all the fields. If any bases were dynamic, the class is dynamic.
4545 // It's impossible for a class to transitively contain itself by value, so
4546 // infinite recursion is impossible.
4547 for (auto *FD : RD->fields()) {
4548 bool SubContained;
4549 if (const CXXRecordDecl *ContainedRD =
4550 getContainedDynamicClass(FD->getType(), SubContained)) {
4551 IsContained = true;
4552 return ContainedRD;
4553 }
4554 }
4555
4556 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004557}
4558
Chandler Carruth889ed862011-06-21 23:04:20 +00004559/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004560/// otherwise returns NULL.
4561static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004562 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004563 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4564 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4565 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004566
Craig Topperc3ec1492014-05-26 06:22:03 +00004567 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004568}
4569
Chandler Carruth889ed862011-06-21 23:04:20 +00004570/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004571static QualType getSizeOfArgType(const Expr* E) {
4572 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4573 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4574 if (SizeOf->getKind() == clang::UETT_SizeOf)
4575 return SizeOf->getTypeOfArgument();
4576
4577 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004578}
4579
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004580/// \brief Check for dangerous or invalid arguments to memset().
4581///
Chandler Carruthac687262011-06-03 06:23:57 +00004582/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004583/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4584/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004585///
4586/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004587void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004588 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004589 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004590 assert(BId != 0);
4591
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004592 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004593 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004594 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004595 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004596 return;
4597
Anna Zaks22122702012-01-17 00:37:07 +00004598 unsigned LastArg = (BId == Builtin::BImemset ||
4599 BId == Builtin::BIstrndup ? 1 : 2);
4600 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004601 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004602
Nico Weber0e6daef2013-12-26 23:38:39 +00004603 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4604 Call->getLocStart(), Call->getRParenLoc()))
4605 return;
4606
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004607 // We have special checking when the length is a sizeof expression.
4608 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4609 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4610 llvm::FoldingSetNodeID SizeOfArgID;
4611
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004612 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4613 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004614 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004615
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004616 QualType DestTy = Dest->getType();
4617 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4618 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004619
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004620 // Never warn about void type pointers. This can be used to suppress
4621 // false positives.
4622 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004623 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004624
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004625 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4626 // actually comparing the expressions for equality. Because computing the
4627 // expression IDs can be expensive, we only do this if the diagnostic is
4628 // enabled.
4629 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004630 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4631 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004632 // We only compute IDs for expressions if the warning is enabled, and
4633 // cache the sizeof arg's ID.
4634 if (SizeOfArgID == llvm::FoldingSetNodeID())
4635 SizeOfArg->Profile(SizeOfArgID, Context, true);
4636 llvm::FoldingSetNodeID DestID;
4637 Dest->Profile(DestID, Context, true);
4638 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004639 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4640 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004641 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004642 StringRef ReadableName = FnName->getName();
4643
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004644 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004645 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004646 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004647 if (!PointeeTy->isIncompleteType() &&
4648 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004649 ActionIdx = 2; // If the pointee's size is sizeof(char),
4650 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004651
4652 // If the function is defined as a builtin macro, do not show macro
4653 // expansion.
4654 SourceLocation SL = SizeOfArg->getExprLoc();
4655 SourceRange DSR = Dest->getSourceRange();
4656 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004657 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004658
4659 if (SM.isMacroArgExpansion(SL)) {
4660 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4661 SL = SM.getSpellingLoc(SL);
4662 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4663 SM.getSpellingLoc(DSR.getEnd()));
4664 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4665 SM.getSpellingLoc(SSR.getEnd()));
4666 }
4667
Anna Zaksd08d9152012-05-30 23:14:52 +00004668 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004669 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004670 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004671 << PointeeTy
4672 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004673 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004674 << SSR);
4675 DiagRuntimeBehavior(SL, SizeOfArg,
4676 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4677 << ActionIdx
4678 << SSR);
4679
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004680 break;
4681 }
4682 }
4683
4684 // Also check for cases where the sizeof argument is the exact same
4685 // type as the memory argument, and where it points to a user-defined
4686 // record type.
4687 if (SizeOfArgTy != QualType()) {
4688 if (PointeeTy->isRecordType() &&
4689 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4690 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4691 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4692 << FnName << SizeOfArgTy << ArgIdx
4693 << PointeeTy << Dest->getSourceRange()
4694 << LenExpr->getSourceRange());
4695 break;
4696 }
Nico Weberc5e73862011-06-14 16:14:58 +00004697 }
4698
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004699 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004700 bool IsContained;
4701 if (const CXXRecordDecl *ContainedRD =
4702 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004703
4704 unsigned OperationType = 0;
4705 // "overwritten" if we're warning about the destination for any call
4706 // but memcmp; otherwise a verb appropriate to the call.
4707 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4708 if (BId == Builtin::BImemcpy)
4709 OperationType = 1;
4710 else if(BId == Builtin::BImemmove)
4711 OperationType = 2;
4712 else if (BId == Builtin::BImemcmp)
4713 OperationType = 3;
4714 }
4715
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004716 DiagRuntimeBehavior(
4717 Dest->getExprLoc(), Dest,
4718 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004719 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004720 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004721 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004722 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4723 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004724 DiagRuntimeBehavior(
4725 Dest->getExprLoc(), Dest,
4726 PDiag(diag::warn_arc_object_memaccess)
4727 << ArgIdx << FnName << PointeeTy
4728 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004729 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004730 continue;
John McCall31168b02011-06-15 23:02:42 +00004731
4732 DiagRuntimeBehavior(
4733 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004734 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004735 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4736 break;
4737 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004738 }
4739}
4740
Ted Kremenek6865f772011-08-18 20:55:45 +00004741// A little helper routine: ignore addition and subtraction of integer literals.
4742// This intentionally does not ignore all integer constant expressions because
4743// we don't want to remove sizeof().
4744static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4745 Ex = Ex->IgnoreParenCasts();
4746
4747 for (;;) {
4748 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4749 if (!BO || !BO->isAdditiveOp())
4750 break;
4751
4752 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4753 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4754
4755 if (isa<IntegerLiteral>(RHS))
4756 Ex = LHS;
4757 else if (isa<IntegerLiteral>(LHS))
4758 Ex = RHS;
4759 else
4760 break;
4761 }
4762
4763 return Ex;
4764}
4765
Anna Zaks13b08572012-08-08 21:42:23 +00004766static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4767 ASTContext &Context) {
4768 // Only handle constant-sized or VLAs, but not flexible members.
4769 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4770 // Only issue the FIXIT for arrays of size > 1.
4771 if (CAT->getSize().getSExtValue() <= 1)
4772 return false;
4773 } else if (!Ty->isVariableArrayType()) {
4774 return false;
4775 }
4776 return true;
4777}
4778
Ted Kremenek6865f772011-08-18 20:55:45 +00004779// Warn if the user has made the 'size' argument to strlcpy or strlcat
4780// be the size of the source, instead of the destination.
4781void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4782 IdentifierInfo *FnName) {
4783
4784 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004785 unsigned NumArgs = Call->getNumArgs();
4786 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004787 return;
4788
4789 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4790 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004791 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004792
4793 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4794 Call->getLocStart(), Call->getRParenLoc()))
4795 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004796
4797 // Look for 'strlcpy(dst, x, sizeof(x))'
4798 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4799 CompareWithSrc = Ex;
4800 else {
4801 // Look for 'strlcpy(dst, x, strlen(x))'
4802 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004803 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4804 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004805 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4806 }
4807 }
4808
4809 if (!CompareWithSrc)
4810 return;
4811
4812 // Determine if the argument to sizeof/strlen is equal to the source
4813 // argument. In principle there's all kinds of things you could do
4814 // here, for instance creating an == expression and evaluating it with
4815 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4816 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4817 if (!SrcArgDRE)
4818 return;
4819
4820 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4821 if (!CompareWithSrcDRE ||
4822 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4823 return;
4824
4825 const Expr *OriginalSizeArg = Call->getArg(2);
4826 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4827 << OriginalSizeArg->getSourceRange() << FnName;
4828
4829 // Output a FIXIT hint if the destination is an array (rather than a
4830 // pointer to an array). This could be enhanced to handle some
4831 // pointers if we know the actual size, like if DstArg is 'array+2'
4832 // we could say 'sizeof(array)-2'.
4833 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004834 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004835 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004836
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004837 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004838 llvm::raw_svector_ostream OS(sizeString);
4839 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004840 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004841 OS << ")";
4842
4843 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4844 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4845 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004846}
4847
Anna Zaks314cd092012-02-01 19:08:57 +00004848/// Check if two expressions refer to the same declaration.
4849static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4850 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4851 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4852 return D1->getDecl() == D2->getDecl();
4853 return false;
4854}
4855
4856static const Expr *getStrlenExprArg(const Expr *E) {
4857 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4858 const FunctionDecl *FD = CE->getDirectCallee();
4859 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004860 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004861 return CE->getArg(0)->IgnoreParenCasts();
4862 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004863 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004864}
4865
4866// Warn on anti-patterns as the 'size' argument to strncat.
4867// The correct size argument should look like following:
4868// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4869void Sema::CheckStrncatArguments(const CallExpr *CE,
4870 IdentifierInfo *FnName) {
4871 // Don't crash if the user has the wrong number of arguments.
4872 if (CE->getNumArgs() < 3)
4873 return;
4874 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4875 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4876 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4877
Nico Weber0e6daef2013-12-26 23:38:39 +00004878 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4879 CE->getRParenLoc()))
4880 return;
4881
Anna Zaks314cd092012-02-01 19:08:57 +00004882 // Identify common expressions, which are wrongly used as the size argument
4883 // to strncat and may lead to buffer overflows.
4884 unsigned PatternType = 0;
4885 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4886 // - sizeof(dst)
4887 if (referToTheSameDecl(SizeOfArg, DstArg))
4888 PatternType = 1;
4889 // - sizeof(src)
4890 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4891 PatternType = 2;
4892 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4893 if (BE->getOpcode() == BO_Sub) {
4894 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4895 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4896 // - sizeof(dst) - strlen(dst)
4897 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4898 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4899 PatternType = 1;
4900 // - sizeof(src) - (anything)
4901 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4902 PatternType = 2;
4903 }
4904 }
4905
4906 if (PatternType == 0)
4907 return;
4908
Anna Zaks5069aa32012-02-03 01:27:37 +00004909 // Generate the diagnostic.
4910 SourceLocation SL = LenArg->getLocStart();
4911 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004912 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004913
4914 // If the function is defined as a builtin macro, do not show macro expansion.
4915 if (SM.isMacroArgExpansion(SL)) {
4916 SL = SM.getSpellingLoc(SL);
4917 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4918 SM.getSpellingLoc(SR.getEnd()));
4919 }
4920
Anna Zaks13b08572012-08-08 21:42:23 +00004921 // Check if the destination is an array (rather than a pointer to an array).
4922 QualType DstTy = DstArg->getType();
4923 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4924 Context);
4925 if (!isKnownSizeArray) {
4926 if (PatternType == 1)
4927 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4928 else
4929 Diag(SL, diag::warn_strncat_src_size) << SR;
4930 return;
4931 }
4932
Anna Zaks314cd092012-02-01 19:08:57 +00004933 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004934 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004935 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004936 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004937
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004938 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004939 llvm::raw_svector_ostream OS(sizeString);
4940 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004941 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004942 OS << ") - ";
4943 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004944 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004945 OS << ") - 1";
4946
Anna Zaks5069aa32012-02-03 01:27:37 +00004947 Diag(SL, diag::note_strncat_wrong_size)
4948 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004949}
4950
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004951//===--- CHECK: Return Address of Stack Variable --------------------------===//
4952
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004953static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4954 Decl *ParentDecl);
4955static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4956 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004957
4958/// CheckReturnStackAddr - Check if a return statement returns the address
4959/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004960static void
4961CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4962 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004963
Craig Topperc3ec1492014-05-26 06:22:03 +00004964 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004965 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004966
4967 // Perform checking for returned stack addresses, local blocks,
4968 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004969 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004970 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004971 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004972 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004973 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004974 }
4975
Craig Topperc3ec1492014-05-26 06:22:03 +00004976 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004977 return; // Nothing suspicious was found.
4978
4979 SourceLocation diagLoc;
4980 SourceRange diagRange;
4981 if (refVars.empty()) {
4982 diagLoc = stackE->getLocStart();
4983 diagRange = stackE->getSourceRange();
4984 } else {
4985 // We followed through a reference variable. 'stackE' contains the
4986 // problematic expression but we will warn at the return statement pointing
4987 // at the reference variable. We will later display the "trail" of
4988 // reference variables using notes.
4989 diagLoc = refVars[0]->getLocStart();
4990 diagRange = refVars[0]->getSourceRange();
4991 }
4992
4993 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004994 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004995 : diag::warn_ret_stack_addr)
4996 << DR->getDecl()->getDeclName() << diagRange;
4997 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004998 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004999 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005000 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005001 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005002 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5003 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005004 << diagRange;
5005 }
5006
5007 // Display the "trail" of reference variables that we followed until we
5008 // found the problematic expression using notes.
5009 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5010 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5011 // If this var binds to another reference var, show the range of the next
5012 // var, otherwise the var binds to the problematic expression, in which case
5013 // show the range of the expression.
5014 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5015 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005016 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5017 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005018 }
5019}
5020
5021/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5022/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005023/// to a location on the stack, a local block, an address of a label, or a
5024/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005025/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005026/// encounter a subexpression that (1) clearly does not lead to one of the
5027/// above problematic expressions (2) is something we cannot determine leads to
5028/// a problematic expression based on such local checking.
5029///
5030/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5031/// the expression that they point to. Such variables are added to the
5032/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005033///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005034/// EvalAddr processes expressions that are pointers that are used as
5035/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005036/// At the base case of the recursion is a check for the above problematic
5037/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005038///
5039/// This implementation handles:
5040///
5041/// * pointer-to-pointer casts
5042/// * implicit conversions from array references to pointers
5043/// * taking the address of fields
5044/// * arbitrary interplay between "&" and "*" operators
5045/// * pointer arithmetic from an address of a stack variable
5046/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005047static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5048 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005049 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005050 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005051
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005052 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005053 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005054 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005055 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005056 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005057
Peter Collingbourne91147592011-04-15 00:35:48 +00005058 E = E->IgnoreParens();
5059
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005060 // Our "symbolic interpreter" is just a dispatch off the currently
5061 // viewed AST node. We then recursively traverse the AST by calling
5062 // EvalAddr and EvalVal appropriately.
5063 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005064 case Stmt::DeclRefExprClass: {
5065 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5066
Richard Smith40f08eb2014-01-30 22:05:38 +00005067 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005068 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005069 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005070
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005071 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5072 // If this is a reference variable, follow through to the expression that
5073 // it points to.
5074 if (V->hasLocalStorage() &&
5075 V->getType()->isReferenceType() && V->hasInit()) {
5076 // Add the reference variable to the "trail".
5077 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005078 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005079 }
5080
Craig Topperc3ec1492014-05-26 06:22:03 +00005081 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005082 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005083
Chris Lattner934edb22007-12-28 05:31:15 +00005084 case Stmt::UnaryOperatorClass: {
5085 // The only unary operator that make sense to handle here
5086 // is AddrOf. All others don't make sense as pointers.
5087 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005088
John McCalle3027922010-08-25 11:45:40 +00005089 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005090 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005091 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005092 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005093 }
Mike Stump11289f42009-09-09 15:08:12 +00005094
Chris Lattner934edb22007-12-28 05:31:15 +00005095 case Stmt::BinaryOperatorClass: {
5096 // Handle pointer arithmetic. All other binary operators are not valid
5097 // in this context.
5098 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005099 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005100
John McCalle3027922010-08-25 11:45:40 +00005101 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005102 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005103
Chris Lattner934edb22007-12-28 05:31:15 +00005104 Expr *Base = B->getLHS();
5105
5106 // Determine which argument is the real pointer base. It could be
5107 // the RHS argument instead of the LHS.
5108 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005109
Chris Lattner934edb22007-12-28 05:31:15 +00005110 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005111 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005112 }
Steve Naroff2752a172008-09-10 19:17:48 +00005113
Chris Lattner934edb22007-12-28 05:31:15 +00005114 // For conditional operators we need to see if either the LHS or RHS are
5115 // valid DeclRefExpr*s. If one of them is valid, we return it.
5116 case Stmt::ConditionalOperatorClass: {
5117 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005118
Chris Lattner934edb22007-12-28 05:31:15 +00005119 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005120 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5121 if (Expr *LHSExpr = C->getLHS()) {
5122 // In C++, we can have a throw-expression, which has 'void' type.
5123 if (!LHSExpr->getType()->isVoidType())
5124 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005125 return LHS;
5126 }
Chris Lattner934edb22007-12-28 05:31:15 +00005127
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005128 // In C++, we can have a throw-expression, which has 'void' type.
5129 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005130 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005131
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005132 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005133 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005134
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005135 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005136 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005137 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005138 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005139
5140 case Stmt::AddrLabelExprClass:
5141 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005142
John McCall28fc7092011-11-10 05:35:25 +00005143 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005144 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5145 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005146
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005147 // For casts, we need to handle conversions from arrays to
5148 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005149 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005150 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005151 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005152 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005153 case Stmt::CXXStaticCastExprClass:
5154 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005155 case Stmt::CXXConstCastExprClass:
5156 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005157 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5158 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005159 case CK_LValueToRValue:
5160 case CK_NoOp:
5161 case CK_BaseToDerived:
5162 case CK_DerivedToBase:
5163 case CK_UncheckedDerivedToBase:
5164 case CK_Dynamic:
5165 case CK_CPointerToObjCPointerCast:
5166 case CK_BlockPointerToObjCPointerCast:
5167 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005168 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005169
5170 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005171 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005172
Richard Trieudadefde2014-07-02 04:39:38 +00005173 case CK_BitCast:
5174 if (SubExpr->getType()->isAnyPointerType() ||
5175 SubExpr->getType()->isBlockPointerType() ||
5176 SubExpr->getType()->isObjCQualifiedIdType())
5177 return EvalAddr(SubExpr, refVars, ParentDecl);
5178 else
5179 return nullptr;
5180
Eli Friedman8195ad72012-02-23 23:04:32 +00005181 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005182 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005183 }
Chris Lattner934edb22007-12-28 05:31:15 +00005184 }
Mike Stump11289f42009-09-09 15:08:12 +00005185
Douglas Gregorfe314812011-06-21 17:03:29 +00005186 case Stmt::MaterializeTemporaryExprClass:
5187 if (Expr *Result = EvalAddr(
5188 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005189 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005190 return Result;
5191
5192 return E;
5193
Chris Lattner934edb22007-12-28 05:31:15 +00005194 // Everything else: we simply don't reason about them.
5195 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005196 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005197 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005198}
Mike Stump11289f42009-09-09 15:08:12 +00005199
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005200
5201/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5202/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005203static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5204 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005205do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005206 // We should only be called for evaluating non-pointer expressions, or
5207 // expressions with a pointer type that are not used as references but instead
5208 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005209
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005210 // Our "symbolic interpreter" is just a dispatch off the currently
5211 // viewed AST node. We then recursively traverse the AST by calling
5212 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005213
5214 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005215 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005216 case Stmt::ImplicitCastExprClass: {
5217 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005218 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005219 E = IE->getSubExpr();
5220 continue;
5221 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005222 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005223 }
5224
John McCall28fc7092011-11-10 05:35:25 +00005225 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005226 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005227
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005228 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005229 // When we hit a DeclRefExpr we are looking at code that refers to a
5230 // variable's name. If it's not a reference variable we check if it has
5231 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005232 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005233
Richard Smith40f08eb2014-01-30 22:05:38 +00005234 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005235 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005236 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005237
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005238 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5239 // Check if it refers to itself, e.g. "int& i = i;".
5240 if (V == ParentDecl)
5241 return DR;
5242
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005243 if (V->hasLocalStorage()) {
5244 if (!V->getType()->isReferenceType())
5245 return DR;
5246
5247 // Reference variable, follow through to the expression that
5248 // it points to.
5249 if (V->hasInit()) {
5250 // Add the reference variable to the "trail".
5251 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005252 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005253 }
5254 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005255 }
Mike Stump11289f42009-09-09 15:08:12 +00005256
Craig Topperc3ec1492014-05-26 06:22:03 +00005257 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005258 }
Mike Stump11289f42009-09-09 15:08:12 +00005259
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005260 case Stmt::UnaryOperatorClass: {
5261 // The only unary operator that make sense to handle here
5262 // is Deref. All others don't resolve to a "name." This includes
5263 // handling all sorts of rvalues passed to a unary operator.
5264 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005265
John McCalle3027922010-08-25 11:45:40 +00005266 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005267 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005268
Craig Topperc3ec1492014-05-26 06:22:03 +00005269 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005270 }
Mike Stump11289f42009-09-09 15:08:12 +00005271
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005272 case Stmt::ArraySubscriptExprClass: {
5273 // Array subscripts are potential references to data on the stack. We
5274 // retrieve the DeclRefExpr* for the array variable if it indeed
5275 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005276 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005277 }
Mike Stump11289f42009-09-09 15:08:12 +00005278
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005279 case Stmt::ConditionalOperatorClass: {
5280 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005281 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005282 ConditionalOperator *C = cast<ConditionalOperator>(E);
5283
Anders Carlsson801c5c72007-11-30 19:04:31 +00005284 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005285 if (Expr *LHSExpr = C->getLHS()) {
5286 // In C++, we can have a throw-expression, which has 'void' type.
5287 if (!LHSExpr->getType()->isVoidType())
5288 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5289 return LHS;
5290 }
5291
5292 // In C++, we can have a throw-expression, which has 'void' type.
5293 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005294 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005295
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005296 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005297 }
Mike Stump11289f42009-09-09 15:08:12 +00005298
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005299 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005300 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005301 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005302
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005303 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005304 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005305 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005306
5307 // Check whether the member type is itself a reference, in which case
5308 // we're not going to refer to the member, but to what the member refers to.
5309 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005310 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005311
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005312 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005313 }
Mike Stump11289f42009-09-09 15:08:12 +00005314
Douglas Gregorfe314812011-06-21 17:03:29 +00005315 case Stmt::MaterializeTemporaryExprClass:
5316 if (Expr *Result = EvalVal(
5317 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005318 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005319 return Result;
5320
5321 return E;
5322
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005323 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005324 // Check that we don't return or take the address of a reference to a
5325 // temporary. This is only useful in C++.
5326 if (!E->isTypeDependent() && E->isRValue())
5327 return E;
5328
5329 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005330 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005331 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005332} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005333}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005334
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005335void
5336Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5337 SourceLocation ReturnLoc,
5338 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005339 const AttrVec *Attrs,
5340 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005341 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5342
5343 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005344 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5345 CheckNonNullExpr(*this, RetValExp))
5346 Diag(ReturnLoc, diag::warn_null_ret)
5347 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005348
5349 // C++11 [basic.stc.dynamic.allocation]p4:
5350 // If an allocation function declared with a non-throwing
5351 // exception-specification fails to allocate storage, it shall return
5352 // a null pointer. Any other allocation function that fails to allocate
5353 // storage shall indicate failure only by throwing an exception [...]
5354 if (FD) {
5355 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5356 if (Op == OO_New || Op == OO_Array_New) {
5357 const FunctionProtoType *Proto
5358 = FD->getType()->castAs<FunctionProtoType>();
5359 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5360 CheckNonNullExpr(*this, RetValExp))
5361 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5362 << FD << getLangOpts().CPlusPlus11;
5363 }
5364 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005365}
5366
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005367//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5368
5369/// Check for comparisons of floating point operands using != and ==.
5370/// Issue a warning if these are no self-comparisons, as they are not likely
5371/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005372void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005373 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5374 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005375
5376 // Special case: check for x == x (which is OK).
5377 // Do not emit warnings for such cases.
5378 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5379 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5380 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005381 return;
Mike Stump11289f42009-09-09 15:08:12 +00005382
5383
Ted Kremenekeda40e22007-11-29 00:59:04 +00005384 // Special case: check for comparisons against literals that can be exactly
5385 // represented by APFloat. In such cases, do not emit a warning. This
5386 // is a heuristic: often comparison against such literals are used to
5387 // detect if a value in a variable has not changed. This clearly can
5388 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005389 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5390 if (FLL->isExact())
5391 return;
5392 } else
5393 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5394 if (FLR->isExact())
5395 return;
Mike Stump11289f42009-09-09 15:08:12 +00005396
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005397 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005398 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005399 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005400 return;
Mike Stump11289f42009-09-09 15:08:12 +00005401
David Blaikie1f4ff152012-07-16 20:47:22 +00005402 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005403 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005404 return;
Mike Stump11289f42009-09-09 15:08:12 +00005405
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005406 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005407 Diag(Loc, diag::warn_floatingpoint_eq)
5408 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005409}
John McCallca01b222010-01-04 23:21:16 +00005410
John McCall70aa5392010-01-06 05:24:50 +00005411//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5412//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005413
John McCall70aa5392010-01-06 05:24:50 +00005414namespace {
John McCallca01b222010-01-04 23:21:16 +00005415
John McCall70aa5392010-01-06 05:24:50 +00005416/// Structure recording the 'active' range of an integer-valued
5417/// expression.
5418struct IntRange {
5419 /// The number of bits active in the int.
5420 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005421
John McCall70aa5392010-01-06 05:24:50 +00005422 /// True if the int is known not to have negative values.
5423 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005424
John McCall70aa5392010-01-06 05:24:50 +00005425 IntRange(unsigned Width, bool NonNegative)
5426 : Width(Width), NonNegative(NonNegative)
5427 {}
John McCallca01b222010-01-04 23:21:16 +00005428
John McCall817d4af2010-11-10 23:38:19 +00005429 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005430 static IntRange forBoolType() {
5431 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005432 }
5433
John McCall817d4af2010-11-10 23:38:19 +00005434 /// Returns the range of an opaque value of the given integral type.
5435 static IntRange forValueOfType(ASTContext &C, QualType T) {
5436 return forValueOfCanonicalType(C,
5437 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005438 }
5439
John McCall817d4af2010-11-10 23:38:19 +00005440 /// Returns the range of an opaque value of a canonical integral type.
5441 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005442 assert(T->isCanonicalUnqualified());
5443
5444 if (const VectorType *VT = dyn_cast<VectorType>(T))
5445 T = VT->getElementType().getTypePtr();
5446 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5447 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005448 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5449 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005450
David Majnemer6a426652013-06-07 22:07:20 +00005451 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005452 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005453 EnumDecl *Enum = ET->getDecl();
5454 if (!Enum->isCompleteDefinition())
5455 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005456
David Majnemer6a426652013-06-07 22:07:20 +00005457 unsigned NumPositive = Enum->getNumPositiveBits();
5458 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005459
David Majnemer6a426652013-06-07 22:07:20 +00005460 if (NumNegative == 0)
5461 return IntRange(NumPositive, true/*NonNegative*/);
5462 else
5463 return IntRange(std::max(NumPositive + 1, NumNegative),
5464 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005465 }
John McCall70aa5392010-01-06 05:24:50 +00005466
5467 const BuiltinType *BT = cast<BuiltinType>(T);
5468 assert(BT->isInteger());
5469
5470 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5471 }
5472
John McCall817d4af2010-11-10 23:38:19 +00005473 /// Returns the "target" range of a canonical integral type, i.e.
5474 /// the range of values expressible in the type.
5475 ///
5476 /// This matches forValueOfCanonicalType except that enums have the
5477 /// full range of their type, not the range of their enumerators.
5478 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5479 assert(T->isCanonicalUnqualified());
5480
5481 if (const VectorType *VT = dyn_cast<VectorType>(T))
5482 T = VT->getElementType().getTypePtr();
5483 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5484 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005485 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5486 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005487 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005488 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005489
5490 const BuiltinType *BT = cast<BuiltinType>(T);
5491 assert(BT->isInteger());
5492
5493 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5494 }
5495
5496 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005497 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005498 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005499 L.NonNegative && R.NonNegative);
5500 }
5501
John McCall817d4af2010-11-10 23:38:19 +00005502 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005503 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005504 return IntRange(std::min(L.Width, R.Width),
5505 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005506 }
5507};
5508
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005509static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5510 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005511 if (value.isSigned() && value.isNegative())
5512 return IntRange(value.getMinSignedBits(), false);
5513
5514 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005515 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005516
5517 // isNonNegative() just checks the sign bit without considering
5518 // signedness.
5519 return IntRange(value.getActiveBits(), true);
5520}
5521
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005522static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5523 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005524 if (result.isInt())
5525 return GetValueRange(C, result.getInt(), MaxWidth);
5526
5527 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005528 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5529 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5530 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5531 R = IntRange::join(R, El);
5532 }
John McCall70aa5392010-01-06 05:24:50 +00005533 return R;
5534 }
5535
5536 if (result.isComplexInt()) {
5537 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5538 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5539 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005540 }
5541
5542 // This can happen with lossless casts to intptr_t of "based" lvalues.
5543 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005544 // FIXME: The only reason we need to pass the type in here is to get
5545 // the sign right on this one case. It would be nice if APValue
5546 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005547 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005548 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005549}
John McCall70aa5392010-01-06 05:24:50 +00005550
Eli Friedmane6d33952013-07-08 20:20:06 +00005551static QualType GetExprType(Expr *E) {
5552 QualType Ty = E->getType();
5553 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5554 Ty = AtomicRHS->getValueType();
5555 return Ty;
5556}
5557
John McCall70aa5392010-01-06 05:24:50 +00005558/// Pseudo-evaluate the given integer expression, estimating the
5559/// range of values it might take.
5560///
5561/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005562static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005563 E = E->IgnoreParens();
5564
5565 // Try a full evaluation first.
5566 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005567 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005568 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005569
5570 // I think we only want to look through implicit casts here; if the
5571 // user has an explicit widening cast, we should treat the value as
5572 // being of the new, wider type.
5573 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005574 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005575 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5576
Eli Friedmane6d33952013-07-08 20:20:06 +00005577 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005578
John McCalle3027922010-08-25 11:45:40 +00005579 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005580
John McCall70aa5392010-01-06 05:24:50 +00005581 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005582 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005583 return OutputTypeRange;
5584
5585 IntRange SubRange
5586 = GetExprRange(C, CE->getSubExpr(),
5587 std::min(MaxWidth, OutputTypeRange.Width));
5588
5589 // Bail out if the subexpr's range is as wide as the cast type.
5590 if (SubRange.Width >= OutputTypeRange.Width)
5591 return OutputTypeRange;
5592
5593 // Otherwise, we take the smaller width, and we're non-negative if
5594 // either the output type or the subexpr is.
5595 return IntRange(SubRange.Width,
5596 SubRange.NonNegative || OutputTypeRange.NonNegative);
5597 }
5598
5599 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5600 // If we can fold the condition, just take that operand.
5601 bool CondResult;
5602 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5603 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5604 : CO->getFalseExpr(),
5605 MaxWidth);
5606
5607 // Otherwise, conservatively merge.
5608 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5609 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5610 return IntRange::join(L, R);
5611 }
5612
5613 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5614 switch (BO->getOpcode()) {
5615
5616 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005617 case BO_LAnd:
5618 case BO_LOr:
5619 case BO_LT:
5620 case BO_GT:
5621 case BO_LE:
5622 case BO_GE:
5623 case BO_EQ:
5624 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005625 return IntRange::forBoolType();
5626
John McCallc3688382011-07-13 06:35:24 +00005627 // The type of the assignments is the type of the LHS, so the RHS
5628 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005629 case BO_MulAssign:
5630 case BO_DivAssign:
5631 case BO_RemAssign:
5632 case BO_AddAssign:
5633 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005634 case BO_XorAssign:
5635 case BO_OrAssign:
5636 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005637 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005638
John McCallc3688382011-07-13 06:35:24 +00005639 // Simple assignments just pass through the RHS, which will have
5640 // been coerced to the LHS type.
5641 case BO_Assign:
5642 // TODO: bitfields?
5643 return GetExprRange(C, BO->getRHS(), MaxWidth);
5644
John McCall70aa5392010-01-06 05:24:50 +00005645 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005646 case BO_PtrMemD:
5647 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005648 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005649
John McCall2ce81ad2010-01-06 22:07:33 +00005650 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005651 case BO_And:
5652 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005653 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5654 GetExprRange(C, BO->getRHS(), MaxWidth));
5655
John McCall70aa5392010-01-06 05:24:50 +00005656 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005657 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005658 // ...except that we want to treat '1 << (blah)' as logically
5659 // positive. It's an important idiom.
5660 if (IntegerLiteral *I
5661 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5662 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005663 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005664 return IntRange(R.Width, /*NonNegative*/ true);
5665 }
5666 }
5667 // fallthrough
5668
John McCalle3027922010-08-25 11:45:40 +00005669 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005670 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005671
John McCall2ce81ad2010-01-06 22:07:33 +00005672 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005673 case BO_Shr:
5674 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005675 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5676
5677 // If the shift amount is a positive constant, drop the width by
5678 // that much.
5679 llvm::APSInt shift;
5680 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5681 shift.isNonNegative()) {
5682 unsigned zext = shift.getZExtValue();
5683 if (zext >= L.Width)
5684 L.Width = (L.NonNegative ? 0 : 1);
5685 else
5686 L.Width -= zext;
5687 }
5688
5689 return L;
5690 }
5691
5692 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005693 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005694 return GetExprRange(C, BO->getRHS(), MaxWidth);
5695
John McCall2ce81ad2010-01-06 22:07:33 +00005696 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005697 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005698 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005699 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005700 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005701
John McCall51431812011-07-14 22:39:48 +00005702 // The width of a division result is mostly determined by the size
5703 // of the LHS.
5704 case BO_Div: {
5705 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005706 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005707 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5708
5709 // If the divisor is constant, use that.
5710 llvm::APSInt divisor;
5711 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5712 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5713 if (log2 >= L.Width)
5714 L.Width = (L.NonNegative ? 0 : 1);
5715 else
5716 L.Width = std::min(L.Width - log2, MaxWidth);
5717 return L;
5718 }
5719
5720 // Otherwise, just use the LHS's width.
5721 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5722 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5723 }
5724
5725 // The result of a remainder can't be larger than the result of
5726 // either side.
5727 case BO_Rem: {
5728 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005729 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005730 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5731 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5732
5733 IntRange meet = IntRange::meet(L, R);
5734 meet.Width = std::min(meet.Width, MaxWidth);
5735 return meet;
5736 }
5737
5738 // The default behavior is okay for these.
5739 case BO_Mul:
5740 case BO_Add:
5741 case BO_Xor:
5742 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005743 break;
5744 }
5745
John McCall51431812011-07-14 22:39:48 +00005746 // The default case is to treat the operation as if it were closed
5747 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005748 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5749 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5750 return IntRange::join(L, R);
5751 }
5752
5753 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5754 switch (UO->getOpcode()) {
5755 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005756 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005757 return IntRange::forBoolType();
5758
5759 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005760 case UO_Deref:
5761 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005762 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005763
5764 default:
5765 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5766 }
5767 }
5768
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005769 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5770 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5771
John McCalld25db7e2013-05-06 21:39:12 +00005772 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005773 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005774 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005775
Eli Friedmane6d33952013-07-08 20:20:06 +00005776 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005777}
John McCall263a48b2010-01-04 23:31:57 +00005778
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005779static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005780 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005781}
5782
John McCall263a48b2010-01-04 23:31:57 +00005783/// Checks whether the given value, which currently has the given
5784/// source semantics, has the same value when coerced through the
5785/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005786static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5787 const llvm::fltSemantics &Src,
5788 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005789 llvm::APFloat truncated = value;
5790
5791 bool ignored;
5792 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5793 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5794
5795 return truncated.bitwiseIsEqual(value);
5796}
5797
5798/// Checks whether the given value, which currently has the given
5799/// source semantics, has the same value when coerced through the
5800/// target semantics.
5801///
5802/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005803static bool IsSameFloatAfterCast(const APValue &value,
5804 const llvm::fltSemantics &Src,
5805 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005806 if (value.isFloat())
5807 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5808
5809 if (value.isVector()) {
5810 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5811 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5812 return false;
5813 return true;
5814 }
5815
5816 assert(value.isComplexFloat());
5817 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5818 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5819}
5820
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005821static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005822
Ted Kremenek6274be42010-09-23 21:43:44 +00005823static bool IsZero(Sema &S, Expr *E) {
5824 // Suppress cases where we are comparing against an enum constant.
5825 if (const DeclRefExpr *DR =
5826 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5827 if (isa<EnumConstantDecl>(DR->getDecl()))
5828 return false;
5829
5830 // Suppress cases where the '0' value is expanded from a macro.
5831 if (E->getLocStart().isMacroID())
5832 return false;
5833
John McCallcc7e5bf2010-05-06 08:58:33 +00005834 llvm::APSInt Value;
5835 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5836}
5837
John McCall2551c1b2010-10-06 00:25:24 +00005838static bool HasEnumType(Expr *E) {
5839 // Strip off implicit integral promotions.
5840 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005841 if (ICE->getCastKind() != CK_IntegralCast &&
5842 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005843 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005844 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005845 }
5846
5847 return E->getType()->isEnumeralType();
5848}
5849
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005850static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005851 // Disable warning in template instantiations.
5852 if (!S.ActiveTemplateInstantiations.empty())
5853 return;
5854
John McCalle3027922010-08-25 11:45:40 +00005855 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005856 if (E->isValueDependent())
5857 return;
5858
John McCalle3027922010-08-25 11:45:40 +00005859 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005860 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005861 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005862 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005863 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005864 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005865 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005866 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005867 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005868 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005869 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005870 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005871 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005872 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005873 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005874 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5875 }
5876}
5877
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005878static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005879 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005880 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005881 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005882 // Disable warning in template instantiations.
5883 if (!S.ActiveTemplateInstantiations.empty())
5884 return;
5885
Richard Trieu0f097742014-04-04 04:13:47 +00005886 // TODO: Investigate using GetExprRange() to get tighter bounds
5887 // on the bit ranges.
5888 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005889 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5890 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005891 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5892 unsigned OtherWidth = OtherRange.Width;
5893
5894 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5895
Richard Trieu560910c2012-11-14 22:50:24 +00005896 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005897 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005898 return;
5899
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005900 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005901 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005902
Richard Trieu0f097742014-04-04 04:13:47 +00005903 // Used for diagnostic printout.
5904 enum {
5905 LiteralConstant = 0,
5906 CXXBoolLiteralTrue,
5907 CXXBoolLiteralFalse
5908 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005909
Richard Trieu0f097742014-04-04 04:13:47 +00005910 if (!OtherIsBooleanType) {
5911 QualType ConstantT = Constant->getType();
5912 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005913
Richard Trieu0f097742014-04-04 04:13:47 +00005914 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5915 return;
5916 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5917 "comparison with non-integer type");
5918
5919 bool ConstantSigned = ConstantT->isSignedIntegerType();
5920 bool CommonSigned = CommonT->isSignedIntegerType();
5921
5922 bool EqualityOnly = false;
5923
5924 if (CommonSigned) {
5925 // The common type is signed, therefore no signed to unsigned conversion.
5926 if (!OtherRange.NonNegative) {
5927 // Check that the constant is representable in type OtherT.
5928 if (ConstantSigned) {
5929 if (OtherWidth >= Value.getMinSignedBits())
5930 return;
5931 } else { // !ConstantSigned
5932 if (OtherWidth >= Value.getActiveBits() + 1)
5933 return;
5934 }
5935 } else { // !OtherSigned
5936 // Check that the constant is representable in type OtherT.
5937 // Negative values are out of range.
5938 if (ConstantSigned) {
5939 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5940 return;
5941 } else { // !ConstantSigned
5942 if (OtherWidth >= Value.getActiveBits())
5943 return;
5944 }
Richard Trieu560910c2012-11-14 22:50:24 +00005945 }
Richard Trieu0f097742014-04-04 04:13:47 +00005946 } else { // !CommonSigned
5947 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005948 if (OtherWidth >= Value.getActiveBits())
5949 return;
Craig Toppercf360162014-06-18 05:13:11 +00005950 } else { // OtherSigned
5951 assert(!ConstantSigned &&
5952 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00005953 // Check to see if the constant is representable in OtherT.
5954 if (OtherWidth > Value.getActiveBits())
5955 return;
5956 // Check to see if the constant is equivalent to a negative value
5957 // cast to CommonT.
5958 if (S.Context.getIntWidth(ConstantT) ==
5959 S.Context.getIntWidth(CommonT) &&
5960 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5961 return;
5962 // The constant value rests between values that OtherT can represent
5963 // after conversion. Relational comparison still works, but equality
5964 // comparisons will be tautological.
5965 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005966 }
5967 }
Richard Trieu0f097742014-04-04 04:13:47 +00005968
5969 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5970
5971 if (op == BO_EQ || op == BO_NE) {
5972 IsTrue = op == BO_NE;
5973 } else if (EqualityOnly) {
5974 return;
5975 } else if (RhsConstant) {
5976 if (op == BO_GT || op == BO_GE)
5977 IsTrue = !PositiveConstant;
5978 else // op == BO_LT || op == BO_LE
5979 IsTrue = PositiveConstant;
5980 } else {
5981 if (op == BO_LT || op == BO_LE)
5982 IsTrue = !PositiveConstant;
5983 else // op == BO_GT || op == BO_GE
5984 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005985 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005986 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005987 // Other isKnownToHaveBooleanValue
5988 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5989 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5990 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5991
5992 static const struct LinkedConditions {
5993 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5994 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5995 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5996 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5997 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5998 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5999
6000 } TruthTable = {
6001 // Constant on LHS. | Constant on RHS. |
6002 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6003 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6004 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6005 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6006 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6007 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6008 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6009 };
6010
6011 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6012
6013 enum ConstantValue ConstVal = Zero;
6014 if (Value.isUnsigned() || Value.isNonNegative()) {
6015 if (Value == 0) {
6016 LiteralOrBoolConstant =
6017 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6018 ConstVal = Zero;
6019 } else if (Value == 1) {
6020 LiteralOrBoolConstant =
6021 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6022 ConstVal = One;
6023 } else {
6024 LiteralOrBoolConstant = LiteralConstant;
6025 ConstVal = GT_One;
6026 }
6027 } else {
6028 ConstVal = LT_Zero;
6029 }
6030
6031 CompareBoolWithConstantResult CmpRes;
6032
6033 switch (op) {
6034 case BO_LT:
6035 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6036 break;
6037 case BO_GT:
6038 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6039 break;
6040 case BO_LE:
6041 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6042 break;
6043 case BO_GE:
6044 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6045 break;
6046 case BO_EQ:
6047 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6048 break;
6049 case BO_NE:
6050 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6051 break;
6052 default:
6053 CmpRes = Unkwn;
6054 break;
6055 }
6056
6057 if (CmpRes == AFals) {
6058 IsTrue = false;
6059 } else if (CmpRes == ATrue) {
6060 IsTrue = true;
6061 } else {
6062 return;
6063 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006064 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006065
6066 // If this is a comparison to an enum constant, include that
6067 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006068 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006069 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6070 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6071
6072 SmallString<64> PrettySourceValue;
6073 llvm::raw_svector_ostream OS(PrettySourceValue);
6074 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006075 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006076 else
6077 OS << Value;
6078
Richard Trieu0f097742014-04-04 04:13:47 +00006079 S.DiagRuntimeBehavior(
6080 E->getOperatorLoc(), E,
6081 S.PDiag(diag::warn_out_of_range_compare)
6082 << OS.str() << LiteralOrBoolConstant
6083 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6084 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006085}
6086
John McCallcc7e5bf2010-05-06 08:58:33 +00006087/// Analyze the operands of the given comparison. Implements the
6088/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006089static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006090 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6091 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006092}
John McCall263a48b2010-01-04 23:31:57 +00006093
John McCallca01b222010-01-04 23:21:16 +00006094/// \brief Implements -Wsign-compare.
6095///
Richard Trieu82402a02011-09-15 21:56:47 +00006096/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006097static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006098 // The type the comparison is being performed in.
6099 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006100
6101 // Only analyze comparison operators where both sides have been converted to
6102 // the same type.
6103 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6104 return AnalyzeImpConvsInComparison(S, E);
6105
6106 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006107 if (E->isValueDependent())
6108 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006109
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006110 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6111 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006112
6113 bool IsComparisonConstant = false;
6114
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006115 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006116 // of 'true' or 'false'.
6117 if (T->isIntegralType(S.Context)) {
6118 llvm::APSInt RHSValue;
6119 bool IsRHSIntegralLiteral =
6120 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6121 llvm::APSInt LHSValue;
6122 bool IsLHSIntegralLiteral =
6123 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6124 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6125 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6126 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6127 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6128 else
6129 IsComparisonConstant =
6130 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006131 } else if (!T->hasUnsignedIntegerRepresentation())
6132 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006133
John McCallcc7e5bf2010-05-06 08:58:33 +00006134 // We don't do anything special if this isn't an unsigned integral
6135 // comparison: we're only interested in integral comparisons, and
6136 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006137 //
6138 // We also don't care about value-dependent expressions or expressions
6139 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006140 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006141 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006142
John McCallcc7e5bf2010-05-06 08:58:33 +00006143 // Check to see if one of the (unmodified) operands is of different
6144 // signedness.
6145 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006146 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6147 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006148 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006149 signedOperand = LHS;
6150 unsignedOperand = RHS;
6151 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6152 signedOperand = RHS;
6153 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006154 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006155 CheckTrivialUnsignedComparison(S, E);
6156 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006157 }
6158
John McCallcc7e5bf2010-05-06 08:58:33 +00006159 // Otherwise, calculate the effective range of the signed operand.
6160 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006161
John McCallcc7e5bf2010-05-06 08:58:33 +00006162 // Go ahead and analyze implicit conversions in the operands. Note
6163 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006164 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6165 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006166
John McCallcc7e5bf2010-05-06 08:58:33 +00006167 // If the signed range is non-negative, -Wsign-compare won't fire,
6168 // but we should still check for comparisons which are always true
6169 // or false.
6170 if (signedRange.NonNegative)
6171 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006172
6173 // For (in)equality comparisons, if the unsigned operand is a
6174 // constant which cannot collide with a overflowed signed operand,
6175 // then reinterpreting the signed operand as unsigned will not
6176 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006177 if (E->isEqualityOp()) {
6178 unsigned comparisonWidth = S.Context.getIntWidth(T);
6179 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006180
John McCallcc7e5bf2010-05-06 08:58:33 +00006181 // We should never be unable to prove that the unsigned operand is
6182 // non-negative.
6183 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6184
6185 if (unsignedRange.Width < comparisonWidth)
6186 return;
6187 }
6188
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006189 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6190 S.PDiag(diag::warn_mixed_sign_comparison)
6191 << LHS->getType() << RHS->getType()
6192 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006193}
6194
John McCall1f425642010-11-11 03:21:53 +00006195/// Analyzes an attempt to assign the given value to a bitfield.
6196///
6197/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006198static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6199 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006200 assert(Bitfield->isBitField());
6201 if (Bitfield->isInvalidDecl())
6202 return false;
6203
John McCalldeebbcf2010-11-11 05:33:51 +00006204 // White-list bool bitfields.
6205 if (Bitfield->getType()->isBooleanType())
6206 return false;
6207
Douglas Gregor789adec2011-02-04 13:09:01 +00006208 // Ignore value- or type-dependent expressions.
6209 if (Bitfield->getBitWidth()->isValueDependent() ||
6210 Bitfield->getBitWidth()->isTypeDependent() ||
6211 Init->isValueDependent() ||
6212 Init->isTypeDependent())
6213 return false;
6214
John McCall1f425642010-11-11 03:21:53 +00006215 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6216
Richard Smith5fab0c92011-12-28 19:48:30 +00006217 llvm::APSInt Value;
6218 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006219 return false;
6220
John McCall1f425642010-11-11 03:21:53 +00006221 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006222 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006223
6224 if (OriginalWidth <= FieldWidth)
6225 return false;
6226
Eli Friedmanc267a322012-01-26 23:11:39 +00006227 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006228 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006229 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006230
Eli Friedmanc267a322012-01-26 23:11:39 +00006231 // Check whether the stored value is equal to the original value.
6232 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006233 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006234 return false;
6235
Eli Friedmanc267a322012-01-26 23:11:39 +00006236 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006237 // therefore don't strictly fit into a signed bitfield of width 1.
6238 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006239 return false;
6240
John McCall1f425642010-11-11 03:21:53 +00006241 std::string PrettyValue = Value.toString(10);
6242 std::string PrettyTrunc = TruncatedValue.toString(10);
6243
6244 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6245 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6246 << Init->getSourceRange();
6247
6248 return true;
6249}
6250
John McCalld2a53122010-11-09 23:24:47 +00006251/// Analyze the given simple or compound assignment for warning-worthy
6252/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006253static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006254 // Just recurse on the LHS.
6255 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6256
6257 // We want to recurse on the RHS as normal unless we're assigning to
6258 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006259 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006260 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006261 E->getOperatorLoc())) {
6262 // Recurse, ignoring any implicit conversions on the RHS.
6263 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6264 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006265 }
6266 }
6267
6268 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6269}
6270
John McCall263a48b2010-01-04 23:31:57 +00006271/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006272static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006273 SourceLocation CContext, unsigned diag,
6274 bool pruneControlFlow = false) {
6275 if (pruneControlFlow) {
6276 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6277 S.PDiag(diag)
6278 << SourceType << T << E->getSourceRange()
6279 << SourceRange(CContext));
6280 return;
6281 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006282 S.Diag(E->getExprLoc(), diag)
6283 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6284}
6285
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006286/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006287static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006288 SourceLocation CContext, unsigned diag,
6289 bool pruneControlFlow = false) {
6290 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006291}
6292
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006293/// Diagnose an implicit cast from a literal expression. Does not warn when the
6294/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006295void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6296 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006297 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006298 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006299 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006300 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6301 T->hasUnsignedIntegerRepresentation());
6302 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006303 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006304 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006305 return;
6306
Eli Friedman07185912013-08-29 23:44:43 +00006307 // FIXME: Force the precision of the source value down so we don't print
6308 // digits which are usually useless (we don't really care here if we
6309 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6310 // would automatically print the shortest representation, but it's a bit
6311 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006312 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006313 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6314 precision = (precision * 59 + 195) / 196;
6315 Value.toString(PrettySourceValue, precision);
6316
David Blaikie9b88cc02012-05-15 17:18:27 +00006317 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006318 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6319 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6320 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006321 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006322
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006323 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006324 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6325 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006326}
6327
John McCall18a2c2c2010-11-09 22:22:12 +00006328std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6329 if (!Range.Width) return "0";
6330
6331 llvm::APSInt ValueInRange = Value;
6332 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006333 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006334 return ValueInRange.toString(10);
6335}
6336
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006337static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6338 if (!isa<ImplicitCastExpr>(Ex))
6339 return false;
6340
6341 Expr *InnerE = Ex->IgnoreParenImpCasts();
6342 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6343 const Type *Source =
6344 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6345 if (Target->isDependentType())
6346 return false;
6347
6348 const BuiltinType *FloatCandidateBT =
6349 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6350 const Type *BoolCandidateType = ToBool ? Target : Source;
6351
6352 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6353 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6354}
6355
6356void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6357 SourceLocation CC) {
6358 unsigned NumArgs = TheCall->getNumArgs();
6359 for (unsigned i = 0; i < NumArgs; ++i) {
6360 Expr *CurrA = TheCall->getArg(i);
6361 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6362 continue;
6363
6364 bool IsSwapped = ((i > 0) &&
6365 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6366 IsSwapped |= ((i < (NumArgs - 1)) &&
6367 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6368 if (IsSwapped) {
6369 // Warn on this floating-point to bool conversion.
6370 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6371 CurrA->getType(), CC,
6372 diag::warn_impcast_floating_point_to_bool);
6373 }
6374 }
6375}
6376
Richard Trieu5b993502014-10-15 03:42:06 +00006377static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6378 SourceLocation CC) {
6379 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6380 E->getExprLoc()))
6381 return;
6382
6383 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6384 const Expr::NullPointerConstantKind NullKind =
6385 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6386 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6387 return;
6388
6389 // Return if target type is a safe conversion.
6390 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6391 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6392 return;
6393
6394 SourceLocation Loc = E->getSourceRange().getBegin();
6395
6396 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6397 if (NullKind == Expr::NPCK_GNUNull) {
6398 if (Loc.isMacroID())
6399 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6400 }
6401
6402 // Only warn if the null and context location are in the same macro expansion.
6403 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6404 return;
6405
6406 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6407 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6408 << FixItHint::CreateReplacement(Loc,
6409 S.getFixItZeroLiteralForType(T, Loc));
6410}
6411
John McCallcc7e5bf2010-05-06 08:58:33 +00006412void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006413 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006414 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006415
John McCallcc7e5bf2010-05-06 08:58:33 +00006416 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6417 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6418 if (Source == Target) return;
6419 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006420
Chandler Carruthc22845a2011-07-26 05:40:03 +00006421 // If the conversion context location is invalid don't complain. We also
6422 // don't want to emit a warning if the issue occurs from the expansion of
6423 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6424 // delay this check as long as possible. Once we detect we are in that
6425 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006426 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006427 return;
6428
Richard Trieu021baa32011-09-23 20:10:00 +00006429 // Diagnose implicit casts to bool.
6430 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6431 if (isa<StringLiteral>(E))
6432 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006433 // and expressions, for instance, assert(0 && "error here"), are
6434 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006435 return DiagnoseImpCast(S, E, T, CC,
6436 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006437 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6438 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6439 // This covers the literal expressions that evaluate to Objective-C
6440 // objects.
6441 return DiagnoseImpCast(S, E, T, CC,
6442 diag::warn_impcast_objective_c_literal_to_bool);
6443 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006444 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6445 // Warn on pointer to bool conversion that is always true.
6446 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6447 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006448 }
Richard Trieu021baa32011-09-23 20:10:00 +00006449 }
John McCall263a48b2010-01-04 23:31:57 +00006450
6451 // Strip vector types.
6452 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006453 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006454 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006455 return;
John McCallacf0ee52010-10-08 02:01:28 +00006456 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006457 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006458
6459 // If the vector cast is cast between two vectors of the same size, it is
6460 // a bitcast, not a conversion.
6461 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6462 return;
John McCall263a48b2010-01-04 23:31:57 +00006463
6464 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6465 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6466 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006467 if (auto VecTy = dyn_cast<VectorType>(Target))
6468 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006469
6470 // Strip complex types.
6471 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006472 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006473 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006474 return;
6475
John McCallacf0ee52010-10-08 02:01:28 +00006476 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006477 }
John McCall263a48b2010-01-04 23:31:57 +00006478
6479 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6480 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6481 }
6482
6483 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6484 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6485
6486 // If the source is floating point...
6487 if (SourceBT && SourceBT->isFloatingPoint()) {
6488 // ...and the target is floating point...
6489 if (TargetBT && TargetBT->isFloatingPoint()) {
6490 // ...then warn if we're dropping FP rank.
6491
6492 // Builtin FP kinds are ordered by increasing FP rank.
6493 if (SourceBT->getKind() > TargetBT->getKind()) {
6494 // Don't warn about float constants that are precisely
6495 // representable in the target type.
6496 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006497 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006498 // Value might be a float, a float vector, or a float complex.
6499 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006500 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6501 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006502 return;
6503 }
6504
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006505 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006506 return;
6507
John McCallacf0ee52010-10-08 02:01:28 +00006508 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006509 }
6510 return;
6511 }
6512
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006513 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006514 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006515 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006516 return;
6517
Chandler Carruth22c7a792011-02-17 11:05:49 +00006518 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006519 // We also want to warn on, e.g., "int i = -1.234"
6520 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6521 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6522 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6523
Chandler Carruth016ef402011-04-10 08:36:24 +00006524 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6525 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006526 } else {
6527 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6528 }
6529 }
John McCall263a48b2010-01-04 23:31:57 +00006530
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006531 // If the target is bool, warn if expr is a function or method call.
6532 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6533 isa<CallExpr>(E)) {
6534 // Check last argument of function call to see if it is an
6535 // implicit cast from a type matching the type the result
6536 // is being cast to.
6537 CallExpr *CEx = cast<CallExpr>(E);
6538 unsigned NumArgs = CEx->getNumArgs();
6539 if (NumArgs > 0) {
6540 Expr *LastA = CEx->getArg(NumArgs - 1);
6541 Expr *InnerE = LastA->IgnoreParenImpCasts();
6542 const Type *InnerType =
6543 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6544 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6545 // Warn on this floating-point to bool conversion
6546 DiagnoseImpCast(S, E, T, CC,
6547 diag::warn_impcast_floating_point_to_bool);
6548 }
6549 }
6550 }
John McCall263a48b2010-01-04 23:31:57 +00006551 return;
6552 }
6553
Richard Trieu5b993502014-10-15 03:42:06 +00006554 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006555
David Blaikie9366d2b2012-06-19 21:19:06 +00006556 if (!Source->isIntegerType() || !Target->isIntegerType())
6557 return;
6558
David Blaikie7555b6a2012-05-15 16:56:36 +00006559 // TODO: remove this early return once the false positives for constant->bool
6560 // in templates, macros, etc, are reduced or removed.
6561 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6562 return;
6563
John McCallcc7e5bf2010-05-06 08:58:33 +00006564 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006565 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006566
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006567 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006568 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006569 // TODO: this should happen for bitfield stores, too.
6570 llvm::APSInt Value(32);
6571 if (E->isIntegerConstantExpr(Value, S.Context)) {
6572 if (S.SourceMgr.isInSystemMacro(CC))
6573 return;
6574
John McCall18a2c2c2010-11-09 22:22:12 +00006575 std::string PrettySourceValue = Value.toString(10);
6576 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006577
Ted Kremenek33ba9952011-10-22 02:37:33 +00006578 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6579 S.PDiag(diag::warn_impcast_integer_precision_constant)
6580 << PrettySourceValue << PrettyTargetValue
6581 << E->getType() << T << E->getSourceRange()
6582 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006583 return;
6584 }
6585
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006586 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6587 if (S.SourceMgr.isInSystemMacro(CC))
6588 return;
6589
David Blaikie9455da02012-04-12 22:40:54 +00006590 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006591 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6592 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006593 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006594 }
6595
6596 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6597 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6598 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006599
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006600 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006601 return;
6602
John McCallcc7e5bf2010-05-06 08:58:33 +00006603 unsigned DiagID = diag::warn_impcast_integer_sign;
6604
6605 // Traditionally, gcc has warned about this under -Wsign-compare.
6606 // We also want to warn about it in -Wconversion.
6607 // So if -Wconversion is off, use a completely identical diagnostic
6608 // in the sign-compare group.
6609 // The conditional-checking code will
6610 if (ICContext) {
6611 DiagID = diag::warn_impcast_integer_sign_conditional;
6612 *ICContext = true;
6613 }
6614
John McCallacf0ee52010-10-08 02:01:28 +00006615 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006616 }
6617
Douglas Gregora78f1932011-02-22 02:45:07 +00006618 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006619 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6620 // type, to give us better diagnostics.
6621 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006622 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006623 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6624 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6625 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6626 SourceType = S.Context.getTypeDeclType(Enum);
6627 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6628 }
6629 }
6630
Douglas Gregora78f1932011-02-22 02:45:07 +00006631 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6632 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006633 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6634 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006635 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006636 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006637 return;
6638
Douglas Gregor364f7db2011-03-12 00:14:31 +00006639 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006640 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006641 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006642
John McCall263a48b2010-01-04 23:31:57 +00006643 return;
6644}
6645
David Blaikie18e9ac72012-05-15 21:57:38 +00006646void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6647 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006648
6649void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006650 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006651 E = E->IgnoreParenImpCasts();
6652
6653 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006654 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006655
John McCallacf0ee52010-10-08 02:01:28 +00006656 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006657 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006658 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006659 return;
6660}
6661
David Blaikie18e9ac72012-05-15 21:57:38 +00006662void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6663 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006664 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006665
6666 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006667 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6668 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006669
6670 // If -Wconversion would have warned about either of the candidates
6671 // for a signedness conversion to the context type...
6672 if (!Suspicious) return;
6673
6674 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006675 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006676 return;
6677
John McCallcc7e5bf2010-05-06 08:58:33 +00006678 // ...then check whether it would have warned about either of the
6679 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006680 if (E->getType() == T) return;
6681
6682 Suspicious = false;
6683 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6684 E->getType(), CC, &Suspicious);
6685 if (!Suspicious)
6686 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006687 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006688}
6689
Richard Trieu65724892014-11-15 06:37:39 +00006690/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6691/// Input argument E is a logical expression.
6692static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6693 if (S.getLangOpts().Bool)
6694 return;
6695 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6696}
6697
John McCallcc7e5bf2010-05-06 08:58:33 +00006698/// AnalyzeImplicitConversions - Find and report any interesting
6699/// implicit conversions in the given expression. There are a couple
6700/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006701void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006702 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006703 Expr *E = OrigE->IgnoreParenImpCasts();
6704
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006705 if (E->isTypeDependent() || E->isValueDependent())
6706 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006707
John McCallcc7e5bf2010-05-06 08:58:33 +00006708 // For conditional operators, we analyze the arguments as if they
6709 // were being fed directly into the output.
6710 if (isa<ConditionalOperator>(E)) {
6711 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006712 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006713 return;
6714 }
6715
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006716 // Check implicit argument conversions for function calls.
6717 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6718 CheckImplicitArgumentConversions(S, Call, CC);
6719
John McCallcc7e5bf2010-05-06 08:58:33 +00006720 // Go ahead and check any implicit conversions we might have skipped.
6721 // The non-canonical typecheck is just an optimization;
6722 // CheckImplicitConversion will filter out dead implicit conversions.
6723 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006724 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006725
6726 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006727
6728 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006729 if (POE->getResultExpr())
6730 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006731 }
6732
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006733 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6734 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6735
John McCallcc7e5bf2010-05-06 08:58:33 +00006736 // Skip past explicit casts.
6737 if (isa<ExplicitCastExpr>(E)) {
6738 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006739 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006740 }
6741
John McCalld2a53122010-11-09 23:24:47 +00006742 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6743 // Do a somewhat different check with comparison operators.
6744 if (BO->isComparisonOp())
6745 return AnalyzeComparison(S, BO);
6746
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006747 // And with simple assignments.
6748 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006749 return AnalyzeAssignment(S, BO);
6750 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006751
6752 // These break the otherwise-useful invariant below. Fortunately,
6753 // we don't really need to recurse into them, because any internal
6754 // expressions should have been analyzed already when they were
6755 // built into statements.
6756 if (isa<StmtExpr>(E)) return;
6757
6758 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006759 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006760
6761 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006762 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006763 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006764 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006765 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006766 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006767 if (!ChildExpr)
6768 continue;
6769
Richard Trieu955231d2014-01-25 01:10:35 +00006770 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006771 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006772 // Ignore checking string literals that are in logical and operators.
6773 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006774 continue;
6775 AnalyzeImplicitConversions(S, ChildExpr, CC);
6776 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006777
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006778 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006779 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6780 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006781 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00006782
6783 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6784 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006785 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006786 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006787
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006788 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6789 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00006790 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006791}
6792
6793} // end anonymous namespace
6794
Richard Trieu3bb8b562014-02-26 02:36:06 +00006795enum {
6796 AddressOf,
6797 FunctionPointer,
6798 ArrayPointer
6799};
6800
Richard Trieuc1888e02014-06-28 23:25:37 +00006801// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6802// Returns true when emitting a warning about taking the address of a reference.
6803static bool CheckForReference(Sema &SemaRef, const Expr *E,
6804 PartialDiagnostic PD) {
6805 E = E->IgnoreParenImpCasts();
6806
6807 const FunctionDecl *FD = nullptr;
6808
6809 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6810 if (!DRE->getDecl()->getType()->isReferenceType())
6811 return false;
6812 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6813 if (!M->getMemberDecl()->getType()->isReferenceType())
6814 return false;
6815 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6816 if (!Call->getCallReturnType()->isReferenceType())
6817 return false;
6818 FD = Call->getDirectCallee();
6819 } else {
6820 return false;
6821 }
6822
6823 SemaRef.Diag(E->getExprLoc(), PD);
6824
6825 // If possible, point to location of function.
6826 if (FD) {
6827 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6828 }
6829
6830 return true;
6831}
6832
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006833// Returns true if the SourceLocation is expanded from any macro body.
6834// Returns false if the SourceLocation is invalid, is from not in a macro
6835// expansion, or is from expanded from a top-level macro argument.
6836static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6837 if (Loc.isInvalid())
6838 return false;
6839
6840 while (Loc.isMacroID()) {
6841 if (SM.isMacroBodyExpansion(Loc))
6842 return true;
6843 Loc = SM.getImmediateMacroCallerLoc(Loc);
6844 }
6845
6846 return false;
6847}
6848
Richard Trieu3bb8b562014-02-26 02:36:06 +00006849/// \brief Diagnose pointers that are always non-null.
6850/// \param E the expression containing the pointer
6851/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6852/// compared to a null pointer
6853/// \param IsEqual True when the comparison is equal to a null pointer
6854/// \param Range Extra SourceRange to highlight in the diagnostic
6855void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6856 Expr::NullPointerConstantKind NullKind,
6857 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006858 if (!E)
6859 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006860
6861 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006862 if (E->getExprLoc().isMacroID()) {
6863 const SourceManager &SM = getSourceManager();
6864 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6865 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006866 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006867 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006868 E = E->IgnoreImpCasts();
6869
6870 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6871
Richard Trieuf7432752014-06-06 21:39:26 +00006872 if (isa<CXXThisExpr>(E)) {
6873 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6874 : diag::warn_this_bool_conversion;
6875 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6876 return;
6877 }
6878
Richard Trieu3bb8b562014-02-26 02:36:06 +00006879 bool IsAddressOf = false;
6880
6881 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6882 if (UO->getOpcode() != UO_AddrOf)
6883 return;
6884 IsAddressOf = true;
6885 E = UO->getSubExpr();
6886 }
6887
Richard Trieuc1888e02014-06-28 23:25:37 +00006888 if (IsAddressOf) {
6889 unsigned DiagID = IsCompare
6890 ? diag::warn_address_of_reference_null_compare
6891 : diag::warn_address_of_reference_bool_conversion;
6892 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6893 << IsEqual;
6894 if (CheckForReference(*this, E, PD)) {
6895 return;
6896 }
6897 }
6898
Richard Trieu3bb8b562014-02-26 02:36:06 +00006899 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006900 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006901 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6902 D = R->getDecl();
6903 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6904 D = M->getMemberDecl();
6905 }
6906
6907 // Weak Decls can be null.
6908 if (!D || D->isWeak())
6909 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006910
6911 // Check for parameter decl with nonnull attribute
6912 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6913 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6914 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6915 unsigned NumArgs = FD->getNumParams();
6916 llvm::SmallBitVector AttrNonNull(NumArgs);
6917 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6918 if (!NonNull->args_size()) {
6919 AttrNonNull.set(0, NumArgs);
6920 break;
6921 }
6922 for (unsigned Val : NonNull->args()) {
6923 if (Val >= NumArgs)
6924 continue;
6925 AttrNonNull.set(Val);
6926 }
6927 }
6928 if (!AttrNonNull.empty())
6929 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00006930 if (FD->getParamDecl(i) == PV &&
6931 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006932 std::string Str;
6933 llvm::raw_string_ostream S(Str);
6934 E->printPretty(S, nullptr, getPrintingPolicy());
6935 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
6936 : diag::warn_cast_nonnull_to_bool;
6937 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
6938 << Range << IsEqual;
6939 return;
6940 }
6941 }
6942 }
6943
Richard Trieu3bb8b562014-02-26 02:36:06 +00006944 QualType T = D->getType();
6945 const bool IsArray = T->isArrayType();
6946 const bool IsFunction = T->isFunctionType();
6947
Richard Trieuc1888e02014-06-28 23:25:37 +00006948 // Address of function is used to silence the function warning.
6949 if (IsAddressOf && IsFunction) {
6950 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006951 }
6952
6953 // Found nothing.
6954 if (!IsAddressOf && !IsFunction && !IsArray)
6955 return;
6956
6957 // Pretty print the expression for the diagnostic.
6958 std::string Str;
6959 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006960 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006961
6962 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6963 : diag::warn_impcast_pointer_to_bool;
6964 unsigned DiagType;
6965 if (IsAddressOf)
6966 DiagType = AddressOf;
6967 else if (IsFunction)
6968 DiagType = FunctionPointer;
6969 else if (IsArray)
6970 DiagType = ArrayPointer;
6971 else
6972 llvm_unreachable("Could not determine diagnostic.");
6973 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6974 << Range << IsEqual;
6975
6976 if (!IsFunction)
6977 return;
6978
6979 // Suggest '&' to silence the function warning.
6980 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6981 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6982
6983 // Check to see if '()' fixit should be emitted.
6984 QualType ReturnType;
6985 UnresolvedSet<4> NonTemplateOverloads;
6986 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6987 if (ReturnType.isNull())
6988 return;
6989
6990 if (IsCompare) {
6991 // There are two cases here. If there is null constant, the only suggest
6992 // for a pointer return type. If the null is 0, then suggest if the return
6993 // type is a pointer or an integer type.
6994 if (!ReturnType->isPointerType()) {
6995 if (NullKind == Expr::NPCK_ZeroExpression ||
6996 NullKind == Expr::NPCK_ZeroLiteral) {
6997 if (!ReturnType->isIntegerType())
6998 return;
6999 } else {
7000 return;
7001 }
7002 }
7003 } else { // !IsCompare
7004 // For function to bool, only suggest if the function pointer has bool
7005 // return type.
7006 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7007 return;
7008 }
7009 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007010 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007011}
7012
7013
John McCallcc7e5bf2010-05-06 08:58:33 +00007014/// Diagnoses "dangerous" implicit conversions within the given
7015/// expression (which is a full expression). Implements -Wconversion
7016/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007017///
7018/// \param CC the "context" location of the implicit conversion, i.e.
7019/// the most location of the syntactic entity requiring the implicit
7020/// conversion
7021void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007022 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007023 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007024 return;
7025
7026 // Don't diagnose for value- or type-dependent expressions.
7027 if (E->isTypeDependent() || E->isValueDependent())
7028 return;
7029
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007030 // Check for array bounds violations in cases where the check isn't triggered
7031 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7032 // ArraySubscriptExpr is on the RHS of a variable initialization.
7033 CheckArrayAccess(E);
7034
John McCallacf0ee52010-10-08 02:01:28 +00007035 // This is not the right CC for (e.g.) a variable initialization.
7036 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007037}
7038
Richard Trieu65724892014-11-15 06:37:39 +00007039/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7040/// Input argument E is a logical expression.
7041void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7042 ::CheckBoolLikeConversion(*this, E, CC);
7043}
7044
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007045/// Diagnose when expression is an integer constant expression and its evaluation
7046/// results in integer overflow
7047void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007048 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7049 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007050}
7051
Richard Smithc406cb72013-01-17 01:17:56 +00007052namespace {
7053/// \brief Visitor for expressions which looks for unsequenced operations on the
7054/// same object.
7055class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007056 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7057
Richard Smithc406cb72013-01-17 01:17:56 +00007058 /// \brief A tree of sequenced regions within an expression. Two regions are
7059 /// unsequenced if one is an ancestor or a descendent of the other. When we
7060 /// finish processing an expression with sequencing, such as a comma
7061 /// expression, we fold its tree nodes into its parent, since they are
7062 /// unsequenced with respect to nodes we will visit later.
7063 class SequenceTree {
7064 struct Value {
7065 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7066 unsigned Parent : 31;
7067 bool Merged : 1;
7068 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007069 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007070
7071 public:
7072 /// \brief A region within an expression which may be sequenced with respect
7073 /// to some other region.
7074 class Seq {
7075 explicit Seq(unsigned N) : Index(N) {}
7076 unsigned Index;
7077 friend class SequenceTree;
7078 public:
7079 Seq() : Index(0) {}
7080 };
7081
7082 SequenceTree() { Values.push_back(Value(0)); }
7083 Seq root() const { return Seq(0); }
7084
7085 /// \brief Create a new sequence of operations, which is an unsequenced
7086 /// subset of \p Parent. This sequence of operations is sequenced with
7087 /// respect to other children of \p Parent.
7088 Seq allocate(Seq Parent) {
7089 Values.push_back(Value(Parent.Index));
7090 return Seq(Values.size() - 1);
7091 }
7092
7093 /// \brief Merge a sequence of operations into its parent.
7094 void merge(Seq S) {
7095 Values[S.Index].Merged = true;
7096 }
7097
7098 /// \brief Determine whether two operations are unsequenced. This operation
7099 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7100 /// should have been merged into its parent as appropriate.
7101 bool isUnsequenced(Seq Cur, Seq Old) {
7102 unsigned C = representative(Cur.Index);
7103 unsigned Target = representative(Old.Index);
7104 while (C >= Target) {
7105 if (C == Target)
7106 return true;
7107 C = Values[C].Parent;
7108 }
7109 return false;
7110 }
7111
7112 private:
7113 /// \brief Pick a representative for a sequence.
7114 unsigned representative(unsigned K) {
7115 if (Values[K].Merged)
7116 // Perform path compression as we go.
7117 return Values[K].Parent = representative(Values[K].Parent);
7118 return K;
7119 }
7120 };
7121
7122 /// An object for which we can track unsequenced uses.
7123 typedef NamedDecl *Object;
7124
7125 /// Different flavors of object usage which we track. We only track the
7126 /// least-sequenced usage of each kind.
7127 enum UsageKind {
7128 /// A read of an object. Multiple unsequenced reads are OK.
7129 UK_Use,
7130 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007131 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007132 UK_ModAsValue,
7133 /// A modification of an object which is not sequenced before the value
7134 /// computation of the expression, such as n++.
7135 UK_ModAsSideEffect,
7136
7137 UK_Count = UK_ModAsSideEffect + 1
7138 };
7139
7140 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007141 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007142 Expr *Use;
7143 SequenceTree::Seq Seq;
7144 };
7145
7146 struct UsageInfo {
7147 UsageInfo() : Diagnosed(false) {}
7148 Usage Uses[UK_Count];
7149 /// Have we issued a diagnostic for this variable already?
7150 bool Diagnosed;
7151 };
7152 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7153
7154 Sema &SemaRef;
7155 /// Sequenced regions within the expression.
7156 SequenceTree Tree;
7157 /// Declaration modifications and references which we have seen.
7158 UsageInfoMap UsageMap;
7159 /// The region we are currently within.
7160 SequenceTree::Seq Region;
7161 /// Filled in with declarations which were modified as a side-effect
7162 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007163 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007164 /// Expressions to check later. We defer checking these to reduce
7165 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007166 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007167
7168 /// RAII object wrapping the visitation of a sequenced subexpression of an
7169 /// expression. At the end of this process, the side-effects of the evaluation
7170 /// become sequenced with respect to the value computation of the result, so
7171 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7172 /// UK_ModAsValue.
7173 struct SequencedSubexpression {
7174 SequencedSubexpression(SequenceChecker &Self)
7175 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7176 Self.ModAsSideEffect = &ModAsSideEffect;
7177 }
7178 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007179 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7180 MI != ME; ++MI) {
7181 UsageInfo &U = Self.UsageMap[MI->first];
7182 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7183 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7184 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007185 }
7186 Self.ModAsSideEffect = OldModAsSideEffect;
7187 }
7188
7189 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007190 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7191 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007192 };
7193
Richard Smith40238f02013-06-20 22:21:56 +00007194 /// RAII object wrapping the visitation of a subexpression which we might
7195 /// choose to evaluate as a constant. If any subexpression is evaluated and
7196 /// found to be non-constant, this allows us to suppress the evaluation of
7197 /// the outer expression.
7198 class EvaluationTracker {
7199 public:
7200 EvaluationTracker(SequenceChecker &Self)
7201 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7202 Self.EvalTracker = this;
7203 }
7204 ~EvaluationTracker() {
7205 Self.EvalTracker = Prev;
7206 if (Prev)
7207 Prev->EvalOK &= EvalOK;
7208 }
7209
7210 bool evaluate(const Expr *E, bool &Result) {
7211 if (!EvalOK || E->isValueDependent())
7212 return false;
7213 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7214 return EvalOK;
7215 }
7216
7217 private:
7218 SequenceChecker &Self;
7219 EvaluationTracker *Prev;
7220 bool EvalOK;
7221 } *EvalTracker;
7222
Richard Smithc406cb72013-01-17 01:17:56 +00007223 /// \brief Find the object which is produced by the specified expression,
7224 /// if any.
7225 Object getObject(Expr *E, bool Mod) const {
7226 E = E->IgnoreParenCasts();
7227 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7228 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7229 return getObject(UO->getSubExpr(), Mod);
7230 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7231 if (BO->getOpcode() == BO_Comma)
7232 return getObject(BO->getRHS(), Mod);
7233 if (Mod && BO->isAssignmentOp())
7234 return getObject(BO->getLHS(), Mod);
7235 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7236 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7237 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7238 return ME->getMemberDecl();
7239 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7240 // FIXME: If this is a reference, map through to its value.
7241 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007242 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007243 }
7244
7245 /// \brief Note that an object was modified or used by an expression.
7246 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7247 Usage &U = UI.Uses[UK];
7248 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7249 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7250 ModAsSideEffect->push_back(std::make_pair(O, U));
7251 U.Use = Ref;
7252 U.Seq = Region;
7253 }
7254 }
7255 /// \brief Check whether a modification or use conflicts with a prior usage.
7256 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7257 bool IsModMod) {
7258 if (UI.Diagnosed)
7259 return;
7260
7261 const Usage &U = UI.Uses[OtherKind];
7262 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7263 return;
7264
7265 Expr *Mod = U.Use;
7266 Expr *ModOrUse = Ref;
7267 if (OtherKind == UK_Use)
7268 std::swap(Mod, ModOrUse);
7269
7270 SemaRef.Diag(Mod->getExprLoc(),
7271 IsModMod ? diag::warn_unsequenced_mod_mod
7272 : diag::warn_unsequenced_mod_use)
7273 << O << SourceRange(ModOrUse->getExprLoc());
7274 UI.Diagnosed = true;
7275 }
7276
7277 void notePreUse(Object O, Expr *Use) {
7278 UsageInfo &U = UsageMap[O];
7279 // Uses conflict with other modifications.
7280 checkUsage(O, U, Use, UK_ModAsValue, false);
7281 }
7282 void notePostUse(Object O, Expr *Use) {
7283 UsageInfo &U = UsageMap[O];
7284 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7285 addUsage(U, O, Use, UK_Use);
7286 }
7287
7288 void notePreMod(Object O, Expr *Mod) {
7289 UsageInfo &U = UsageMap[O];
7290 // Modifications conflict with other modifications and with uses.
7291 checkUsage(O, U, Mod, UK_ModAsValue, true);
7292 checkUsage(O, U, Mod, UK_Use, false);
7293 }
7294 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7295 UsageInfo &U = UsageMap[O];
7296 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7297 addUsage(U, O, Use, UK);
7298 }
7299
7300public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007301 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007302 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7303 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007304 Visit(E);
7305 }
7306
7307 void VisitStmt(Stmt *S) {
7308 // Skip all statements which aren't expressions for now.
7309 }
7310
7311 void VisitExpr(Expr *E) {
7312 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007313 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007314 }
7315
7316 void VisitCastExpr(CastExpr *E) {
7317 Object O = Object();
7318 if (E->getCastKind() == CK_LValueToRValue)
7319 O = getObject(E->getSubExpr(), false);
7320
7321 if (O)
7322 notePreUse(O, E);
7323 VisitExpr(E);
7324 if (O)
7325 notePostUse(O, E);
7326 }
7327
7328 void VisitBinComma(BinaryOperator *BO) {
7329 // C++11 [expr.comma]p1:
7330 // Every value computation and side effect associated with the left
7331 // expression is sequenced before every value computation and side
7332 // effect associated with the right expression.
7333 SequenceTree::Seq LHS = Tree.allocate(Region);
7334 SequenceTree::Seq RHS = Tree.allocate(Region);
7335 SequenceTree::Seq OldRegion = Region;
7336
7337 {
7338 SequencedSubexpression SeqLHS(*this);
7339 Region = LHS;
7340 Visit(BO->getLHS());
7341 }
7342
7343 Region = RHS;
7344 Visit(BO->getRHS());
7345
7346 Region = OldRegion;
7347
7348 // Forget that LHS and RHS are sequenced. They are both unsequenced
7349 // with respect to other stuff.
7350 Tree.merge(LHS);
7351 Tree.merge(RHS);
7352 }
7353
7354 void VisitBinAssign(BinaryOperator *BO) {
7355 // The modification is sequenced after the value computation of the LHS
7356 // and RHS, so check it before inspecting the operands and update the
7357 // map afterwards.
7358 Object O = getObject(BO->getLHS(), true);
7359 if (!O)
7360 return VisitExpr(BO);
7361
7362 notePreMod(O, BO);
7363
7364 // C++11 [expr.ass]p7:
7365 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7366 // only once.
7367 //
7368 // Therefore, for a compound assignment operator, O is considered used
7369 // everywhere except within the evaluation of E1 itself.
7370 if (isa<CompoundAssignOperator>(BO))
7371 notePreUse(O, BO);
7372
7373 Visit(BO->getLHS());
7374
7375 if (isa<CompoundAssignOperator>(BO))
7376 notePostUse(O, BO);
7377
7378 Visit(BO->getRHS());
7379
Richard Smith83e37bee2013-06-26 23:16:51 +00007380 // C++11 [expr.ass]p1:
7381 // the assignment is sequenced [...] before the value computation of the
7382 // assignment expression.
7383 // C11 6.5.16/3 has no such rule.
7384 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7385 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007386 }
7387 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7388 VisitBinAssign(CAO);
7389 }
7390
7391 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7392 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7393 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7394 Object O = getObject(UO->getSubExpr(), true);
7395 if (!O)
7396 return VisitExpr(UO);
7397
7398 notePreMod(O, UO);
7399 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007400 // C++11 [expr.pre.incr]p1:
7401 // the expression ++x is equivalent to x+=1
7402 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7403 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007404 }
7405
7406 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7407 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7408 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7409 Object O = getObject(UO->getSubExpr(), true);
7410 if (!O)
7411 return VisitExpr(UO);
7412
7413 notePreMod(O, UO);
7414 Visit(UO->getSubExpr());
7415 notePostMod(O, UO, UK_ModAsSideEffect);
7416 }
7417
7418 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7419 void VisitBinLOr(BinaryOperator *BO) {
7420 // The side-effects of the LHS of an '&&' are sequenced before the
7421 // value computation of the RHS, and hence before the value computation
7422 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7423 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007424 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007425 {
7426 SequencedSubexpression Sequenced(*this);
7427 Visit(BO->getLHS());
7428 }
7429
7430 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007431 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007432 if (!Result)
7433 Visit(BO->getRHS());
7434 } else {
7435 // Check for unsequenced operations in the RHS, treating it as an
7436 // entirely separate evaluation.
7437 //
7438 // FIXME: If there are operations in the RHS which are unsequenced
7439 // with respect to operations outside the RHS, and those operations
7440 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007441 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007442 }
Richard Smithc406cb72013-01-17 01:17:56 +00007443 }
7444 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007445 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007446 {
7447 SequencedSubexpression Sequenced(*this);
7448 Visit(BO->getLHS());
7449 }
7450
7451 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007452 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007453 if (Result)
7454 Visit(BO->getRHS());
7455 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007456 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007457 }
Richard Smithc406cb72013-01-17 01:17:56 +00007458 }
7459
7460 // Only visit the condition, unless we can be sure which subexpression will
7461 // be chosen.
7462 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007463 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007464 {
7465 SequencedSubexpression Sequenced(*this);
7466 Visit(CO->getCond());
7467 }
Richard Smithc406cb72013-01-17 01:17:56 +00007468
7469 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007470 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007471 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007472 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007473 WorkList.push_back(CO->getTrueExpr());
7474 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007475 }
Richard Smithc406cb72013-01-17 01:17:56 +00007476 }
7477
Richard Smithe3dbfe02013-06-30 10:40:20 +00007478 void VisitCallExpr(CallExpr *CE) {
7479 // C++11 [intro.execution]p15:
7480 // When calling a function [...], every value computation and side effect
7481 // associated with any argument expression, or with the postfix expression
7482 // designating the called function, is sequenced before execution of every
7483 // expression or statement in the body of the function [and thus before
7484 // the value computation of its result].
7485 SequencedSubexpression Sequenced(*this);
7486 Base::VisitCallExpr(CE);
7487
7488 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7489 }
7490
Richard Smithc406cb72013-01-17 01:17:56 +00007491 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007492 // This is a call, so all subexpressions are sequenced before the result.
7493 SequencedSubexpression Sequenced(*this);
7494
Richard Smithc406cb72013-01-17 01:17:56 +00007495 if (!CCE->isListInitialization())
7496 return VisitExpr(CCE);
7497
7498 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007499 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007500 SequenceTree::Seq Parent = Region;
7501 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7502 E = CCE->arg_end();
7503 I != E; ++I) {
7504 Region = Tree.allocate(Parent);
7505 Elts.push_back(Region);
7506 Visit(*I);
7507 }
7508
7509 // Forget that the initializers are sequenced.
7510 Region = Parent;
7511 for (unsigned I = 0; I < Elts.size(); ++I)
7512 Tree.merge(Elts[I]);
7513 }
7514
7515 void VisitInitListExpr(InitListExpr *ILE) {
7516 if (!SemaRef.getLangOpts().CPlusPlus11)
7517 return VisitExpr(ILE);
7518
7519 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007520 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007521 SequenceTree::Seq Parent = Region;
7522 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7523 Expr *E = ILE->getInit(I);
7524 if (!E) continue;
7525 Region = Tree.allocate(Parent);
7526 Elts.push_back(Region);
7527 Visit(E);
7528 }
7529
7530 // Forget that the initializers are sequenced.
7531 Region = Parent;
7532 for (unsigned I = 0; I < Elts.size(); ++I)
7533 Tree.merge(Elts[I]);
7534 }
7535};
7536}
7537
7538void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007539 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007540 WorkList.push_back(E);
7541 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007542 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007543 SequenceChecker(*this, Item, WorkList);
7544 }
Richard Smithc406cb72013-01-17 01:17:56 +00007545}
7546
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007547void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7548 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007549 CheckImplicitConversions(E, CheckLoc);
7550 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007551 if (!IsConstexpr && !E->isValueDependent())
7552 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007553}
7554
John McCall1f425642010-11-11 03:21:53 +00007555void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7556 FieldDecl *BitField,
7557 Expr *Init) {
7558 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7559}
7560
Mike Stump0c2ec772010-01-21 03:59:47 +00007561/// CheckParmsForFunctionDef - Check that the parameters of the given
7562/// function are appropriate for the definition of a function. This
7563/// takes care of any checks that cannot be performed on the
7564/// declaration itself, e.g., that the types of each of the function
7565/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007566bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7567 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007568 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007569 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007570 for (; P != PEnd; ++P) {
7571 ParmVarDecl *Param = *P;
7572
Mike Stump0c2ec772010-01-21 03:59:47 +00007573 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7574 // function declarator that is part of a function definition of
7575 // that function shall not have incomplete type.
7576 //
7577 // This is also C++ [dcl.fct]p6.
7578 if (!Param->isInvalidDecl() &&
7579 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007580 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007581 Param->setInvalidDecl();
7582 HasInvalidParm = true;
7583 }
7584
7585 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7586 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007587 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007588 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007589 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007590 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007591 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007592
7593 // C99 6.7.5.3p12:
7594 // If the function declarator is not part of a definition of that
7595 // function, parameters may have incomplete type and may use the [*]
7596 // notation in their sequences of declarator specifiers to specify
7597 // variable length array types.
7598 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007599 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007600 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007601 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007602 // information is added for it.
7603 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007604 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007605 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007606 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007607 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007608
7609 // MSVC destroys objects passed by value in the callee. Therefore a
7610 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007611 // object's destructor. However, we don't perform any direct access check
7612 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007613 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7614 .getCXXABI()
7615 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007616 if (!Param->isInvalidDecl()) {
7617 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7618 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7619 if (!ClassDecl->isInvalidDecl() &&
7620 !ClassDecl->hasIrrelevantDestructor() &&
7621 !ClassDecl->isDependentContext()) {
7622 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7623 MarkFunctionReferenced(Param->getLocation(), Destructor);
7624 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7625 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007626 }
7627 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007628 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007629 }
7630
7631 return HasInvalidParm;
7632}
John McCall2b5c1b22010-08-12 21:44:57 +00007633
7634/// CheckCastAlign - Implements -Wcast-align, which warns when a
7635/// pointer cast increases the alignment requirements.
7636void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7637 // This is actually a lot of work to potentially be doing on every
7638 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007639 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007640 return;
7641
7642 // Ignore dependent types.
7643 if (T->isDependentType() || Op->getType()->isDependentType())
7644 return;
7645
7646 // Require that the destination be a pointer type.
7647 const PointerType *DestPtr = T->getAs<PointerType>();
7648 if (!DestPtr) return;
7649
7650 // If the destination has alignment 1, we're done.
7651 QualType DestPointee = DestPtr->getPointeeType();
7652 if (DestPointee->isIncompleteType()) return;
7653 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7654 if (DestAlign.isOne()) return;
7655
7656 // Require that the source be a pointer type.
7657 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7658 if (!SrcPtr) return;
7659 QualType SrcPointee = SrcPtr->getPointeeType();
7660
7661 // Whitelist casts from cv void*. We already implicitly
7662 // whitelisted casts to cv void*, since they have alignment 1.
7663 // Also whitelist casts involving incomplete types, which implicitly
7664 // includes 'void'.
7665 if (SrcPointee->isIncompleteType()) return;
7666
7667 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7668 if (SrcAlign >= DestAlign) return;
7669
7670 Diag(TRange.getBegin(), diag::warn_cast_align)
7671 << Op->getType() << T
7672 << static_cast<unsigned>(SrcAlign.getQuantity())
7673 << static_cast<unsigned>(DestAlign.getQuantity())
7674 << TRange << Op->getSourceRange();
7675}
7676
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007677static const Type* getElementType(const Expr *BaseExpr) {
7678 const Type* EltType = BaseExpr->getType().getTypePtr();
7679 if (EltType->isAnyPointerType())
7680 return EltType->getPointeeType().getTypePtr();
7681 else if (EltType->isArrayType())
7682 return EltType->getBaseElementTypeUnsafe();
7683 return EltType;
7684}
7685
Chandler Carruth28389f02011-08-05 09:10:50 +00007686/// \brief Check whether this array fits the idiom of a size-one tail padded
7687/// array member of a struct.
7688///
7689/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7690/// commonly used to emulate flexible arrays in C89 code.
7691static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7692 const NamedDecl *ND) {
7693 if (Size != 1 || !ND) return false;
7694
7695 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7696 if (!FD) return false;
7697
7698 // Don't consider sizes resulting from macro expansions or template argument
7699 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007700
7701 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007702 while (TInfo) {
7703 TypeLoc TL = TInfo->getTypeLoc();
7704 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007705 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7706 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007707 TInfo = TDL->getTypeSourceInfo();
7708 continue;
7709 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007710 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7711 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007712 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7713 return false;
7714 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007715 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007716 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007717
7718 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007719 if (!RD) return false;
7720 if (RD->isUnion()) return false;
7721 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7722 if (!CRD->isStandardLayout()) return false;
7723 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007724
Benjamin Kramer8c543672011-08-06 03:04:42 +00007725 // See if this is the last field decl in the record.
7726 const Decl *D = FD;
7727 while ((D = D->getNextDeclInContext()))
7728 if (isa<FieldDecl>(D))
7729 return false;
7730 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007731}
7732
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007733void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007734 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007735 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007736 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007737 if (IndexExpr->isValueDependent())
7738 return;
7739
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007740 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007741 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007742 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007743 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007744 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007745 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007746
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007747 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007748 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007749 return;
Richard Smith13f67182011-12-16 19:31:14 +00007750 if (IndexNegated)
7751 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007752
Craig Topperc3ec1492014-05-26 06:22:03 +00007753 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007754 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7755 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007756 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007757 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007758
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007759 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007760 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007761 if (!size.isStrictlyPositive())
7762 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007763
7764 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007765 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007766 // Make sure we're comparing apples to apples when comparing index to size
7767 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7768 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007769 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007770 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007771 if (ptrarith_typesize != array_typesize) {
7772 // There's a cast to a different size type involved
7773 uint64_t ratio = array_typesize / ptrarith_typesize;
7774 // TODO: Be smarter about handling cases where array_typesize is not a
7775 // multiple of ptrarith_typesize
7776 if (ptrarith_typesize * ratio == array_typesize)
7777 size *= llvm::APInt(size.getBitWidth(), ratio);
7778 }
7779 }
7780
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007781 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007782 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007783 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007784 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007785
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007786 // For array subscripting the index must be less than size, but for pointer
7787 // arithmetic also allow the index (offset) to be equal to size since
7788 // computing the next address after the end of the array is legal and
7789 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007790 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007791 return;
7792
7793 // Also don't warn for arrays of size 1 which are members of some
7794 // structure. These are often used to approximate flexible arrays in C89
7795 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007796 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007797 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007798
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007799 // Suppress the warning if the subscript expression (as identified by the
7800 // ']' location) and the index expression are both from macro expansions
7801 // within a system header.
7802 if (ASE) {
7803 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7804 ASE->getRBracketLoc());
7805 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7806 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7807 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007808 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007809 return;
7810 }
7811 }
7812
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007813 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007814 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007815 DiagID = diag::warn_array_index_exceeds_bounds;
7816
7817 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7818 PDiag(DiagID) << index.toString(10, true)
7819 << size.toString(10, true)
7820 << (unsigned)size.getLimitedValue(~0U)
7821 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007822 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007823 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007824 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007825 DiagID = diag::warn_ptr_arith_precedes_bounds;
7826 if (index.isNegative()) index = -index;
7827 }
7828
7829 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7830 PDiag(DiagID) << index.toString(10, true)
7831 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007832 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007833
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007834 if (!ND) {
7835 // Try harder to find a NamedDecl to point at in the note.
7836 while (const ArraySubscriptExpr *ASE =
7837 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7838 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7839 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7840 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7841 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7842 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7843 }
7844
Chandler Carruth1af88f12011-02-17 21:10:52 +00007845 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007846 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7847 PDiag(diag::note_array_index_out_of_bounds)
7848 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007849}
7850
Ted Kremenekdf26df72011-03-01 18:41:00 +00007851void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007852 int AllowOnePastEnd = 0;
7853 while (expr) {
7854 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007855 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007856 case Stmt::ArraySubscriptExprClass: {
7857 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007858 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007859 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007860 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007861 }
7862 case Stmt::UnaryOperatorClass: {
7863 // Only unwrap the * and & unary operators
7864 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7865 expr = UO->getSubExpr();
7866 switch (UO->getOpcode()) {
7867 case UO_AddrOf:
7868 AllowOnePastEnd++;
7869 break;
7870 case UO_Deref:
7871 AllowOnePastEnd--;
7872 break;
7873 default:
7874 return;
7875 }
7876 break;
7877 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007878 case Stmt::ConditionalOperatorClass: {
7879 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7880 if (const Expr *lhs = cond->getLHS())
7881 CheckArrayAccess(lhs);
7882 if (const Expr *rhs = cond->getRHS())
7883 CheckArrayAccess(rhs);
7884 return;
7885 }
7886 default:
7887 return;
7888 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007889 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007890}
John McCall31168b02011-06-15 23:02:42 +00007891
7892//===--- CHECK: Objective-C retain cycles ----------------------------------//
7893
7894namespace {
7895 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007896 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007897 VarDecl *Variable;
7898 SourceRange Range;
7899 SourceLocation Loc;
7900 bool Indirect;
7901
7902 void setLocsFrom(Expr *e) {
7903 Loc = e->getExprLoc();
7904 Range = e->getSourceRange();
7905 }
7906 };
7907}
7908
7909/// Consider whether capturing the given variable can possibly lead to
7910/// a retain cycle.
7911static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007912 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007913 // lifetime. In MRR, it's captured strongly if the variable is
7914 // __block and has an appropriate type.
7915 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7916 return false;
7917
7918 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007919 if (ref)
7920 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007921 return true;
7922}
7923
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007924static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007925 while (true) {
7926 e = e->IgnoreParens();
7927 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7928 switch (cast->getCastKind()) {
7929 case CK_BitCast:
7930 case CK_LValueBitCast:
7931 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007932 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007933 e = cast->getSubExpr();
7934 continue;
7935
John McCall31168b02011-06-15 23:02:42 +00007936 default:
7937 return false;
7938 }
7939 }
7940
7941 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7942 ObjCIvarDecl *ivar = ref->getDecl();
7943 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7944 return false;
7945
7946 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007947 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007948 return false;
7949
7950 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7951 owner.Indirect = true;
7952 return true;
7953 }
7954
7955 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7956 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7957 if (!var) return false;
7958 return considerVariable(var, ref, owner);
7959 }
7960
John McCall31168b02011-06-15 23:02:42 +00007961 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7962 if (member->isArrow()) return false;
7963
7964 // Don't count this as an indirect ownership.
7965 e = member->getBase();
7966 continue;
7967 }
7968
John McCallfe96e0b2011-11-06 09:01:30 +00007969 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7970 // Only pay attention to pseudo-objects on property references.
7971 ObjCPropertyRefExpr *pre
7972 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7973 ->IgnoreParens());
7974 if (!pre) return false;
7975 if (pre->isImplicitProperty()) return false;
7976 ObjCPropertyDecl *property = pre->getExplicitProperty();
7977 if (!property->isRetaining() &&
7978 !(property->getPropertyIvarDecl() &&
7979 property->getPropertyIvarDecl()->getType()
7980 .getObjCLifetime() == Qualifiers::OCL_Strong))
7981 return false;
7982
7983 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007984 if (pre->isSuperReceiver()) {
7985 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7986 if (!owner.Variable)
7987 return false;
7988 owner.Loc = pre->getLocation();
7989 owner.Range = pre->getSourceRange();
7990 return true;
7991 }
John McCallfe96e0b2011-11-06 09:01:30 +00007992 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7993 ->getSourceExpr());
7994 continue;
7995 }
7996
John McCall31168b02011-06-15 23:02:42 +00007997 // Array ivars?
7998
7999 return false;
8000 }
8001}
8002
8003namespace {
8004 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8005 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8006 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008007 Context(Context), Variable(variable), Capturer(nullptr),
8008 VarWillBeReased(false) {}
8009 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008010 VarDecl *Variable;
8011 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008012 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008013
8014 void VisitDeclRefExpr(DeclRefExpr *ref) {
8015 if (ref->getDecl() == Variable && !Capturer)
8016 Capturer = ref;
8017 }
8018
John McCall31168b02011-06-15 23:02:42 +00008019 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8020 if (Capturer) return;
8021 Visit(ref->getBase());
8022 if (Capturer && ref->isFreeIvar())
8023 Capturer = ref;
8024 }
8025
8026 void VisitBlockExpr(BlockExpr *block) {
8027 // Look inside nested blocks
8028 if (block->getBlockDecl()->capturesVariable(Variable))
8029 Visit(block->getBlockDecl()->getBody());
8030 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008031
8032 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8033 if (Capturer) return;
8034 if (OVE->getSourceExpr())
8035 Visit(OVE->getSourceExpr());
8036 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008037 void VisitBinaryOperator(BinaryOperator *BinOp) {
8038 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8039 return;
8040 Expr *LHS = BinOp->getLHS();
8041 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8042 if (DRE->getDecl() != Variable)
8043 return;
8044 if (Expr *RHS = BinOp->getRHS()) {
8045 RHS = RHS->IgnoreParenCasts();
8046 llvm::APSInt Value;
8047 VarWillBeReased =
8048 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8049 }
8050 }
8051 }
John McCall31168b02011-06-15 23:02:42 +00008052 };
8053}
8054
8055/// Check whether the given argument is a block which captures a
8056/// variable.
8057static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8058 assert(owner.Variable && owner.Loc.isValid());
8059
8060 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008061
8062 // Look through [^{...} copy] and Block_copy(^{...}).
8063 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8064 Selector Cmd = ME->getSelector();
8065 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8066 e = ME->getInstanceReceiver();
8067 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008068 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008069 e = e->IgnoreParenCasts();
8070 }
8071 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8072 if (CE->getNumArgs() == 1) {
8073 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008074 if (Fn) {
8075 const IdentifierInfo *FnI = Fn->getIdentifier();
8076 if (FnI && FnI->isStr("_Block_copy")) {
8077 e = CE->getArg(0)->IgnoreParenCasts();
8078 }
8079 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008080 }
8081 }
8082
John McCall31168b02011-06-15 23:02:42 +00008083 BlockExpr *block = dyn_cast<BlockExpr>(e);
8084 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008085 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008086
8087 FindCaptureVisitor visitor(S.Context, owner.Variable);
8088 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008089 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008090}
8091
8092static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8093 RetainCycleOwner &owner) {
8094 assert(capturer);
8095 assert(owner.Variable && owner.Loc.isValid());
8096
8097 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8098 << owner.Variable << capturer->getSourceRange();
8099 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8100 << owner.Indirect << owner.Range;
8101}
8102
8103/// Check for a keyword selector that starts with the word 'add' or
8104/// 'set'.
8105static bool isSetterLikeSelector(Selector sel) {
8106 if (sel.isUnarySelector()) return false;
8107
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008108 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008109 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008110 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008111 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008112 else if (str.startswith("add")) {
8113 // Specially whitelist 'addOperationWithBlock:'.
8114 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8115 return false;
8116 str = str.substr(3);
8117 }
John McCall31168b02011-06-15 23:02:42 +00008118 else
8119 return false;
8120
8121 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008122 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008123}
8124
8125/// Check a message send to see if it's likely to cause a retain cycle.
8126void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8127 // Only check instance methods whose selector looks like a setter.
8128 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8129 return;
8130
8131 // Try to find a variable that the receiver is strongly owned by.
8132 RetainCycleOwner owner;
8133 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008134 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008135 return;
8136 } else {
8137 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8138 owner.Variable = getCurMethodDecl()->getSelfDecl();
8139 owner.Loc = msg->getSuperLoc();
8140 owner.Range = msg->getSuperLoc();
8141 }
8142
8143 // Check whether the receiver is captured by any of the arguments.
8144 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8145 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8146 return diagnoseRetainCycle(*this, capturer, owner);
8147}
8148
8149/// Check a property assign to see if it's likely to cause a retain cycle.
8150void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8151 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008152 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008153 return;
8154
8155 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8156 diagnoseRetainCycle(*this, capturer, owner);
8157}
8158
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008159void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8160 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008161 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008162 return;
8163
8164 // Because we don't have an expression for the variable, we have to set the
8165 // location explicitly here.
8166 Owner.Loc = Var->getLocation();
8167 Owner.Range = Var->getSourceRange();
8168
8169 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8170 diagnoseRetainCycle(*this, Capturer, Owner);
8171}
8172
Ted Kremenek9304da92012-12-21 08:04:28 +00008173static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8174 Expr *RHS, bool isProperty) {
8175 // Check if RHS is an Objective-C object literal, which also can get
8176 // immediately zapped in a weak reference. Note that we explicitly
8177 // allow ObjCStringLiterals, since those are designed to never really die.
8178 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008179
Ted Kremenek64873352012-12-21 22:46:35 +00008180 // This enum needs to match with the 'select' in
8181 // warn_objc_arc_literal_assign (off-by-1).
8182 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8183 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8184 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008185
8186 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008187 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008188 << (isProperty ? 0 : 1)
8189 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008190
8191 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008192}
8193
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008194static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8195 Qualifiers::ObjCLifetime LT,
8196 Expr *RHS, bool isProperty) {
8197 // Strip off any implicit cast added to get to the one ARC-specific.
8198 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8199 if (cast->getCastKind() == CK_ARCConsumeObject) {
8200 S.Diag(Loc, diag::warn_arc_retained_assign)
8201 << (LT == Qualifiers::OCL_ExplicitNone)
8202 << (isProperty ? 0 : 1)
8203 << RHS->getSourceRange();
8204 return true;
8205 }
8206 RHS = cast->getSubExpr();
8207 }
8208
8209 if (LT == Qualifiers::OCL_Weak &&
8210 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8211 return true;
8212
8213 return false;
8214}
8215
Ted Kremenekb36234d2012-12-21 08:04:20 +00008216bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8217 QualType LHS, Expr *RHS) {
8218 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8219
8220 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8221 return false;
8222
8223 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8224 return true;
8225
8226 return false;
8227}
8228
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008229void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8230 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008231 QualType LHSType;
8232 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008233 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008234 ObjCPropertyRefExpr *PRE
8235 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8236 if (PRE && !PRE->isImplicitProperty()) {
8237 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8238 if (PD)
8239 LHSType = PD->getType();
8240 }
8241
8242 if (LHSType.isNull())
8243 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008244
8245 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8246
8247 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008248 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008249 getCurFunction()->markSafeWeakUse(LHS);
8250 }
8251
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008252 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8253 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008254
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008255 // FIXME. Check for other life times.
8256 if (LT != Qualifiers::OCL_None)
8257 return;
8258
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008259 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008260 if (PRE->isImplicitProperty())
8261 return;
8262 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8263 if (!PD)
8264 return;
8265
Bill Wendling44426052012-12-20 19:22:21 +00008266 unsigned Attributes = PD->getPropertyAttributes();
8267 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008268 // when 'assign' attribute was not explicitly specified
8269 // by user, ignore it and rely on property type itself
8270 // for lifetime info.
8271 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8272 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8273 LHSType->isObjCRetainableType())
8274 return;
8275
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008276 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008277 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008278 Diag(Loc, diag::warn_arc_retained_property_assign)
8279 << RHS->getSourceRange();
8280 return;
8281 }
8282 RHS = cast->getSubExpr();
8283 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008284 }
Bill Wendling44426052012-12-20 19:22:21 +00008285 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008286 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8287 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008288 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008289 }
8290}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008291
8292//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8293
8294namespace {
8295bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8296 SourceLocation StmtLoc,
8297 const NullStmt *Body) {
8298 // Do not warn if the body is a macro that expands to nothing, e.g:
8299 //
8300 // #define CALL(x)
8301 // if (condition)
8302 // CALL(0);
8303 //
8304 if (Body->hasLeadingEmptyMacro())
8305 return false;
8306
8307 // Get line numbers of statement and body.
8308 bool StmtLineInvalid;
8309 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8310 &StmtLineInvalid);
8311 if (StmtLineInvalid)
8312 return false;
8313
8314 bool BodyLineInvalid;
8315 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8316 &BodyLineInvalid);
8317 if (BodyLineInvalid)
8318 return false;
8319
8320 // Warn if null statement and body are on the same line.
8321 if (StmtLine != BodyLine)
8322 return false;
8323
8324 return true;
8325}
8326} // Unnamed namespace
8327
8328void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8329 const Stmt *Body,
8330 unsigned DiagID) {
8331 // Since this is a syntactic check, don't emit diagnostic for template
8332 // instantiations, this just adds noise.
8333 if (CurrentInstantiationScope)
8334 return;
8335
8336 // The body should be a null statement.
8337 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8338 if (!NBody)
8339 return;
8340
8341 // Do the usual checks.
8342 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8343 return;
8344
8345 Diag(NBody->getSemiLoc(), DiagID);
8346 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8347}
8348
8349void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8350 const Stmt *PossibleBody) {
8351 assert(!CurrentInstantiationScope); // Ensured by caller
8352
8353 SourceLocation StmtLoc;
8354 const Stmt *Body;
8355 unsigned DiagID;
8356 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8357 StmtLoc = FS->getRParenLoc();
8358 Body = FS->getBody();
8359 DiagID = diag::warn_empty_for_body;
8360 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8361 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8362 Body = WS->getBody();
8363 DiagID = diag::warn_empty_while_body;
8364 } else
8365 return; // Neither `for' nor `while'.
8366
8367 // The body should be a null statement.
8368 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8369 if (!NBody)
8370 return;
8371
8372 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008373 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008374 return;
8375
8376 // Do the usual checks.
8377 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8378 return;
8379
8380 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8381 // noise level low, emit diagnostics only if for/while is followed by a
8382 // CompoundStmt, e.g.:
8383 // for (int i = 0; i < n; i++);
8384 // {
8385 // a(i);
8386 // }
8387 // or if for/while is followed by a statement with more indentation
8388 // than for/while itself:
8389 // for (int i = 0; i < n; i++);
8390 // a(i);
8391 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8392 if (!ProbableTypo) {
8393 bool BodyColInvalid;
8394 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8395 PossibleBody->getLocStart(),
8396 &BodyColInvalid);
8397 if (BodyColInvalid)
8398 return;
8399
8400 bool StmtColInvalid;
8401 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8402 S->getLocStart(),
8403 &StmtColInvalid);
8404 if (StmtColInvalid)
8405 return;
8406
8407 if (BodyCol > StmtCol)
8408 ProbableTypo = true;
8409 }
8410
8411 if (ProbableTypo) {
8412 Diag(NBody->getSemiLoc(), DiagID);
8413 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8414 }
8415}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008416
Richard Trieu36d0b2b2015-01-13 02:32:02 +00008417//===--- CHECK: Warn on self move with std::move. -------------------------===//
8418
8419/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8420void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8421 SourceLocation OpLoc) {
8422
8423 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8424 return;
8425
8426 if (!ActiveTemplateInstantiations.empty())
8427 return;
8428
8429 // Strip parens and casts away.
8430 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8431 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8432
8433 // Check for a call expression
8434 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8435 if (!CE || CE->getNumArgs() != 1)
8436 return;
8437
8438 // Check for a call to std::move
8439 const FunctionDecl *FD = CE->getDirectCallee();
8440 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8441 !FD->getIdentifier()->isStr("move"))
8442 return;
8443
8444 // Get argument from std::move
8445 RHSExpr = CE->getArg(0);
8446
8447 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8448 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8449
8450 // Two DeclRefExpr's, check that the decls are the same.
8451 if (LHSDeclRef && RHSDeclRef) {
8452 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8453 return;
8454 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8455 RHSDeclRef->getDecl()->getCanonicalDecl())
8456 return;
8457
8458 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8459 << LHSExpr->getSourceRange()
8460 << RHSExpr->getSourceRange();
8461 return;
8462 }
8463
8464 // Member variables require a different approach to check for self moves.
8465 // MemberExpr's are the same if every nested MemberExpr refers to the same
8466 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8467 // the base Expr's are CXXThisExpr's.
8468 const Expr *LHSBase = LHSExpr;
8469 const Expr *RHSBase = RHSExpr;
8470 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8471 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8472 if (!LHSME || !RHSME)
8473 return;
8474
8475 while (LHSME && RHSME) {
8476 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8477 RHSME->getMemberDecl()->getCanonicalDecl())
8478 return;
8479
8480 LHSBase = LHSME->getBase();
8481 RHSBase = RHSME->getBase();
8482 LHSME = dyn_cast<MemberExpr>(LHSBase);
8483 RHSME = dyn_cast<MemberExpr>(RHSBase);
8484 }
8485
8486 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8487 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8488 if (LHSDeclRef && RHSDeclRef) {
8489 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8490 return;
8491 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8492 RHSDeclRef->getDecl()->getCanonicalDecl())
8493 return;
8494
8495 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8496 << LHSExpr->getSourceRange()
8497 << RHSExpr->getSourceRange();
8498 return;
8499 }
8500
8501 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8502 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8503 << LHSExpr->getSourceRange()
8504 << RHSExpr->getSourceRange();
8505}
8506
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008507//===--- Layout compatibility ----------------------------------------------//
8508
8509namespace {
8510
8511bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8512
8513/// \brief Check if two enumeration types are layout-compatible.
8514bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8515 // C++11 [dcl.enum] p8:
8516 // Two enumeration types are layout-compatible if they have the same
8517 // underlying type.
8518 return ED1->isComplete() && ED2->isComplete() &&
8519 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8520}
8521
8522/// \brief Check if two fields are layout-compatible.
8523bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8524 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8525 return false;
8526
8527 if (Field1->isBitField() != Field2->isBitField())
8528 return false;
8529
8530 if (Field1->isBitField()) {
8531 // Make sure that the bit-fields are the same length.
8532 unsigned Bits1 = Field1->getBitWidthValue(C);
8533 unsigned Bits2 = Field2->getBitWidthValue(C);
8534
8535 if (Bits1 != Bits2)
8536 return false;
8537 }
8538
8539 return true;
8540}
8541
8542/// \brief Check if two standard-layout structs are layout-compatible.
8543/// (C++11 [class.mem] p17)
8544bool isLayoutCompatibleStruct(ASTContext &C,
8545 RecordDecl *RD1,
8546 RecordDecl *RD2) {
8547 // If both records are C++ classes, check that base classes match.
8548 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8549 // If one of records is a CXXRecordDecl we are in C++ mode,
8550 // thus the other one is a CXXRecordDecl, too.
8551 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8552 // Check number of base classes.
8553 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8554 return false;
8555
8556 // Check the base classes.
8557 for (CXXRecordDecl::base_class_const_iterator
8558 Base1 = D1CXX->bases_begin(),
8559 BaseEnd1 = D1CXX->bases_end(),
8560 Base2 = D2CXX->bases_begin();
8561 Base1 != BaseEnd1;
8562 ++Base1, ++Base2) {
8563 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8564 return false;
8565 }
8566 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8567 // If only RD2 is a C++ class, it should have zero base classes.
8568 if (D2CXX->getNumBases() > 0)
8569 return false;
8570 }
8571
8572 // Check the fields.
8573 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8574 Field2End = RD2->field_end(),
8575 Field1 = RD1->field_begin(),
8576 Field1End = RD1->field_end();
8577 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8578 if (!isLayoutCompatible(C, *Field1, *Field2))
8579 return false;
8580 }
8581 if (Field1 != Field1End || Field2 != Field2End)
8582 return false;
8583
8584 return true;
8585}
8586
8587/// \brief Check if two standard-layout unions are layout-compatible.
8588/// (C++11 [class.mem] p18)
8589bool isLayoutCompatibleUnion(ASTContext &C,
8590 RecordDecl *RD1,
8591 RecordDecl *RD2) {
8592 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008593 for (auto *Field2 : RD2->fields())
8594 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008595
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008596 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008597 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8598 I = UnmatchedFields.begin(),
8599 E = UnmatchedFields.end();
8600
8601 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008602 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008603 bool Result = UnmatchedFields.erase(*I);
8604 (void) Result;
8605 assert(Result);
8606 break;
8607 }
8608 }
8609 if (I == E)
8610 return false;
8611 }
8612
8613 return UnmatchedFields.empty();
8614}
8615
8616bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8617 if (RD1->isUnion() != RD2->isUnion())
8618 return false;
8619
8620 if (RD1->isUnion())
8621 return isLayoutCompatibleUnion(C, RD1, RD2);
8622 else
8623 return isLayoutCompatibleStruct(C, RD1, RD2);
8624}
8625
8626/// \brief Check if two types are layout-compatible in C++11 sense.
8627bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8628 if (T1.isNull() || T2.isNull())
8629 return false;
8630
8631 // C++11 [basic.types] p11:
8632 // If two types T1 and T2 are the same type, then T1 and T2 are
8633 // layout-compatible types.
8634 if (C.hasSameType(T1, T2))
8635 return true;
8636
8637 T1 = T1.getCanonicalType().getUnqualifiedType();
8638 T2 = T2.getCanonicalType().getUnqualifiedType();
8639
8640 const Type::TypeClass TC1 = T1->getTypeClass();
8641 const Type::TypeClass TC2 = T2->getTypeClass();
8642
8643 if (TC1 != TC2)
8644 return false;
8645
8646 if (TC1 == Type::Enum) {
8647 return isLayoutCompatible(C,
8648 cast<EnumType>(T1)->getDecl(),
8649 cast<EnumType>(T2)->getDecl());
8650 } else if (TC1 == Type::Record) {
8651 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8652 return false;
8653
8654 return isLayoutCompatible(C,
8655 cast<RecordType>(T1)->getDecl(),
8656 cast<RecordType>(T2)->getDecl());
8657 }
8658
8659 return false;
8660}
8661}
8662
8663//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8664
8665namespace {
8666/// \brief Given a type tag expression find the type tag itself.
8667///
8668/// \param TypeExpr Type tag expression, as it appears in user's code.
8669///
8670/// \param VD Declaration of an identifier that appears in a type tag.
8671///
8672/// \param MagicValue Type tag magic value.
8673bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8674 const ValueDecl **VD, uint64_t *MagicValue) {
8675 while(true) {
8676 if (!TypeExpr)
8677 return false;
8678
8679 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8680
8681 switch (TypeExpr->getStmtClass()) {
8682 case Stmt::UnaryOperatorClass: {
8683 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8684 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8685 TypeExpr = UO->getSubExpr();
8686 continue;
8687 }
8688 return false;
8689 }
8690
8691 case Stmt::DeclRefExprClass: {
8692 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8693 *VD = DRE->getDecl();
8694 return true;
8695 }
8696
8697 case Stmt::IntegerLiteralClass: {
8698 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8699 llvm::APInt MagicValueAPInt = IL->getValue();
8700 if (MagicValueAPInt.getActiveBits() <= 64) {
8701 *MagicValue = MagicValueAPInt.getZExtValue();
8702 return true;
8703 } else
8704 return false;
8705 }
8706
8707 case Stmt::BinaryConditionalOperatorClass:
8708 case Stmt::ConditionalOperatorClass: {
8709 const AbstractConditionalOperator *ACO =
8710 cast<AbstractConditionalOperator>(TypeExpr);
8711 bool Result;
8712 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8713 if (Result)
8714 TypeExpr = ACO->getTrueExpr();
8715 else
8716 TypeExpr = ACO->getFalseExpr();
8717 continue;
8718 }
8719 return false;
8720 }
8721
8722 case Stmt::BinaryOperatorClass: {
8723 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8724 if (BO->getOpcode() == BO_Comma) {
8725 TypeExpr = BO->getRHS();
8726 continue;
8727 }
8728 return false;
8729 }
8730
8731 default:
8732 return false;
8733 }
8734 }
8735}
8736
8737/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8738///
8739/// \param TypeExpr Expression that specifies a type tag.
8740///
8741/// \param MagicValues Registered magic values.
8742///
8743/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8744/// kind.
8745///
8746/// \param TypeInfo Information about the corresponding C type.
8747///
8748/// \returns true if the corresponding C type was found.
8749bool GetMatchingCType(
8750 const IdentifierInfo *ArgumentKind,
8751 const Expr *TypeExpr, const ASTContext &Ctx,
8752 const llvm::DenseMap<Sema::TypeTagMagicValue,
8753 Sema::TypeTagData> *MagicValues,
8754 bool &FoundWrongKind,
8755 Sema::TypeTagData &TypeInfo) {
8756 FoundWrongKind = false;
8757
8758 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008759 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008760
8761 uint64_t MagicValue;
8762
8763 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8764 return false;
8765
8766 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008767 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008768 if (I->getArgumentKind() != ArgumentKind) {
8769 FoundWrongKind = true;
8770 return false;
8771 }
8772 TypeInfo.Type = I->getMatchingCType();
8773 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8774 TypeInfo.MustBeNull = I->getMustBeNull();
8775 return true;
8776 }
8777 return false;
8778 }
8779
8780 if (!MagicValues)
8781 return false;
8782
8783 llvm::DenseMap<Sema::TypeTagMagicValue,
8784 Sema::TypeTagData>::const_iterator I =
8785 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8786 if (I == MagicValues->end())
8787 return false;
8788
8789 TypeInfo = I->second;
8790 return true;
8791}
8792} // unnamed namespace
8793
8794void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8795 uint64_t MagicValue, QualType Type,
8796 bool LayoutCompatible,
8797 bool MustBeNull) {
8798 if (!TypeTagForDatatypeMagicValues)
8799 TypeTagForDatatypeMagicValues.reset(
8800 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8801
8802 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8803 (*TypeTagForDatatypeMagicValues)[Magic] =
8804 TypeTagData(Type, LayoutCompatible, MustBeNull);
8805}
8806
8807namespace {
8808bool IsSameCharType(QualType T1, QualType T2) {
8809 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8810 if (!BT1)
8811 return false;
8812
8813 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8814 if (!BT2)
8815 return false;
8816
8817 BuiltinType::Kind T1Kind = BT1->getKind();
8818 BuiltinType::Kind T2Kind = BT2->getKind();
8819
8820 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8821 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8822 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8823 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8824}
8825} // unnamed namespace
8826
8827void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8828 const Expr * const *ExprArgs) {
8829 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8830 bool IsPointerAttr = Attr->getIsPointer();
8831
8832 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8833 bool FoundWrongKind;
8834 TypeTagData TypeInfo;
8835 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8836 TypeTagForDatatypeMagicValues.get(),
8837 FoundWrongKind, TypeInfo)) {
8838 if (FoundWrongKind)
8839 Diag(TypeTagExpr->getExprLoc(),
8840 diag::warn_type_tag_for_datatype_wrong_kind)
8841 << TypeTagExpr->getSourceRange();
8842 return;
8843 }
8844
8845 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8846 if (IsPointerAttr) {
8847 // Skip implicit cast of pointer to `void *' (as a function argument).
8848 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008849 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008850 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008851 ArgumentExpr = ICE->getSubExpr();
8852 }
8853 QualType ArgumentType = ArgumentExpr->getType();
8854
8855 // Passing a `void*' pointer shouldn't trigger a warning.
8856 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8857 return;
8858
8859 if (TypeInfo.MustBeNull) {
8860 // Type tag with matching void type requires a null pointer.
8861 if (!ArgumentExpr->isNullPointerConstant(Context,
8862 Expr::NPC_ValueDependentIsNotNull)) {
8863 Diag(ArgumentExpr->getExprLoc(),
8864 diag::warn_type_safety_null_pointer_required)
8865 << ArgumentKind->getName()
8866 << ArgumentExpr->getSourceRange()
8867 << TypeTagExpr->getSourceRange();
8868 }
8869 return;
8870 }
8871
8872 QualType RequiredType = TypeInfo.Type;
8873 if (IsPointerAttr)
8874 RequiredType = Context.getPointerType(RequiredType);
8875
8876 bool mismatch = false;
8877 if (!TypeInfo.LayoutCompatible) {
8878 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8879
8880 // C++11 [basic.fundamental] p1:
8881 // Plain char, signed char, and unsigned char are three distinct types.
8882 //
8883 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8884 // char' depending on the current char signedness mode.
8885 if (mismatch)
8886 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8887 RequiredType->getPointeeType())) ||
8888 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8889 mismatch = false;
8890 } else
8891 if (IsPointerAttr)
8892 mismatch = !isLayoutCompatible(Context,
8893 ArgumentType->getPointeeType(),
8894 RequiredType->getPointeeType());
8895 else
8896 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8897
8898 if (mismatch)
8899 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008900 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008901 << TypeInfo.LayoutCompatible << RequiredType
8902 << ArgumentExpr->getSourceRange()
8903 << TypeTagExpr->getSourceRange();
8904}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008905