blob: 8ba9c685cd128254d399d492fea09ed5993e8593 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000035#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000040#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043
Chris Lattnera26fb342009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000048}
49
John McCallbebede42011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerouge4a5b4442012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith6cbd65d2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000104 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000109 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000110 TheCall->setType(ResultType);
111 return false;
112}
113
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000114static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115 CallExpr *TheCall, unsigned SizeIdx,
116 unsigned DstSizeIdx) {
117 if (TheCall->getNumArgs() <= SizeIdx ||
118 TheCall->getNumArgs() <= DstSizeIdx)
119 return;
120
121 const Expr *SizeArg = TheCall->getArg(SizeIdx);
122 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
123
124 llvm::APSInt Size, DstSize;
125
126 // find out if both sizes are known at compile time
127 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
129 return;
130
131 if (Size.ule(DstSize))
132 return;
133
134 // confirmed overflow so generate the diagnostic.
135 IdentifierInfo *FnName = FDecl->getIdentifier();
136 SourceLocation SL = TheCall->getLocStart();
137 SourceRange SR = TheCall->getSourceRange();
138
139 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
140}
141
Peter Collingbournef7706832014-12-12 23:41:25 +0000142static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
143 if (checkArgCount(S, BuiltinCall, 2))
144 return true;
145
146 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
147 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
148 Expr *Call = BuiltinCall->getArg(0);
149 Expr *Chain = BuiltinCall->getArg(1);
150
151 if (Call->getStmtClass() != Stmt::CallExprClass) {
152 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
153 << Call->getSourceRange();
154 return true;
155 }
156
157 auto CE = cast<CallExpr>(Call);
158 if (CE->getCallee()->getType()->isBlockPointerType()) {
159 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
160 << Call->getSourceRange();
161 return true;
162 }
163
164 const Decl *TargetDecl = CE->getCalleeDecl();
165 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
166 if (FD->getBuiltinID()) {
167 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
168 << Call->getSourceRange();
169 return true;
170 }
171
172 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
173 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
174 << Call->getSourceRange();
175 return true;
176 }
177
178 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
179 if (ChainResult.isInvalid())
180 return true;
181 if (!ChainResult.get()->getType()->isPointerType()) {
182 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
183 << Chain->getSourceRange();
184 return true;
185 }
186
David Majnemerced8bdf2015-02-25 17:36:15 +0000187 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000188 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
189 QualType BuiltinTy = S.Context.getFunctionType(
190 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
191 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
192
193 Builtin =
194 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
195
196 BuiltinCall->setType(CE->getType());
197 BuiltinCall->setValueKind(CE->getValueKind());
198 BuiltinCall->setObjectKind(CE->getObjectKind());
199 BuiltinCall->setCallee(Builtin);
200 BuiltinCall->setArg(1, ChainResult.get());
201
202 return false;
203}
204
Reid Kleckner1d59f992015-01-22 01:36:17 +0000205static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
206 Scope::ScopeFlags NeededScopeFlags,
207 unsigned DiagID) {
208 // Scopes aren't available during instantiation. Fortunately, builtin
209 // functions cannot be template args so they cannot be formed through template
210 // instantiation. Therefore checking once during the parse is sufficient.
211 if (!SemaRef.ActiveTemplateInstantiations.empty())
212 return false;
213
214 Scope *S = SemaRef.getCurScope();
215 while (S && !S->isSEHExceptScope())
216 S = S->getParent();
217 if (!S || !(S->getFlags() & NeededScopeFlags)) {
218 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
219 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
220 << DRE->getDecl()->getIdentifier();
221 return true;
222 }
223
224 return false;
225}
226
John McCalldadc5752010-08-24 06:29:42 +0000227ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000228Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
229 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000230 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000231
Chris Lattner3be167f2010-10-01 23:23:24 +0000232 // Find out if any arguments are required to be integer constant expressions.
233 unsigned ICEArguments = 0;
234 ASTContext::GetBuiltinTypeError Error;
235 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
236 if (Error != ASTContext::GE_None)
237 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
238
239 // If any arguments are required to be ICE's, check and diagnose.
240 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
241 // Skip arguments not required to be ICE's.
242 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
243
244 llvm::APSInt Result;
245 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
246 return true;
247 ICEArguments &= ~(1 << ArgNo);
248 }
249
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000250 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000251 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000252 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000253 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000254 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000255 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000256 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000257 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000258 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000259 if (SemaBuiltinVAStart(TheCall))
260 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000261 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000262 case Builtin::BI__va_start: {
263 switch (Context.getTargetInfo().getTriple().getArch()) {
264 case llvm::Triple::arm:
265 case llvm::Triple::thumb:
266 if (SemaBuiltinVAStartARM(TheCall))
267 return ExprError();
268 break;
269 default:
270 if (SemaBuiltinVAStart(TheCall))
271 return ExprError();
272 break;
273 }
274 break;
275 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000276 case Builtin::BI__builtin_isgreater:
277 case Builtin::BI__builtin_isgreaterequal:
278 case Builtin::BI__builtin_isless:
279 case Builtin::BI__builtin_islessequal:
280 case Builtin::BI__builtin_islessgreater:
281 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000282 if (SemaBuiltinUnorderedCompare(TheCall))
283 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000284 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000285 case Builtin::BI__builtin_fpclassify:
286 if (SemaBuiltinFPClassification(TheCall, 6))
287 return ExprError();
288 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000289 case Builtin::BI__builtin_isfinite:
290 case Builtin::BI__builtin_isinf:
291 case Builtin::BI__builtin_isinf_sign:
292 case Builtin::BI__builtin_isnan:
293 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000294 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000295 return ExprError();
296 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000297 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000298 return SemaBuiltinShuffleVector(TheCall);
299 // TheCall will be freed by the smart pointer here, but that's fine, since
300 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000301 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000302 if (SemaBuiltinPrefetch(TheCall))
303 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000304 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000305 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000306 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000307 if (SemaBuiltinAssume(TheCall))
308 return ExprError();
309 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000310 case Builtin::BI__builtin_assume_aligned:
311 if (SemaBuiltinAssumeAligned(TheCall))
312 return ExprError();
313 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000314 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000315 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000316 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000317 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000318 case Builtin::BI__builtin_longjmp:
319 if (SemaBuiltinLongjmp(TheCall))
320 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000321 break;
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;
Craig Topper1e2f8852015-02-26 06:23:15 +0000885 case X86::BI__builtin_ia32_insert128i256: i = 2, l = 0; u = 1; break;
Craig Topper16015252015-01-31 06:31:23 +0000886 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +0000887 case X86::BI__builtin_ia32_vpermil2pd:
888 case X86::BI__builtin_ia32_vpermil2pd256:
889 case X86::BI__builtin_ia32_vpermil2ps:
890 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +0000891 case X86::BI__builtin_ia32_cmpb128_mask:
892 case X86::BI__builtin_ia32_cmpw128_mask:
893 case X86::BI__builtin_ia32_cmpd128_mask:
894 case X86::BI__builtin_ia32_cmpq128_mask:
895 case X86::BI__builtin_ia32_cmpb256_mask:
896 case X86::BI__builtin_ia32_cmpw256_mask:
897 case X86::BI__builtin_ia32_cmpd256_mask:
898 case X86::BI__builtin_ia32_cmpq256_mask:
899 case X86::BI__builtin_ia32_cmpb512_mask:
900 case X86::BI__builtin_ia32_cmpw512_mask:
901 case X86::BI__builtin_ia32_cmpd512_mask:
902 case X86::BI__builtin_ia32_cmpq512_mask:
903 case X86::BI__builtin_ia32_ucmpb128_mask:
904 case X86::BI__builtin_ia32_ucmpw128_mask:
905 case X86::BI__builtin_ia32_ucmpd128_mask:
906 case X86::BI__builtin_ia32_ucmpq128_mask:
907 case X86::BI__builtin_ia32_ucmpb256_mask:
908 case X86::BI__builtin_ia32_ucmpw256_mask:
909 case X86::BI__builtin_ia32_ucmpd256_mask:
910 case X86::BI__builtin_ia32_ucmpq256_mask:
911 case X86::BI__builtin_ia32_ucmpb512_mask:
912 case X86::BI__builtin_ia32_ucmpw512_mask:
913 case X86::BI__builtin_ia32_ucmpd512_mask:
914 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +0000915 case X86::BI__builtin_ia32_roundps:
916 case X86::BI__builtin_ia32_roundpd:
917 case X86::BI__builtin_ia32_roundps256:
918 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
919 case X86::BI__builtin_ia32_roundss:
920 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
921 case X86::BI__builtin_ia32_cmpps:
922 case X86::BI__builtin_ia32_cmpss:
923 case X86::BI__builtin_ia32_cmppd:
924 case X86::BI__builtin_ia32_cmpsd:
925 case X86::BI__builtin_ia32_cmpps256:
926 case X86::BI__builtin_ia32_cmppd256:
927 case X86::BI__builtin_ia32_cmpps512_mask:
928 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +0000929 case X86::BI__builtin_ia32_vpcomub:
930 case X86::BI__builtin_ia32_vpcomuw:
931 case X86::BI__builtin_ia32_vpcomud:
932 case X86::BI__builtin_ia32_vpcomuq:
933 case X86::BI__builtin_ia32_vpcomb:
934 case X86::BI__builtin_ia32_vpcomw:
935 case X86::BI__builtin_ia32_vpcomd:
936 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000937 }
Craig Topperdd84ec52014-12-27 07:00:08 +0000938 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000939}
940
Richard Smith55ce3522012-06-25 20:30:08 +0000941/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
942/// parameter with the FormatAttr's correct format_idx and firstDataArg.
943/// Returns true when the format fits the function and the FormatStringInfo has
944/// been populated.
945bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
946 FormatStringInfo *FSI) {
947 FSI->HasVAListArg = Format->getFirstArg() == 0;
948 FSI->FormatIdx = Format->getFormatIdx() - 1;
949 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000950
Richard Smith55ce3522012-06-25 20:30:08 +0000951 // The way the format attribute works in GCC, the implicit this argument
952 // of member functions is counted. However, it doesn't appear in our own
953 // lists, so decrement format_idx in that case.
954 if (IsCXXMember) {
955 if(FSI->FormatIdx == 0)
956 return false;
957 --FSI->FormatIdx;
958 if (FSI->FirstDataArg != 0)
959 --FSI->FirstDataArg;
960 }
961 return true;
962}
Mike Stump11289f42009-09-09 15:08:12 +0000963
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000964/// Checks if a the given expression evaluates to null.
965///
966/// \brief Returns true if the value evaluates to null.
967static bool CheckNonNullExpr(Sema &S,
968 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000969 // As a special case, transparent unions initialized with zero are
970 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000971 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000972 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
973 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000974 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000975 if (const InitListExpr *ILE =
976 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000977 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000978 }
979
980 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000981 return (!Expr->isValueDependent() &&
982 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
983 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000984}
985
986static void CheckNonNullArgument(Sema &S,
987 const Expr *ArgExpr,
988 SourceLocation CallSiteLoc) {
989 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000990 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
991}
992
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000993bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
994 FormatStringInfo FSI;
995 if ((GetFormatStringType(Format) == FST_NSString) &&
996 getFormatStringInfo(Format, false, &FSI)) {
997 Idx = FSI.FormatIdx;
998 return true;
999 }
1000 return false;
1001}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001002/// \brief Diagnose use of %s directive in an NSString which is being passed
1003/// as formatting string to formatting method.
1004static void
1005DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1006 const NamedDecl *FDecl,
1007 Expr **Args,
1008 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001009 unsigned Idx = 0;
1010 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001011 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1012 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001013 Idx = 2;
1014 Format = true;
1015 }
1016 else
1017 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1018 if (S.GetFormatNSStringIdx(I, Idx)) {
1019 Format = true;
1020 break;
1021 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001022 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001023 if (!Format || NumArgs <= Idx)
1024 return;
1025 const Expr *FormatExpr = Args[Idx];
1026 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1027 FormatExpr = CSCE->getSubExpr();
1028 const StringLiteral *FormatString;
1029 if (const ObjCStringLiteral *OSL =
1030 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1031 FormatString = OSL->getString();
1032 else
1033 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1034 if (!FormatString)
1035 return;
1036 if (S.FormatStringHasSArg(FormatString)) {
1037 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1038 << "%s" << 1 << 1;
1039 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1040 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001041 }
1042}
1043
Ted Kremenek2bc73332014-01-17 06:24:43 +00001044static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001045 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +00001046 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001047 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001048 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001049 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001050 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001051 if (!NonNull->args_size()) {
1052 // Easy case: all pointer arguments are nonnull.
1053 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +00001054 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +00001055 CheckNonNullArgument(S, Arg, CallSiteLoc);
1056 return;
1057 }
1058
1059 for (unsigned Val : NonNull->args()) {
1060 if (Val >= Args.size())
1061 continue;
1062 if (NonNullArgs.empty())
1063 NonNullArgs.resize(Args.size());
1064 NonNullArgs.set(Val);
1065 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001066 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001067
1068 // Check the attributes on the parameters.
1069 ArrayRef<ParmVarDecl*> parms;
1070 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1071 parms = FD->parameters();
1072 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1073 parms = MD->parameters();
1074
Richard Smith588bd9b2014-08-27 04:59:42 +00001075 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001076 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +00001077 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001078 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +00001079 if (PVD->hasAttr<NonNullAttr>() ||
1080 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1081 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +00001082 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001083
1084 // In case this is a variadic call, check any remaining arguments.
1085 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1086 if (NonNullArgs[ArgIndex])
1087 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +00001088}
1089
Richard Smith55ce3522012-06-25 20:30:08 +00001090/// Handles the checks for format strings, non-POD arguments to vararg
1091/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00001092void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1093 unsigned NumParams, bool IsMemberFunction,
1094 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001095 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001096 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001097 if (CurContext->isDependentContext())
1098 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001099
Ted Kremenekb8176da2010-09-09 04:33:05 +00001100 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001101 llvm::SmallBitVector CheckedVarArgs;
1102 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001103 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001104 // Only create vector if there are format attributes.
1105 CheckedVarArgs.resize(Args.size());
1106
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001107 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001108 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001109 }
Richard Smithd7293d72013-08-05 18:49:43 +00001110 }
Richard Smith55ce3522012-06-25 20:30:08 +00001111
1112 // Refuse POD arguments that weren't caught by the format string
1113 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001114 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001115 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001116 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001117 if (const Expr *Arg = Args[ArgIdx]) {
1118 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1119 checkVariadicArgument(Arg, CallType);
1120 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001121 }
Richard Smithd7293d72013-08-05 18:49:43 +00001122 }
Mike Stump11289f42009-09-09 15:08:12 +00001123
Richard Trieu41bc0992013-06-22 00:20:41 +00001124 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001125 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001126
Richard Trieu41bc0992013-06-22 00:20:41 +00001127 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001128 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1129 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001130 }
Richard Smith55ce3522012-06-25 20:30:08 +00001131}
1132
1133/// CheckConstructorCall - Check a constructor call for correctness and safety
1134/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001135void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1136 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001137 const FunctionProtoType *Proto,
1138 SourceLocation Loc) {
1139 VariadicCallType CallType =
1140 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +00001141 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +00001142 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1143}
1144
1145/// CheckFunctionCall - Check a direct function call for various correctness
1146/// and safety properties not strictly enforced by the C type system.
1147bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1148 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001149 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1150 isa<CXXMethodDecl>(FDecl);
1151 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1152 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001153 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1154 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001155 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +00001156 Expr** Args = TheCall->getArgs();
1157 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001158 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001159 // If this is a call to a member operator, hide the first argument
1160 // from checkCall.
1161 // FIXME: Our choice of AST representation here is less than ideal.
1162 ++Args;
1163 --NumArgs;
1164 }
Craig Topper8c2a2a02014-08-30 16:55:39 +00001165 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +00001166 IsMemberFunction, TheCall->getRParenLoc(),
1167 TheCall->getCallee()->getSourceRange(), CallType);
1168
1169 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1170 // None of the checks below are needed for functions that don't have
1171 // simple names (e.g., C++ conversion functions).
1172 if (!FnInfo)
1173 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001174
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001175 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001176 if (getLangOpts().ObjC1)
1177 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001178
Anna Zaks22122702012-01-17 00:37:07 +00001179 unsigned CMId = FDecl->getMemoryFunctionKind();
1180 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001181 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001182
Anna Zaks201d4892012-01-13 21:52:01 +00001183 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001184 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001185 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001186 else if (CMId == Builtin::BIstrncat)
1187 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001188 else
Anna Zaks22122702012-01-17 00:37:07 +00001189 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001190
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001191 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001192}
1193
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001194bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001195 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001196 VariadicCallType CallType =
1197 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001198
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001199 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001200 /*IsMemberFunction=*/false,
1201 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001202
1203 return false;
1204}
1205
Richard Trieu664c4c62013-06-20 21:03:13 +00001206bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1207 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001208 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1209 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001210 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001211
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001212 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +00001213 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001214 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001215
Richard Trieu664c4c62013-06-20 21:03:13 +00001216 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001217 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001218 CallType = VariadicDoesNotApply;
1219 } else if (Ty->isBlockPointerType()) {
1220 CallType = VariadicBlock;
1221 } else { // Ty->isFunctionPointerType()
1222 CallType = VariadicFunction;
1223 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001224 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001225
Craig Topper8c2a2a02014-08-30 16:55:39 +00001226 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1227 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001228 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001229 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001230
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001231 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001232}
1233
Richard Trieu41bc0992013-06-22 00:20:41 +00001234/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1235/// such as function pointers returned from functions.
1236bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001237 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001238 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001239 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001240
Craig Topperc3ec1492014-05-26 06:22:03 +00001241 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001242 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001243 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001244 TheCall->getCallee()->getSourceRange(), CallType);
1245
1246 return false;
1247}
1248
Tim Northovere94a34c2014-03-11 10:49:14 +00001249static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1250 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1251 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1252 return false;
1253
1254 switch (Op) {
1255 case AtomicExpr::AO__c11_atomic_init:
1256 llvm_unreachable("There is no ordering argument for an init");
1257
1258 case AtomicExpr::AO__c11_atomic_load:
1259 case AtomicExpr::AO__atomic_load_n:
1260 case AtomicExpr::AO__atomic_load:
1261 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1262 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1263
1264 case AtomicExpr::AO__c11_atomic_store:
1265 case AtomicExpr::AO__atomic_store:
1266 case AtomicExpr::AO__atomic_store_n:
1267 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1268 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1269 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1270
1271 default:
1272 return true;
1273 }
1274}
1275
Richard Smithfeea8832012-04-12 05:08:17 +00001276ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1277 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001278 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1279 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001280
Richard Smithfeea8832012-04-12 05:08:17 +00001281 // All these operations take one of the following forms:
1282 enum {
1283 // C __c11_atomic_init(A *, C)
1284 Init,
1285 // C __c11_atomic_load(A *, int)
1286 Load,
1287 // void __atomic_load(A *, CP, int)
1288 Copy,
1289 // C __c11_atomic_add(A *, M, int)
1290 Arithmetic,
1291 // C __atomic_exchange_n(A *, CP, int)
1292 Xchg,
1293 // void __atomic_exchange(A *, C *, CP, int)
1294 GNUXchg,
1295 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1296 C11CmpXchg,
1297 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1298 GNUCmpXchg
1299 } Form = Init;
1300 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1301 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1302 // where:
1303 // C is an appropriate type,
1304 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1305 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1306 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1307 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001308
Richard Smithfeea8832012-04-12 05:08:17 +00001309 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1310 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1311 && "need to update code for modified C11 atomics");
1312 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1313 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1314 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1315 Op == AtomicExpr::AO__atomic_store_n ||
1316 Op == AtomicExpr::AO__atomic_exchange_n ||
1317 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1318 bool IsAddSub = false;
1319
1320 switch (Op) {
1321 case AtomicExpr::AO__c11_atomic_init:
1322 Form = Init;
1323 break;
1324
1325 case AtomicExpr::AO__c11_atomic_load:
1326 case AtomicExpr::AO__atomic_load_n:
1327 Form = Load;
1328 break;
1329
1330 case AtomicExpr::AO__c11_atomic_store:
1331 case AtomicExpr::AO__atomic_load:
1332 case AtomicExpr::AO__atomic_store:
1333 case AtomicExpr::AO__atomic_store_n:
1334 Form = Copy;
1335 break;
1336
1337 case AtomicExpr::AO__c11_atomic_fetch_add:
1338 case AtomicExpr::AO__c11_atomic_fetch_sub:
1339 case AtomicExpr::AO__atomic_fetch_add:
1340 case AtomicExpr::AO__atomic_fetch_sub:
1341 case AtomicExpr::AO__atomic_add_fetch:
1342 case AtomicExpr::AO__atomic_sub_fetch:
1343 IsAddSub = true;
1344 // Fall through.
1345 case AtomicExpr::AO__c11_atomic_fetch_and:
1346 case AtomicExpr::AO__c11_atomic_fetch_or:
1347 case AtomicExpr::AO__c11_atomic_fetch_xor:
1348 case AtomicExpr::AO__atomic_fetch_and:
1349 case AtomicExpr::AO__atomic_fetch_or:
1350 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001351 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001352 case AtomicExpr::AO__atomic_and_fetch:
1353 case AtomicExpr::AO__atomic_or_fetch:
1354 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001355 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001356 Form = Arithmetic;
1357 break;
1358
1359 case AtomicExpr::AO__c11_atomic_exchange:
1360 case AtomicExpr::AO__atomic_exchange_n:
1361 Form = Xchg;
1362 break;
1363
1364 case AtomicExpr::AO__atomic_exchange:
1365 Form = GNUXchg;
1366 break;
1367
1368 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1369 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1370 Form = C11CmpXchg;
1371 break;
1372
1373 case AtomicExpr::AO__atomic_compare_exchange:
1374 case AtomicExpr::AO__atomic_compare_exchange_n:
1375 Form = GNUCmpXchg;
1376 break;
1377 }
1378
1379 // Check we have the right number of arguments.
1380 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001381 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_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();
Richard Smithfeea8832012-04-12 05:08:17 +00001385 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1386 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001387 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001388 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001389 << TheCall->getCallee()->getSourceRange();
1390 return ExprError();
1391 }
1392
Richard Smithfeea8832012-04-12 05:08:17 +00001393 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001394 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001395 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1396 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1397 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001398 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001399 << Ptr->getType() << Ptr->getSourceRange();
1400 return ExprError();
1401 }
1402
Richard Smithfeea8832012-04-12 05:08:17 +00001403 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1404 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1405 QualType ValType = AtomTy; // 'C'
1406 if (IsC11) {
1407 if (!AtomTy->isAtomicType()) {
1408 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1409 << Ptr->getType() << Ptr->getSourceRange();
1410 return ExprError();
1411 }
Richard Smithe00921a2012-09-15 06:09:58 +00001412 if (AtomTy.isConstQualified()) {
1413 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1414 << Ptr->getType() << Ptr->getSourceRange();
1415 return ExprError();
1416 }
Richard Smithfeea8832012-04-12 05:08:17 +00001417 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001418 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001419
Richard Smithfeea8832012-04-12 05:08:17 +00001420 // For an arithmetic operation, the implied arithmetic must be well-formed.
1421 if (Form == Arithmetic) {
1422 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1423 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1424 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1425 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1426 return ExprError();
1427 }
1428 if (!IsAddSub && !ValType->isIntegerType()) {
1429 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1430 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1431 return ExprError();
1432 }
David Majnemere85cff82015-01-28 05:48:06 +00001433 if (IsC11 && ValType->isPointerType() &&
1434 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1435 diag::err_incomplete_type)) {
1436 return ExprError();
1437 }
Richard Smithfeea8832012-04-12 05:08:17 +00001438 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1439 // For __atomic_*_n operations, the value type must be a scalar integral or
1440 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001441 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001442 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1443 return ExprError();
1444 }
1445
Eli Friedmanaa769812013-09-11 03:49:34 +00001446 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1447 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001448 // For GNU atomics, require a trivially-copyable type. This is not part of
1449 // the GNU atomics specification, but we enforce it for sanity.
1450 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001451 << Ptr->getType() << Ptr->getSourceRange();
1452 return ExprError();
1453 }
1454
Richard Smithfeea8832012-04-12 05:08:17 +00001455 // FIXME: For any builtin other than a load, the ValType must not be
1456 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001457
1458 switch (ValType.getObjCLifetime()) {
1459 case Qualifiers::OCL_None:
1460 case Qualifiers::OCL_ExplicitNone:
1461 // okay
1462 break;
1463
1464 case Qualifiers::OCL_Weak:
1465 case Qualifiers::OCL_Strong:
1466 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001467 // FIXME: Can this happen? By this point, ValType should be known
1468 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001469 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1470 << ValType << Ptr->getSourceRange();
1471 return ExprError();
1472 }
1473
1474 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001475 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001476 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001477 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001478 ResultType = Context.BoolTy;
1479
Richard Smithfeea8832012-04-12 05:08:17 +00001480 // The type of a parameter passed 'by value'. In the GNU atomics, such
1481 // arguments are actually passed as pointers.
1482 QualType ByValType = ValType; // 'CP'
1483 if (!IsC11 && !IsN)
1484 ByValType = Ptr->getType();
1485
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001486 // The first argument --- the pointer --- has a fixed type; we
1487 // deduce the types of the rest of the arguments accordingly. Walk
1488 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001489 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001490 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001491 if (i < NumVals[Form] + 1) {
1492 switch (i) {
1493 case 1:
1494 // The second argument is the non-atomic operand. For arithmetic, this
1495 // is always passed by value, and for a compare_exchange it is always
1496 // passed by address. For the rest, GNU uses by-address and C11 uses
1497 // by-value.
1498 assert(Form != Load);
1499 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1500 Ty = ValType;
1501 else if (Form == Copy || Form == Xchg)
1502 Ty = ByValType;
1503 else if (Form == Arithmetic)
1504 Ty = Context.getPointerDiffType();
1505 else
1506 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1507 break;
1508 case 2:
1509 // The third argument to compare_exchange / GNU exchange is a
1510 // (pointer to a) desired value.
1511 Ty = ByValType;
1512 break;
1513 case 3:
1514 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1515 Ty = Context.BoolTy;
1516 break;
1517 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001518 } else {
1519 // The order(s) are always converted to int.
1520 Ty = Context.IntTy;
1521 }
Richard Smithfeea8832012-04-12 05:08:17 +00001522
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001523 InitializedEntity Entity =
1524 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001525 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001526 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1527 if (Arg.isInvalid())
1528 return true;
1529 TheCall->setArg(i, Arg.get());
1530 }
1531
Richard Smithfeea8832012-04-12 05:08:17 +00001532 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001533 SmallVector<Expr*, 5> SubExprs;
1534 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001535 switch (Form) {
1536 case Init:
1537 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001538 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001539 break;
1540 case Load:
1541 SubExprs.push_back(TheCall->getArg(1)); // Order
1542 break;
1543 case Copy:
1544 case Arithmetic:
1545 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001546 SubExprs.push_back(TheCall->getArg(2)); // Order
1547 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001548 break;
1549 case GNUXchg:
1550 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1551 SubExprs.push_back(TheCall->getArg(3)); // Order
1552 SubExprs.push_back(TheCall->getArg(1)); // Val1
1553 SubExprs.push_back(TheCall->getArg(2)); // Val2
1554 break;
1555 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001556 SubExprs.push_back(TheCall->getArg(3)); // Order
1557 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001558 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001559 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001560 break;
1561 case GNUCmpXchg:
1562 SubExprs.push_back(TheCall->getArg(4)); // Order
1563 SubExprs.push_back(TheCall->getArg(1)); // Val1
1564 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1565 SubExprs.push_back(TheCall->getArg(2)); // Val2
1566 SubExprs.push_back(TheCall->getArg(3)); // Weak
1567 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001568 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001569
1570 if (SubExprs.size() >= 2 && Form != Init) {
1571 llvm::APSInt Result(32);
1572 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1573 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001574 Diag(SubExprs[1]->getLocStart(),
1575 diag::warn_atomic_op_has_invalid_memory_order)
1576 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001577 }
1578
Fariborz Jahanian615de762013-05-28 17:37:39 +00001579 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1580 SubExprs, ResultType, Op,
1581 TheCall->getRParenLoc());
1582
1583 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1584 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1585 Context.AtomicUsesUnsupportedLibcall(AE))
1586 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1587 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001588
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001589 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001590}
1591
1592
John McCall29ad95b2011-08-27 01:09:30 +00001593/// checkBuiltinArgument - Given a call to a builtin function, perform
1594/// normal type-checking on the given argument, updating the call in
1595/// place. This is useful when a builtin function requires custom
1596/// type-checking for some of its arguments but not necessarily all of
1597/// them.
1598///
1599/// Returns true on error.
1600static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1601 FunctionDecl *Fn = E->getDirectCallee();
1602 assert(Fn && "builtin call without direct callee!");
1603
1604 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1605 InitializedEntity Entity =
1606 InitializedEntity::InitializeParameter(S.Context, Param);
1607
1608 ExprResult Arg = E->getArg(0);
1609 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1610 if (Arg.isInvalid())
1611 return true;
1612
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001613 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001614 return false;
1615}
1616
Chris Lattnerdc046542009-05-08 06:58:22 +00001617/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1618/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1619/// type of its first argument. The main ActOnCallExpr routines have already
1620/// promoted the types of arguments because all of these calls are prototyped as
1621/// void(...).
1622///
1623/// This function goes through and does final semantic checking for these
1624/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001625ExprResult
1626Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001627 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001628 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1629 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1630
1631 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001632 if (TheCall->getNumArgs() < 1) {
1633 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1634 << 0 << 1 << TheCall->getNumArgs()
1635 << TheCall->getCallee()->getSourceRange();
1636 return ExprError();
1637 }
Mike Stump11289f42009-09-09 15:08:12 +00001638
Chris Lattnerdc046542009-05-08 06:58:22 +00001639 // Inspect the first argument of the atomic builtin. This should always be
1640 // a pointer type, whose element is an integral scalar or pointer type.
1641 // Because it is a pointer type, we don't have to worry about any implicit
1642 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001643 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001644 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001645 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1646 if (FirstArgResult.isInvalid())
1647 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001648 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001649 TheCall->setArg(0, FirstArg);
1650
John McCall31168b02011-06-15 23:02:42 +00001651 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1652 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001653 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1654 << FirstArg->getType() << FirstArg->getSourceRange();
1655 return ExprError();
1656 }
Mike Stump11289f42009-09-09 15:08:12 +00001657
John McCall31168b02011-06-15 23:02:42 +00001658 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001659 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001660 !ValType->isBlockPointerType()) {
1661 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1662 << FirstArg->getType() << FirstArg->getSourceRange();
1663 return ExprError();
1664 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001665
John McCall31168b02011-06-15 23:02:42 +00001666 switch (ValType.getObjCLifetime()) {
1667 case Qualifiers::OCL_None:
1668 case Qualifiers::OCL_ExplicitNone:
1669 // okay
1670 break;
1671
1672 case Qualifiers::OCL_Weak:
1673 case Qualifiers::OCL_Strong:
1674 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001675 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001676 << ValType << FirstArg->getSourceRange();
1677 return ExprError();
1678 }
1679
John McCallb50451a2011-10-05 07:41:44 +00001680 // Strip any qualifiers off ValType.
1681 ValType = ValType.getUnqualifiedType();
1682
Chandler Carruth3973af72010-07-18 20:54:12 +00001683 // The majority of builtins return a value, but a few have special return
1684 // types, so allow them to override appropriately below.
1685 QualType ResultType = ValType;
1686
Chris Lattnerdc046542009-05-08 06:58:22 +00001687 // We need to figure out which concrete builtin this maps onto. For example,
1688 // __sync_fetch_and_add with a 2 byte object turns into
1689 // __sync_fetch_and_add_2.
1690#define BUILTIN_ROW(x) \
1691 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1692 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001693
Chris Lattnerdc046542009-05-08 06:58:22 +00001694 static const unsigned BuiltinIndices[][5] = {
1695 BUILTIN_ROW(__sync_fetch_and_add),
1696 BUILTIN_ROW(__sync_fetch_and_sub),
1697 BUILTIN_ROW(__sync_fetch_and_or),
1698 BUILTIN_ROW(__sync_fetch_and_and),
1699 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001700 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001701
Chris Lattnerdc046542009-05-08 06:58:22 +00001702 BUILTIN_ROW(__sync_add_and_fetch),
1703 BUILTIN_ROW(__sync_sub_and_fetch),
1704 BUILTIN_ROW(__sync_and_and_fetch),
1705 BUILTIN_ROW(__sync_or_and_fetch),
1706 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001707 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001708
Chris Lattnerdc046542009-05-08 06:58:22 +00001709 BUILTIN_ROW(__sync_val_compare_and_swap),
1710 BUILTIN_ROW(__sync_bool_compare_and_swap),
1711 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001712 BUILTIN_ROW(__sync_lock_release),
1713 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001714 };
Mike Stump11289f42009-09-09 15:08:12 +00001715#undef BUILTIN_ROW
1716
Chris Lattnerdc046542009-05-08 06:58:22 +00001717 // Determine the index of the size.
1718 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001719 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001720 case 1: SizeIndex = 0; break;
1721 case 2: SizeIndex = 1; break;
1722 case 4: SizeIndex = 2; break;
1723 case 8: SizeIndex = 3; break;
1724 case 16: SizeIndex = 4; break;
1725 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001726 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1727 << FirstArg->getType() << FirstArg->getSourceRange();
1728 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001729 }
Mike Stump11289f42009-09-09 15:08:12 +00001730
Chris Lattnerdc046542009-05-08 06:58:22 +00001731 // Each of these builtins has one pointer argument, followed by some number of
1732 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1733 // that we ignore. Find out which row of BuiltinIndices to read from as well
1734 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001735 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001736 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001737 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001738 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001739 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001740 case Builtin::BI__sync_fetch_and_add:
1741 case Builtin::BI__sync_fetch_and_add_1:
1742 case Builtin::BI__sync_fetch_and_add_2:
1743 case Builtin::BI__sync_fetch_and_add_4:
1744 case Builtin::BI__sync_fetch_and_add_8:
1745 case Builtin::BI__sync_fetch_and_add_16:
1746 BuiltinIndex = 0;
1747 break;
1748
1749 case Builtin::BI__sync_fetch_and_sub:
1750 case Builtin::BI__sync_fetch_and_sub_1:
1751 case Builtin::BI__sync_fetch_and_sub_2:
1752 case Builtin::BI__sync_fetch_and_sub_4:
1753 case Builtin::BI__sync_fetch_and_sub_8:
1754 case Builtin::BI__sync_fetch_and_sub_16:
1755 BuiltinIndex = 1;
1756 break;
1757
1758 case Builtin::BI__sync_fetch_and_or:
1759 case Builtin::BI__sync_fetch_and_or_1:
1760 case Builtin::BI__sync_fetch_and_or_2:
1761 case Builtin::BI__sync_fetch_and_or_4:
1762 case Builtin::BI__sync_fetch_and_or_8:
1763 case Builtin::BI__sync_fetch_and_or_16:
1764 BuiltinIndex = 2;
1765 break;
1766
1767 case Builtin::BI__sync_fetch_and_and:
1768 case Builtin::BI__sync_fetch_and_and_1:
1769 case Builtin::BI__sync_fetch_and_and_2:
1770 case Builtin::BI__sync_fetch_and_and_4:
1771 case Builtin::BI__sync_fetch_and_and_8:
1772 case Builtin::BI__sync_fetch_and_and_16:
1773 BuiltinIndex = 3;
1774 break;
Mike Stump11289f42009-09-09 15:08:12 +00001775
Douglas Gregor73722482011-11-28 16:30:08 +00001776 case Builtin::BI__sync_fetch_and_xor:
1777 case Builtin::BI__sync_fetch_and_xor_1:
1778 case Builtin::BI__sync_fetch_and_xor_2:
1779 case Builtin::BI__sync_fetch_and_xor_4:
1780 case Builtin::BI__sync_fetch_and_xor_8:
1781 case Builtin::BI__sync_fetch_and_xor_16:
1782 BuiltinIndex = 4;
1783 break;
1784
Hal Finkeld2208b52014-10-02 20:53:50 +00001785 case Builtin::BI__sync_fetch_and_nand:
1786 case Builtin::BI__sync_fetch_and_nand_1:
1787 case Builtin::BI__sync_fetch_and_nand_2:
1788 case Builtin::BI__sync_fetch_and_nand_4:
1789 case Builtin::BI__sync_fetch_and_nand_8:
1790 case Builtin::BI__sync_fetch_and_nand_16:
1791 BuiltinIndex = 5;
1792 WarnAboutSemanticsChange = true;
1793 break;
1794
Douglas Gregor73722482011-11-28 16:30:08 +00001795 case Builtin::BI__sync_add_and_fetch:
1796 case Builtin::BI__sync_add_and_fetch_1:
1797 case Builtin::BI__sync_add_and_fetch_2:
1798 case Builtin::BI__sync_add_and_fetch_4:
1799 case Builtin::BI__sync_add_and_fetch_8:
1800 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001801 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00001802 break;
1803
1804 case Builtin::BI__sync_sub_and_fetch:
1805 case Builtin::BI__sync_sub_and_fetch_1:
1806 case Builtin::BI__sync_sub_and_fetch_2:
1807 case Builtin::BI__sync_sub_and_fetch_4:
1808 case Builtin::BI__sync_sub_and_fetch_8:
1809 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001810 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00001811 break;
1812
1813 case Builtin::BI__sync_and_and_fetch:
1814 case Builtin::BI__sync_and_and_fetch_1:
1815 case Builtin::BI__sync_and_and_fetch_2:
1816 case Builtin::BI__sync_and_and_fetch_4:
1817 case Builtin::BI__sync_and_and_fetch_8:
1818 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001819 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00001820 break;
1821
1822 case Builtin::BI__sync_or_and_fetch:
1823 case Builtin::BI__sync_or_and_fetch_1:
1824 case Builtin::BI__sync_or_and_fetch_2:
1825 case Builtin::BI__sync_or_and_fetch_4:
1826 case Builtin::BI__sync_or_and_fetch_8:
1827 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001828 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00001829 break;
1830
1831 case Builtin::BI__sync_xor_and_fetch:
1832 case Builtin::BI__sync_xor_and_fetch_1:
1833 case Builtin::BI__sync_xor_and_fetch_2:
1834 case Builtin::BI__sync_xor_and_fetch_4:
1835 case Builtin::BI__sync_xor_and_fetch_8:
1836 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001837 BuiltinIndex = 10;
1838 break;
1839
1840 case Builtin::BI__sync_nand_and_fetch:
1841 case Builtin::BI__sync_nand_and_fetch_1:
1842 case Builtin::BI__sync_nand_and_fetch_2:
1843 case Builtin::BI__sync_nand_and_fetch_4:
1844 case Builtin::BI__sync_nand_and_fetch_8:
1845 case Builtin::BI__sync_nand_and_fetch_16:
1846 BuiltinIndex = 11;
1847 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00001848 break;
Mike Stump11289f42009-09-09 15:08:12 +00001849
Chris Lattnerdc046542009-05-08 06:58:22 +00001850 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001851 case Builtin::BI__sync_val_compare_and_swap_1:
1852 case Builtin::BI__sync_val_compare_and_swap_2:
1853 case Builtin::BI__sync_val_compare_and_swap_4:
1854 case Builtin::BI__sync_val_compare_and_swap_8:
1855 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001856 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00001857 NumFixed = 2;
1858 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001859
Chris Lattnerdc046542009-05-08 06:58:22 +00001860 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001861 case Builtin::BI__sync_bool_compare_and_swap_1:
1862 case Builtin::BI__sync_bool_compare_and_swap_2:
1863 case Builtin::BI__sync_bool_compare_and_swap_4:
1864 case Builtin::BI__sync_bool_compare_and_swap_8:
1865 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001866 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001867 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001868 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001869 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001870
1871 case Builtin::BI__sync_lock_test_and_set:
1872 case Builtin::BI__sync_lock_test_and_set_1:
1873 case Builtin::BI__sync_lock_test_and_set_2:
1874 case Builtin::BI__sync_lock_test_and_set_4:
1875 case Builtin::BI__sync_lock_test_and_set_8:
1876 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001877 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00001878 break;
1879
Chris Lattnerdc046542009-05-08 06:58:22 +00001880 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001881 case Builtin::BI__sync_lock_release_1:
1882 case Builtin::BI__sync_lock_release_2:
1883 case Builtin::BI__sync_lock_release_4:
1884 case Builtin::BI__sync_lock_release_8:
1885 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001886 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00001887 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001888 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001889 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001890
1891 case Builtin::BI__sync_swap:
1892 case Builtin::BI__sync_swap_1:
1893 case Builtin::BI__sync_swap_2:
1894 case Builtin::BI__sync_swap_4:
1895 case Builtin::BI__sync_swap_8:
1896 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001897 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00001898 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001899 }
Mike Stump11289f42009-09-09 15:08:12 +00001900
Chris Lattnerdc046542009-05-08 06:58:22 +00001901 // Now that we know how many fixed arguments we expect, first check that we
1902 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001903 if (TheCall->getNumArgs() < 1+NumFixed) {
1904 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1905 << 0 << 1+NumFixed << TheCall->getNumArgs()
1906 << TheCall->getCallee()->getSourceRange();
1907 return ExprError();
1908 }
Mike Stump11289f42009-09-09 15:08:12 +00001909
Hal Finkeld2208b52014-10-02 20:53:50 +00001910 if (WarnAboutSemanticsChange) {
1911 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1912 << TheCall->getCallee()->getSourceRange();
1913 }
1914
Chris Lattner5b9241b2009-05-08 15:36:58 +00001915 // Get the decl for the concrete builtin from this, we can tell what the
1916 // concrete integer type we should convert to is.
1917 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1918 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001919 FunctionDecl *NewBuiltinDecl;
1920 if (NewBuiltinID == BuiltinID)
1921 NewBuiltinDecl = FDecl;
1922 else {
1923 // Perform builtin lookup to avoid redeclaring it.
1924 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1925 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1926 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1927 assert(Res.getFoundDecl());
1928 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001929 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001930 return ExprError();
1931 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001932
John McCallcf142162010-08-07 06:22:56 +00001933 // The first argument --- the pointer --- has a fixed type; we
1934 // deduce the types of the rest of the arguments accordingly. Walk
1935 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001936 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001937 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001938
Chris Lattnerdc046542009-05-08 06:58:22 +00001939 // GCC does an implicit conversion to the pointer or integer ValType. This
1940 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001941 // Initialize the argument.
1942 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1943 ValType, /*consume*/ false);
1944 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001945 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001946 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001947
Chris Lattnerdc046542009-05-08 06:58:22 +00001948 // Okay, we have something that *can* be converted to the right type. Check
1949 // to see if there is a potentially weird extension going on here. This can
1950 // happen when you do an atomic operation on something like an char* and
1951 // pass in 42. The 42 gets converted to char. This is even more strange
1952 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001953 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001954 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001955 }
Mike Stump11289f42009-09-09 15:08:12 +00001956
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001957 ASTContext& Context = this->getASTContext();
1958
1959 // Create a new DeclRefExpr to refer to the new decl.
1960 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1961 Context,
1962 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001963 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001964 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001965 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001966 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001967 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001968 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001969
Chris Lattnerdc046542009-05-08 06:58:22 +00001970 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001971 // FIXME: This loses syntactic information.
1972 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1973 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1974 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001975 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001976
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001977 // Change the result type of the call to match the original value type. This
1978 // is arbitrary, but the codegen for these builtins ins design to handle it
1979 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001980 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001981
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001982 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001983}
1984
Chris Lattner6436fb62009-02-18 06:01:06 +00001985/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001986/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001987/// Note: It might also make sense to do the UTF-16 conversion here (would
1988/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001989bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001990 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001991 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1992
Douglas Gregorfb65e592011-07-27 05:40:30 +00001993 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001994 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1995 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001996 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001997 }
Mike Stump11289f42009-09-09 15:08:12 +00001998
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001999 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002000 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002001 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002002 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002003 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002004 UTF16 *ToPtr = &ToBuf[0];
2005
2006 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2007 &ToPtr, ToPtr + NumBytes,
2008 strictConversion);
2009 // Check for conversion failure.
2010 if (Result != conversionOK)
2011 Diag(Arg->getLocStart(),
2012 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2013 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002014 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002015}
2016
Chris Lattnere202e6a2007-12-20 00:05:45 +00002017/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2018/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00002019bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2020 Expr *Fn = TheCall->getCallee();
2021 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002022 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002023 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002024 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2025 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002026 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002027 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002028 return true;
2029 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002030
2031 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002032 return Diag(TheCall->getLocEnd(),
2033 diag::err_typecheck_call_too_few_args_at_least)
2034 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002035 }
2036
John McCall29ad95b2011-08-27 01:09:30 +00002037 // Type-check the first argument normally.
2038 if (checkBuiltinArgument(*this, TheCall, 0))
2039 return true;
2040
Chris Lattnere202e6a2007-12-20 00:05:45 +00002041 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002042 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002043 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002044 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002045 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002046 else if (FunctionDecl *FD = getCurFunctionDecl())
2047 isVariadic = FD->isVariadic();
2048 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002049 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002050
Chris Lattnere202e6a2007-12-20 00:05:45 +00002051 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002052 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2053 return true;
2054 }
Mike Stump11289f42009-09-09 15:08:12 +00002055
Chris Lattner43be2e62007-12-19 23:59:04 +00002056 // Verify that the second argument to the builtin is the last argument of the
2057 // current function or method.
2058 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002059 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002060
Nico Weber9eea7642013-05-24 23:31:57 +00002061 // These are valid if SecondArgIsLastNamedArgument is false after the next
2062 // block.
2063 QualType Type;
2064 SourceLocation ParamLoc;
2065
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002066 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2067 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002068 // FIXME: This isn't correct for methods (results in bogus warning).
2069 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002070 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002071 if (CurBlock)
2072 LastArg = *(CurBlock->TheDecl->param_end()-1);
2073 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002074 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002075 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002076 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002077 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002078
2079 Type = PV->getType();
2080 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002081 }
2082 }
Mike Stump11289f42009-09-09 15:08:12 +00002083
Chris Lattner43be2e62007-12-19 23:59:04 +00002084 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002085 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002086 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002087 else if (Type->isReferenceType()) {
2088 Diag(Arg->getLocStart(),
2089 diag::warn_va_start_of_reference_type_is_undefined);
2090 Diag(ParamLoc, diag::note_parameter_type) << Type;
2091 }
2092
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002093 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002094 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002095}
Chris Lattner43be2e62007-12-19 23:59:04 +00002096
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002097bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2098 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2099 // const char *named_addr);
2100
2101 Expr *Func = Call->getCallee();
2102
2103 if (Call->getNumArgs() < 3)
2104 return Diag(Call->getLocEnd(),
2105 diag::err_typecheck_call_too_few_args_at_least)
2106 << 0 /*function call*/ << 3 << Call->getNumArgs();
2107
2108 // Determine whether the current function is variadic or not.
2109 bool IsVariadic;
2110 if (BlockScopeInfo *CurBlock = getCurBlock())
2111 IsVariadic = CurBlock->TheDecl->isVariadic();
2112 else if (FunctionDecl *FD = getCurFunctionDecl())
2113 IsVariadic = FD->isVariadic();
2114 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2115 IsVariadic = MD->isVariadic();
2116 else
2117 llvm_unreachable("unexpected statement type");
2118
2119 if (!IsVariadic) {
2120 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2121 return true;
2122 }
2123
2124 // Type-check the first argument normally.
2125 if (checkBuiltinArgument(*this, Call, 0))
2126 return true;
2127
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002128 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002129 unsigned ArgNo;
2130 QualType Type;
2131 } ArgumentTypes[] = {
2132 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2133 { 2, Context.getSizeType() },
2134 };
2135
2136 for (const auto &AT : ArgumentTypes) {
2137 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2138 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2139 continue;
2140 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2141 << Arg->getType() << AT.Type << 1 /* different class */
2142 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2143 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2144 }
2145
2146 return false;
2147}
2148
Chris Lattner2da14fb2007-12-20 00:26:33 +00002149/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2150/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002151bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2152 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002153 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002154 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002155 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002156 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002157 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002158 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002159 << SourceRange(TheCall->getArg(2)->getLocStart(),
2160 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002161
John Wiegley01296292011-04-08 18:41:53 +00002162 ExprResult OrigArg0 = TheCall->getArg(0);
2163 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002164
Chris Lattner2da14fb2007-12-20 00:26:33 +00002165 // Do standard promotions between the two arguments, returning their common
2166 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002167 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002168 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2169 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002170
2171 // Make sure any conversions are pushed back into the call; this is
2172 // type safe since unordered compare builtins are declared as "_Bool
2173 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002174 TheCall->setArg(0, OrigArg0.get());
2175 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002176
John Wiegley01296292011-04-08 18:41:53 +00002177 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002178 return false;
2179
Chris Lattner2da14fb2007-12-20 00:26:33 +00002180 // If the common type isn't a real floating type, then the arguments were
2181 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002182 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002183 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002184 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002185 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2186 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002187
Chris Lattner2da14fb2007-12-20 00:26:33 +00002188 return false;
2189}
2190
Benjamin Kramer634fc102010-02-15 22:42:31 +00002191/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2192/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002193/// to check everything. We expect the last argument to be a floating point
2194/// value.
2195bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2196 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002197 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002198 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002199 if (TheCall->getNumArgs() > NumArgs)
2200 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002201 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002202 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002203 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002204 (*(TheCall->arg_end()-1))->getLocEnd());
2205
Benjamin Kramer64aae502010-02-16 10:07:31 +00002206 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002207
Eli Friedman7e4faac2009-08-31 20:06:00 +00002208 if (OrigArg->isTypeDependent())
2209 return false;
2210
Chris Lattner68784ef2010-05-06 05:50:07 +00002211 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002212 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002213 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002214 diag::err_typecheck_call_invalid_unary_fp)
2215 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002216
Chris Lattner68784ef2010-05-06 05:50:07 +00002217 // If this is an implicit conversion from float -> double, remove it.
2218 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2219 Expr *CastArg = Cast->getSubExpr();
2220 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2221 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2222 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002223 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002224 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002225 }
2226 }
2227
Eli Friedman7e4faac2009-08-31 20:06:00 +00002228 return false;
2229}
2230
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002231/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2232// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002233ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002234 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002235 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002236 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002237 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2238 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002239
Nate Begemana0110022010-06-08 00:16:34 +00002240 // Determine which of the following types of shufflevector we're checking:
2241 // 1) unary, vector mask: (lhs, mask)
2242 // 2) binary, vector mask: (lhs, rhs, mask)
2243 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2244 QualType resType = TheCall->getArg(0)->getType();
2245 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002246
Douglas Gregorc25f7662009-05-19 22:10:17 +00002247 if (!TheCall->getArg(0)->isTypeDependent() &&
2248 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002249 QualType LHSType = TheCall->getArg(0)->getType();
2250 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002251
Craig Topperbaca3892013-07-29 06:47:04 +00002252 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2253 return ExprError(Diag(TheCall->getLocStart(),
2254 diag::err_shufflevector_non_vector)
2255 << SourceRange(TheCall->getArg(0)->getLocStart(),
2256 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002257
Nate Begemana0110022010-06-08 00:16:34 +00002258 numElements = LHSType->getAs<VectorType>()->getNumElements();
2259 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002260
Nate Begemana0110022010-06-08 00:16:34 +00002261 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2262 // with mask. If so, verify that RHS is an integer vector type with the
2263 // same number of elts as lhs.
2264 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002265 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002266 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002267 return ExprError(Diag(TheCall->getLocStart(),
2268 diag::err_shufflevector_incompatible_vector)
2269 << SourceRange(TheCall->getArg(1)->getLocStart(),
2270 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002271 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002272 return ExprError(Diag(TheCall->getLocStart(),
2273 diag::err_shufflevector_incompatible_vector)
2274 << SourceRange(TheCall->getArg(0)->getLocStart(),
2275 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002276 } else if (numElements != numResElements) {
2277 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002278 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002279 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002280 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002281 }
2282
2283 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002284 if (TheCall->getArg(i)->isTypeDependent() ||
2285 TheCall->getArg(i)->isValueDependent())
2286 continue;
2287
Nate Begemana0110022010-06-08 00:16:34 +00002288 llvm::APSInt Result(32);
2289 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2290 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002291 diag::err_shufflevector_nonconstant_argument)
2292 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002293
Craig Topper50ad5b72013-08-03 17:40:38 +00002294 // Allow -1 which will be translated to undef in the IR.
2295 if (Result.isSigned() && Result.isAllOnesValue())
2296 continue;
2297
Chris Lattner7ab824e2008-08-10 02:05:13 +00002298 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002299 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002300 diag::err_shufflevector_argument_too_large)
2301 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002302 }
2303
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002304 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002305
Chris Lattner7ab824e2008-08-10 02:05:13 +00002306 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002307 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002308 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002309 }
2310
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002311 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2312 TheCall->getCallee()->getLocStart(),
2313 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002314}
Chris Lattner43be2e62007-12-19 23:59:04 +00002315
Hal Finkelc4d7c822013-09-18 03:29:45 +00002316/// SemaConvertVectorExpr - Handle __builtin_convertvector
2317ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2318 SourceLocation BuiltinLoc,
2319 SourceLocation RParenLoc) {
2320 ExprValueKind VK = VK_RValue;
2321 ExprObjectKind OK = OK_Ordinary;
2322 QualType DstTy = TInfo->getType();
2323 QualType SrcTy = E->getType();
2324
2325 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2326 return ExprError(Diag(BuiltinLoc,
2327 diag::err_convertvector_non_vector)
2328 << E->getSourceRange());
2329 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2330 return ExprError(Diag(BuiltinLoc,
2331 diag::err_convertvector_non_vector_type));
2332
2333 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2334 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2335 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2336 if (SrcElts != DstElts)
2337 return ExprError(Diag(BuiltinLoc,
2338 diag::err_convertvector_incompatible_vector)
2339 << E->getSourceRange());
2340 }
2341
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002342 return new (Context)
2343 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002344}
2345
Daniel Dunbarb7257262008-07-21 22:59:13 +00002346/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2347// This is declared to take (const void*, ...) and can take two
2348// optional constant int args.
2349bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002350 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002351
Chris Lattner3b054132008-11-19 05:08:23 +00002352 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002353 return Diag(TheCall->getLocEnd(),
2354 diag::err_typecheck_call_too_many_args_at_most)
2355 << 0 /*function call*/ << 3 << NumArgs
2356 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002357
2358 // Argument 0 is checked for us and the remaining arguments must be
2359 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002360 for (unsigned i = 1; i != NumArgs; ++i)
2361 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002362 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002363
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002364 return false;
2365}
2366
Hal Finkelf0417332014-07-17 14:25:55 +00002367/// SemaBuiltinAssume - Handle __assume (MS Extension).
2368// __assume does not evaluate its arguments, and should warn if its argument
2369// has side effects.
2370bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2371 Expr *Arg = TheCall->getArg(0);
2372 if (Arg->isInstantiationDependent()) return false;
2373
2374 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002375 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002376 << Arg->getSourceRange()
2377 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2378
2379 return false;
2380}
2381
2382/// Handle __builtin_assume_aligned. This is declared
2383/// as (const void*, size_t, ...) and can take one optional constant int arg.
2384bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2385 unsigned NumArgs = TheCall->getNumArgs();
2386
2387 if (NumArgs > 3)
2388 return Diag(TheCall->getLocEnd(),
2389 diag::err_typecheck_call_too_many_args_at_most)
2390 << 0 /*function call*/ << 3 << NumArgs
2391 << TheCall->getSourceRange();
2392
2393 // The alignment must be a constant integer.
2394 Expr *Arg = TheCall->getArg(1);
2395
2396 // We can't check the value of a dependent argument.
2397 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2398 llvm::APSInt Result;
2399 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2400 return true;
2401
2402 if (!Result.isPowerOf2())
2403 return Diag(TheCall->getLocStart(),
2404 diag::err_alignment_not_power_of_two)
2405 << Arg->getSourceRange();
2406 }
2407
2408 if (NumArgs > 2) {
2409 ExprResult Arg(TheCall->getArg(2));
2410 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2411 Context.getSizeType(), false);
2412 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2413 if (Arg.isInvalid()) return true;
2414 TheCall->setArg(2, Arg.get());
2415 }
Hal Finkelf0417332014-07-17 14:25:55 +00002416
2417 return false;
2418}
2419
Eric Christopher8d0c6212010-04-17 02:26:23 +00002420/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2421/// TheCall is a constant expression.
2422bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2423 llvm::APSInt &Result) {
2424 Expr *Arg = TheCall->getArg(ArgNum);
2425 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2426 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2427
2428 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2429
2430 if (!Arg->isIntegerConstantExpr(Result, Context))
2431 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002432 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002433
Chris Lattnerd545ad12009-09-23 06:06:36 +00002434 return false;
2435}
2436
Richard Sandiford28940af2014-04-16 08:47:51 +00002437/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2438/// TheCall is a constant expression in the range [Low, High].
2439bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2440 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002441 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002442
2443 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002444 Expr *Arg = TheCall->getArg(ArgNum);
2445 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002446 return false;
2447
Eric Christopher8d0c6212010-04-17 02:26:23 +00002448 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002449 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002450 return true;
2451
Richard Sandiford28940af2014-04-16 08:47:51 +00002452 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002453 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002454 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002455
2456 return false;
2457}
2458
Eli Friedmanc97d0142009-05-03 06:04:26 +00002459/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002460/// This checks that val is a constant 1.
2461bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2462 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002463 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002464
Eric Christopher8d0c6212010-04-17 02:26:23 +00002465 // TODO: This is less than ideal. Overload this to take a value.
2466 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2467 return true;
2468
2469 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002470 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2471 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2472
2473 return false;
2474}
2475
Richard Smithd7293d72013-08-05 18:49:43 +00002476namespace {
2477enum StringLiteralCheckType {
2478 SLCT_NotALiteral,
2479 SLCT_UncheckedLiteral,
2480 SLCT_CheckedLiteral
2481};
2482}
2483
Richard Smith55ce3522012-06-25 20:30:08 +00002484// Determine if an expression is a string literal or constant string.
2485// If this function returns false on the arguments to a function expecting a
2486// format string, we will usually need to emit a warning.
2487// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002488static StringLiteralCheckType
2489checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2490 bool HasVAListArg, unsigned format_idx,
2491 unsigned firstDataArg, Sema::FormatStringType Type,
2492 Sema::VariadicCallType CallType, bool InFunctionCall,
2493 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002494 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002495 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002496 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002497
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002498 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002499
Richard Smithd7293d72013-08-05 18:49:43 +00002500 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002501 // Technically -Wformat-nonliteral does not warn about this case.
2502 // The behavior of printf and friends in this case is implementation
2503 // dependent. Ideally if the format string cannot be null then
2504 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002505 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002506
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002507 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002508 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002509 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002510 // The expression is a literal if both sub-expressions were, and it was
2511 // completely checked only if both sub-expressions were checked.
2512 const AbstractConditionalOperator *C =
2513 cast<AbstractConditionalOperator>(E);
2514 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002515 checkFormatStringExpr(S, C->getTrueExpr(), 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 if (Left == SLCT_NotALiteral)
2519 return SLCT_NotALiteral;
2520 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002521 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002522 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002523 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002524 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002525 }
2526
2527 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002528 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2529 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002530 }
2531
John McCallc07a0c72011-02-17 10:25:35 +00002532 case Stmt::OpaqueValueExprClass:
2533 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2534 E = src;
2535 goto tryAgain;
2536 }
Richard Smith55ce3522012-06-25 20:30:08 +00002537 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002538
Ted Kremeneka8890832011-02-24 23:03:04 +00002539 case Stmt::PredefinedExprClass:
2540 // While __func__, etc., are technically not string literals, they
2541 // cannot contain format specifiers and thus are not a security
2542 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002543 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002544
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002545 case Stmt::DeclRefExprClass: {
2546 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002547
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002548 // As an exception, do not flag errors for variables binding to
2549 // const string literals.
2550 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2551 bool isConstant = false;
2552 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002553
Richard Smithd7293d72013-08-05 18:49:43 +00002554 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2555 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002556 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002557 isConstant = T.isConstant(S.Context) &&
2558 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002559 } else if (T->isObjCObjectPointerType()) {
2560 // In ObjC, there is usually no "const ObjectPointer" type,
2561 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002562 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002563 }
Mike Stump11289f42009-09-09 15:08:12 +00002564
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002565 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002566 if (const Expr *Init = VD->getAnyInitializer()) {
2567 // Look through initializers like const char c[] = { "foo" }
2568 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2569 if (InitList->isStringLiteralInit())
2570 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2571 }
Richard Smithd7293d72013-08-05 18:49:43 +00002572 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002573 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002574 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002575 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002576 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002577 }
Mike Stump11289f42009-09-09 15:08:12 +00002578
Anders Carlssonb012ca92009-06-28 19:55:58 +00002579 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2580 // special check to see if the format string is a function parameter
2581 // of the function calling the printf function. If the function
2582 // has an attribute indicating it is a printf-like function, then we
2583 // should suppress warnings concerning non-literals being used in a call
2584 // to a vprintf function. For example:
2585 //
2586 // void
2587 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2588 // va_list ap;
2589 // va_start(ap, fmt);
2590 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2591 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002592 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002593 if (HasVAListArg) {
2594 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2595 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2596 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002597 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002598 // adjust for implicit parameter
2599 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2600 if (MD->isInstance())
2601 ++PVIndex;
2602 // We also check if the formats are compatible.
2603 // We can't pass a 'scanf' string to a 'printf' function.
2604 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002605 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002606 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002607 }
2608 }
2609 }
2610 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002611 }
Mike Stump11289f42009-09-09 15:08:12 +00002612
Richard Smith55ce3522012-06-25 20:30:08 +00002613 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002614 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002615
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002616 case Stmt::CallExprClass:
2617 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002618 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002619 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2620 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2621 unsigned ArgIndex = FA->getFormatIdx();
2622 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2623 if (MD->isInstance())
2624 --ArgIndex;
2625 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002626
Richard Smithd7293d72013-08-05 18:49:43 +00002627 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002628 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002629 Type, CallType, InFunctionCall,
2630 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002631 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2632 unsigned BuiltinID = FD->getBuiltinID();
2633 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2634 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2635 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002636 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002637 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002638 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002639 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002640 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002641 }
2642 }
Mike Stump11289f42009-09-09 15:08:12 +00002643
Richard Smith55ce3522012-06-25 20:30:08 +00002644 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002645 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002646 case Stmt::ObjCStringLiteralClass:
2647 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002648 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002649
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002650 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002651 StrE = ObjCFExpr->getString();
2652 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002653 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002654
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002655 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002656 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2657 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002658 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002659 }
Mike Stump11289f42009-09-09 15:08:12 +00002660
Richard Smith55ce3522012-06-25 20:30:08 +00002661 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002662 }
Mike Stump11289f42009-09-09 15:08:12 +00002663
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002664 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002665 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002666 }
2667}
2668
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002669Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002670 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002671 .Case("scanf", FST_Scanf)
2672 .Cases("printf", "printf0", FST_Printf)
2673 .Cases("NSString", "CFString", FST_NSString)
2674 .Case("strftime", FST_Strftime)
2675 .Case("strfmon", FST_Strfmon)
2676 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00002677 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00002678 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002679 .Default(FST_Unknown);
2680}
2681
Jordan Rose3e0ec582012-07-19 18:10:23 +00002682/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002683/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002684/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002685bool Sema::CheckFormatArguments(const FormatAttr *Format,
2686 ArrayRef<const Expr *> Args,
2687 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002688 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002689 SourceLocation Loc, SourceRange Range,
2690 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002691 FormatStringInfo FSI;
2692 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002693 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002694 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002695 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002696 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002697}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002698
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002699bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002700 bool HasVAListArg, unsigned format_idx,
2701 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002702 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002703 SourceLocation Loc, SourceRange Range,
2704 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002705 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002706 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002707 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002708 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002709 }
Mike Stump11289f42009-09-09 15:08:12 +00002710
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002711 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002712
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002713 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002714 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002715 // Dynamically generated format strings are difficult to
2716 // automatically vet at compile time. Requiring that format strings
2717 // are string literals: (1) permits the checking of format strings by
2718 // the compiler and thereby (2) can practically remove the source of
2719 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002720
Mike Stump11289f42009-09-09 15:08:12 +00002721 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002722 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002723 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002724 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002725 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002726 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2727 format_idx, firstDataArg, Type, CallType,
2728 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002729 if (CT != SLCT_NotALiteral)
2730 // Literal format string found, check done!
2731 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002732
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002733 // Strftime is particular as it always uses a single 'time' argument,
2734 // so it is safe to pass a non-literal string.
2735 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002736 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002737
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002738 // Do not emit diag when the string param is a macro expansion and the
2739 // format is either NSString or CFString. This is a hack to prevent
2740 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2741 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002742 if (Type == FST_NSString &&
2743 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002744 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002745
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002746 // If there are no arguments specified, warn with -Wformat-security, otherwise
2747 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002748 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002749 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002750 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002751 << OrigFormatExpr->getSourceRange();
2752 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002753 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002754 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002755 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002756 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002757}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002758
Ted Kremenekab278de2010-01-28 23:39:18 +00002759namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002760class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2761protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002762 Sema &S;
2763 const StringLiteral *FExpr;
2764 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002765 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002766 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002767 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002768 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002769 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002770 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002771 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002772 bool usesPositionalArgs;
2773 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002774 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002775 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002776 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002777public:
Ted Kremenek02087932010-07-16 02:11:22 +00002778 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002779 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002780 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002781 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002782 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002783 Sema::VariadicCallType callType,
2784 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002785 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002786 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2787 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002788 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002789 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002790 inFunctionCall(inFunctionCall), CallType(callType),
2791 CheckedVarArgs(CheckedVarArgs) {
2792 CoveredArgs.resize(numDataArgs);
2793 CoveredArgs.reset();
2794 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002795
Ted Kremenek019d2242010-01-29 01:50:07 +00002796 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002797
Ted Kremenek02087932010-07-16 02:11:22 +00002798 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002799 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002800
Jordan Rose92303592012-09-08 04:00:03 +00002801 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002802 const analyze_format_string::FormatSpecifier &FS,
2803 const analyze_format_string::ConversionSpecifier &CS,
2804 const char *startSpecifier, unsigned specifierLen,
2805 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002806
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002807 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002808 const analyze_format_string::FormatSpecifier &FS,
2809 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002810
2811 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002812 const analyze_format_string::ConversionSpecifier &CS,
2813 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002814
Craig Toppere14c0f82014-03-12 04:55:44 +00002815 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002816
Craig Toppere14c0f82014-03-12 04:55:44 +00002817 void HandleInvalidPosition(const char *startSpecifier,
2818 unsigned specifierLen,
2819 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002820
Craig Toppere14c0f82014-03-12 04:55:44 +00002821 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002822
Craig Toppere14c0f82014-03-12 04:55:44 +00002823 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002824
Richard Trieu03cf7b72011-10-28 00:41:25 +00002825 template <typename Range>
2826 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2827 const Expr *ArgumentExpr,
2828 PartialDiagnostic PDiag,
2829 SourceLocation StringLoc,
2830 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002831 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002832
Ted Kremenek02087932010-07-16 02:11:22 +00002833protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002834 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2835 const char *startSpec,
2836 unsigned specifierLen,
2837 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002838
2839 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2840 const char *startSpec,
2841 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002842
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002843 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002844 CharSourceRange getSpecifierRange(const char *startSpecifier,
2845 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002846 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002847
Ted Kremenek5739de72010-01-29 01:06:55 +00002848 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002849
2850 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2851 const analyze_format_string::ConversionSpecifier &CS,
2852 const char *startSpecifier, unsigned specifierLen,
2853 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002854
2855 template <typename Range>
2856 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2857 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002858 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002859};
2860}
2861
Ted Kremenek02087932010-07-16 02:11:22 +00002862SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002863 return OrigFormatExpr->getSourceRange();
2864}
2865
Ted Kremenek02087932010-07-16 02:11:22 +00002866CharSourceRange CheckFormatHandler::
2867getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002868 SourceLocation Start = getLocationOfByte(startSpecifier);
2869 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2870
2871 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002872 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002873
2874 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002875}
2876
Ted Kremenek02087932010-07-16 02:11:22 +00002877SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002878 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002879}
2880
Ted Kremenek02087932010-07-16 02:11:22 +00002881void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2882 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002883 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2884 getLocationOfByte(startSpecifier),
2885 /*IsStringLocation*/true,
2886 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002887}
2888
Jordan Rose92303592012-09-08 04:00:03 +00002889void CheckFormatHandler::HandleInvalidLengthModifier(
2890 const analyze_format_string::FormatSpecifier &FS,
2891 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002892 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002893 using namespace analyze_format_string;
2894
2895 const LengthModifier &LM = FS.getLengthModifier();
2896 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2897
2898 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002899 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002900 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002901 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002902 getLocationOfByte(LM.getStart()),
2903 /*IsStringLocation*/true,
2904 getSpecifierRange(startSpecifier, specifierLen));
2905
2906 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2907 << FixedLM->toString()
2908 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2909
2910 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002911 FixItHint Hint;
2912 if (DiagID == diag::warn_format_nonsensical_length)
2913 Hint = FixItHint::CreateRemoval(LMRange);
2914
2915 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002916 getLocationOfByte(LM.getStart()),
2917 /*IsStringLocation*/true,
2918 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002919 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002920 }
2921}
2922
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002923void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002924 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002925 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002926 using namespace analyze_format_string;
2927
2928 const LengthModifier &LM = FS.getLengthModifier();
2929 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2930
2931 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002932 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002933 if (FixedLM) {
2934 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2935 << LM.toString() << 0,
2936 getLocationOfByte(LM.getStart()),
2937 /*IsStringLocation*/true,
2938 getSpecifierRange(startSpecifier, specifierLen));
2939
2940 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2941 << FixedLM->toString()
2942 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2943
2944 } else {
2945 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2946 << LM.toString() << 0,
2947 getLocationOfByte(LM.getStart()),
2948 /*IsStringLocation*/true,
2949 getSpecifierRange(startSpecifier, specifierLen));
2950 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002951}
2952
2953void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2954 const analyze_format_string::ConversionSpecifier &CS,
2955 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002956 using namespace analyze_format_string;
2957
2958 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002959 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002960 if (FixedCS) {
2961 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2962 << CS.toString() << /*conversion specifier*/1,
2963 getLocationOfByte(CS.getStart()),
2964 /*IsStringLocation*/true,
2965 getSpecifierRange(startSpecifier, specifierLen));
2966
2967 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2968 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2969 << FixedCS->toString()
2970 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2971 } else {
2972 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2973 << CS.toString() << /*conversion specifier*/1,
2974 getLocationOfByte(CS.getStart()),
2975 /*IsStringLocation*/true,
2976 getSpecifierRange(startSpecifier, specifierLen));
2977 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002978}
2979
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002980void CheckFormatHandler::HandlePosition(const char *startPos,
2981 unsigned posLen) {
2982 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2983 getLocationOfByte(startPos),
2984 /*IsStringLocation*/true,
2985 getSpecifierRange(startPos, posLen));
2986}
2987
Ted Kremenekd1668192010-02-27 01:41:03 +00002988void
Ted Kremenek02087932010-07-16 02:11:22 +00002989CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2990 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002991 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2992 << (unsigned) p,
2993 getLocationOfByte(startPos), /*IsStringLocation*/true,
2994 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002995}
2996
Ted Kremenek02087932010-07-16 02:11:22 +00002997void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002998 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002999 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3000 getLocationOfByte(startPos),
3001 /*IsStringLocation*/true,
3002 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003003}
3004
Ted Kremenek02087932010-07-16 02:11:22 +00003005void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003006 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003007 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003008 EmitFormatDiagnostic(
3009 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3010 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3011 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003012 }
Ted Kremenek02087932010-07-16 02:11:22 +00003013}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003014
Jordan Rose58bbe422012-07-19 18:10:08 +00003015// Note that this may return NULL if there was an error parsing or building
3016// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003017const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003018 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003019}
3020
3021void CheckFormatHandler::DoneProcessing() {
3022 // Does the number of data arguments exceed the number of
3023 // format conversions in the format string?
3024 if (!HasVAListArg) {
3025 // Find any arguments that weren't covered.
3026 CoveredArgs.flip();
3027 signed notCoveredArg = CoveredArgs.find_first();
3028 if (notCoveredArg >= 0) {
3029 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003030 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3031 SourceLocation Loc = E->getLocStart();
3032 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3033 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3034 Loc, /*IsStringLocation*/false,
3035 getFormatStringRange());
3036 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003037 }
Ted Kremenek02087932010-07-16 02:11:22 +00003038 }
3039 }
3040}
3041
Ted Kremenekce815422010-07-19 21:25:57 +00003042bool
3043CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3044 SourceLocation Loc,
3045 const char *startSpec,
3046 unsigned specifierLen,
3047 const char *csStart,
3048 unsigned csLen) {
3049
3050 bool keepGoing = true;
3051 if (argIndex < NumDataArgs) {
3052 // Consider the argument coverered, even though the specifier doesn't
3053 // make sense.
3054 CoveredArgs.set(argIndex);
3055 }
3056 else {
3057 // If argIndex exceeds the number of data arguments we
3058 // don't issue a warning because that is just a cascade of warnings (and
3059 // they may have intended '%%' anyway). We don't want to continue processing
3060 // the format string after this point, however, as we will like just get
3061 // gibberish when trying to match arguments.
3062 keepGoing = false;
3063 }
3064
Richard Trieu03cf7b72011-10-28 00:41:25 +00003065 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3066 << StringRef(csStart, csLen),
3067 Loc, /*IsStringLocation*/true,
3068 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003069
3070 return keepGoing;
3071}
3072
Richard Trieu03cf7b72011-10-28 00:41:25 +00003073void
3074CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3075 const char *startSpec,
3076 unsigned specifierLen) {
3077 EmitFormatDiagnostic(
3078 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3079 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3080}
3081
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003082bool
3083CheckFormatHandler::CheckNumArgs(
3084 const analyze_format_string::FormatSpecifier &FS,
3085 const analyze_format_string::ConversionSpecifier &CS,
3086 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3087
3088 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003089 PartialDiagnostic PDiag = FS.usesPositionalArg()
3090 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3091 << (argIndex+1) << NumDataArgs)
3092 : S.PDiag(diag::warn_printf_insufficient_data_args);
3093 EmitFormatDiagnostic(
3094 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3095 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003096 return false;
3097 }
3098 return true;
3099}
3100
Richard Trieu03cf7b72011-10-28 00:41:25 +00003101template<typename Range>
3102void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3103 SourceLocation Loc,
3104 bool IsStringLocation,
3105 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003106 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003107 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003108 Loc, IsStringLocation, StringRange, FixIt);
3109}
3110
3111/// \brief If the format string is not within the funcion call, emit a note
3112/// so that the function call and string are in diagnostic messages.
3113///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003114/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003115/// call and only one diagnostic message will be produced. Otherwise, an
3116/// extra note will be emitted pointing to location of the format string.
3117///
3118/// \param ArgumentExpr the expression that is passed as the format string
3119/// argument in the function call. Used for getting locations when two
3120/// diagnostics are emitted.
3121///
3122/// \param PDiag the callee should already have provided any strings for the
3123/// diagnostic message. This function only adds locations and fixits
3124/// to diagnostics.
3125///
3126/// \param Loc primary location for diagnostic. If two diagnostics are
3127/// required, one will be at Loc and a new SourceLocation will be created for
3128/// the other one.
3129///
3130/// \param IsStringLocation if true, Loc points to the format string should be
3131/// used for the note. Otherwise, Loc points to the argument list and will
3132/// be used with PDiag.
3133///
3134/// \param StringRange some or all of the string to highlight. This is
3135/// templated so it can accept either a CharSourceRange or a SourceRange.
3136///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003137/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003138template<typename Range>
3139void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3140 const Expr *ArgumentExpr,
3141 PartialDiagnostic PDiag,
3142 SourceLocation Loc,
3143 bool IsStringLocation,
3144 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003145 ArrayRef<FixItHint> FixIt) {
3146 if (InFunctionCall) {
3147 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3148 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003149 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003150 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003151 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3152 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003153
3154 const Sema::SemaDiagnosticBuilder &Note =
3155 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3156 diag::note_format_string_defined);
3157
3158 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003159 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003160 }
3161}
3162
Ted Kremenek02087932010-07-16 02:11:22 +00003163//===--- CHECK: Printf format string checking ------------------------------===//
3164
3165namespace {
3166class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003167 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003168public:
3169 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3170 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003171 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003172 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003173 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003174 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003175 Sema::VariadicCallType CallType,
3176 llvm::SmallBitVector &CheckedVarArgs)
3177 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3178 numDataArgs, beg, hasVAListArg, Args,
3179 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3180 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003181 {}
3182
Craig Toppere14c0f82014-03-12 04:55:44 +00003183
Ted Kremenek02087932010-07-16 02:11:22 +00003184 bool HandleInvalidPrintfConversionSpecifier(
3185 const analyze_printf::PrintfSpecifier &FS,
3186 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003187 unsigned specifierLen) override;
3188
Ted Kremenek02087932010-07-16 02:11:22 +00003189 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3190 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003191 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003192 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3193 const char *StartSpecifier,
3194 unsigned SpecifierLen,
3195 const Expr *E);
3196
Ted Kremenek02087932010-07-16 02:11:22 +00003197 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3198 const char *startSpecifier, unsigned specifierLen);
3199 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3200 const analyze_printf::OptionalAmount &Amt,
3201 unsigned type,
3202 const char *startSpecifier, unsigned specifierLen);
3203 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3204 const analyze_printf::OptionalFlag &flag,
3205 const char *startSpecifier, unsigned specifierLen);
3206 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3207 const analyze_printf::OptionalFlag &ignoredFlag,
3208 const analyze_printf::OptionalFlag &flag,
3209 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003210 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003211 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003212
Ted Kremenek02087932010-07-16 02:11:22 +00003213};
3214}
3215
3216bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3217 const analyze_printf::PrintfSpecifier &FS,
3218 const char *startSpecifier,
3219 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003220 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003221 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003222
Ted Kremenekce815422010-07-19 21:25:57 +00003223 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3224 getLocationOfByte(CS.getStart()),
3225 startSpecifier, specifierLen,
3226 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003227}
3228
Ted Kremenek02087932010-07-16 02:11:22 +00003229bool CheckPrintfHandler::HandleAmount(
3230 const analyze_format_string::OptionalAmount &Amt,
3231 unsigned k, const char *startSpecifier,
3232 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003233
3234 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003235 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003236 unsigned argIndex = Amt.getArgIndex();
3237 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003238 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3239 << k,
3240 getLocationOfByte(Amt.getStart()),
3241 /*IsStringLocation*/true,
3242 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003243 // Don't do any more checking. We will just emit
3244 // spurious errors.
3245 return false;
3246 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003247
Ted Kremenek5739de72010-01-29 01:06:55 +00003248 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003249 // Although not in conformance with C99, we also allow the argument to be
3250 // an 'unsigned int' as that is a reasonably safe case. GCC also
3251 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003252 CoveredArgs.set(argIndex);
3253 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003254 if (!Arg)
3255 return false;
3256
Ted Kremenek5739de72010-01-29 01:06:55 +00003257 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003258
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003259 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3260 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003261
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003262 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003263 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003264 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003265 << T << Arg->getSourceRange(),
3266 getLocationOfByte(Amt.getStart()),
3267 /*IsStringLocation*/true,
3268 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003269 // Don't do any more checking. We will just emit
3270 // spurious errors.
3271 return false;
3272 }
3273 }
3274 }
3275 return true;
3276}
Ted Kremenek5739de72010-01-29 01:06:55 +00003277
Tom Careb49ec692010-06-17 19:00:27 +00003278void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003279 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003280 const analyze_printf::OptionalAmount &Amt,
3281 unsigned type,
3282 const char *startSpecifier,
3283 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003284 const analyze_printf::PrintfConversionSpecifier &CS =
3285 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003286
Richard Trieu03cf7b72011-10-28 00:41:25 +00003287 FixItHint fixit =
3288 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3289 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3290 Amt.getConstantLength()))
3291 : FixItHint();
3292
3293 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3294 << type << CS.toString(),
3295 getLocationOfByte(Amt.getStart()),
3296 /*IsStringLocation*/true,
3297 getSpecifierRange(startSpecifier, specifierLen),
3298 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003299}
3300
Ted Kremenek02087932010-07-16 02:11:22 +00003301void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003302 const analyze_printf::OptionalFlag &flag,
3303 const char *startSpecifier,
3304 unsigned specifierLen) {
3305 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003306 const analyze_printf::PrintfConversionSpecifier &CS =
3307 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003308 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3309 << flag.toString() << CS.toString(),
3310 getLocationOfByte(flag.getPosition()),
3311 /*IsStringLocation*/true,
3312 getSpecifierRange(startSpecifier, specifierLen),
3313 FixItHint::CreateRemoval(
3314 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003315}
3316
3317void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003318 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003319 const analyze_printf::OptionalFlag &ignoredFlag,
3320 const analyze_printf::OptionalFlag &flag,
3321 const char *startSpecifier,
3322 unsigned specifierLen) {
3323 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003324 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3325 << ignoredFlag.toString() << flag.toString(),
3326 getLocationOfByte(ignoredFlag.getPosition()),
3327 /*IsStringLocation*/true,
3328 getSpecifierRange(startSpecifier, specifierLen),
3329 FixItHint::CreateRemoval(
3330 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003331}
3332
Richard Smith55ce3522012-06-25 20:30:08 +00003333// Determines if the specified is a C++ class or struct containing
3334// a member with the specified name and kind (e.g. a CXXMethodDecl named
3335// "c_str()").
3336template<typename MemberKind>
3337static llvm::SmallPtrSet<MemberKind*, 1>
3338CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3339 const RecordType *RT = Ty->getAs<RecordType>();
3340 llvm::SmallPtrSet<MemberKind*, 1> Results;
3341
3342 if (!RT)
3343 return Results;
3344 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003345 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003346 return Results;
3347
Alp Tokerb6cc5922014-05-03 03:45:55 +00003348 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003349 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003350 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003351
3352 // We just need to include all members of the right kind turned up by the
3353 // filter, at this point.
3354 if (S.LookupQualifiedName(R, RT->getDecl()))
3355 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3356 NamedDecl *decl = (*I)->getUnderlyingDecl();
3357 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3358 Results.insert(FK);
3359 }
3360 return Results;
3361}
3362
Richard Smith2868a732014-02-28 01:36:39 +00003363/// Check if we could call '.c_str()' on an object.
3364///
3365/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3366/// allow the call, or if it would be ambiguous).
3367bool Sema::hasCStrMethod(const Expr *E) {
3368 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3369 MethodSet Results =
3370 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3371 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3372 MI != ME; ++MI)
3373 if ((*MI)->getMinRequiredArguments() == 0)
3374 return true;
3375 return false;
3376}
3377
Richard Smith55ce3522012-06-25 20:30:08 +00003378// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003379// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003380// Returns true when a c_str() conversion method is found.
3381bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003382 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003383 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3384
3385 MethodSet Results =
3386 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3387
3388 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3389 MI != ME; ++MI) {
3390 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003391 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003392 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003393 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003394 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003395 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3396 << "c_str()"
3397 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3398 return true;
3399 }
3400 }
3401
3402 return false;
3403}
3404
Ted Kremenekab278de2010-01-28 23:39:18 +00003405bool
Ted Kremenek02087932010-07-16 02:11:22 +00003406CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003407 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003408 const char *startSpecifier,
3409 unsigned specifierLen) {
3410
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003411 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003412 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003413 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003414
Ted Kremenek6cd69422010-07-19 22:01:06 +00003415 if (FS.consumesDataArgument()) {
3416 if (atFirstArg) {
3417 atFirstArg = false;
3418 usesPositionalArgs = FS.usesPositionalArg();
3419 }
3420 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003421 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3422 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003423 return false;
3424 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003425 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003426
Ted Kremenekd1668192010-02-27 01:41:03 +00003427 // First check if the field width, precision, and conversion specifier
3428 // have matching data arguments.
3429 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3430 startSpecifier, specifierLen)) {
3431 return false;
3432 }
3433
3434 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3435 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003436 return false;
3437 }
3438
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003439 if (!CS.consumesDataArgument()) {
3440 // FIXME: Technically specifying a precision or field width here
3441 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003442 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003443 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003444
Ted Kremenek4a49d982010-02-26 19:18:41 +00003445 // Consume the argument.
3446 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003447 if (argIndex < NumDataArgs) {
3448 // The check to see if the argIndex is valid will come later.
3449 // We set the bit here because we may exit early from this
3450 // function if we encounter some other error.
3451 CoveredArgs.set(argIndex);
3452 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003453
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003454 // FreeBSD kernel extensions.
3455 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3456 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3457 // We need at least two arguments.
3458 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3459 return false;
3460
3461 // Claim the second argument.
3462 CoveredArgs.set(argIndex + 1);
3463
3464 // Type check the first argument (int for %b, pointer for %D)
3465 const Expr *Ex = getDataArg(argIndex);
3466 const analyze_printf::ArgType &AT =
3467 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3468 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3469 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3470 EmitFormatDiagnostic(
3471 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3472 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3473 << false << Ex->getSourceRange(),
3474 Ex->getLocStart(), /*IsStringLocation*/false,
3475 getSpecifierRange(startSpecifier, specifierLen));
3476
3477 // Type check the second argument (char * for both %b and %D)
3478 Ex = getDataArg(argIndex + 1);
3479 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3480 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3481 EmitFormatDiagnostic(
3482 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3483 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3484 << false << Ex->getSourceRange(),
3485 Ex->getLocStart(), /*IsStringLocation*/false,
3486 getSpecifierRange(startSpecifier, specifierLen));
3487
3488 return true;
3489 }
3490
Ted Kremenek4a49d982010-02-26 19:18:41 +00003491 // Check for using an Objective-C specific conversion specifier
3492 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003493 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003494 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3495 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003496 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003497
Tom Careb49ec692010-06-17 19:00:27 +00003498 // Check for invalid use of field width
3499 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003500 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003501 startSpecifier, specifierLen);
3502 }
3503
3504 // Check for invalid use of precision
3505 if (!FS.hasValidPrecision()) {
3506 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3507 startSpecifier, specifierLen);
3508 }
3509
3510 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003511 if (!FS.hasValidThousandsGroupingPrefix())
3512 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003513 if (!FS.hasValidLeadingZeros())
3514 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3515 if (!FS.hasValidPlusPrefix())
3516 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003517 if (!FS.hasValidSpacePrefix())
3518 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003519 if (!FS.hasValidAlternativeForm())
3520 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3521 if (!FS.hasValidLeftJustified())
3522 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3523
3524 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003525 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3526 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3527 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003528 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3529 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3530 startSpecifier, specifierLen);
3531
3532 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003533 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003534 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3535 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003536 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003537 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003538 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003539 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3540 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003541
Jordan Rose92303592012-09-08 04:00:03 +00003542 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3543 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3544
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003545 // The remaining checks depend on the data arguments.
3546 if (HasVAListArg)
3547 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003548
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003549 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003550 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003551
Jordan Rose58bbe422012-07-19 18:10:08 +00003552 const Expr *Arg = getDataArg(argIndex);
3553 if (!Arg)
3554 return true;
3555
3556 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003557}
3558
Jordan Roseaee34382012-09-05 22:56:26 +00003559static bool requiresParensToAddCast(const Expr *E) {
3560 // FIXME: We should have a general way to reason about operator
3561 // precedence and whether parens are actually needed here.
3562 // Take care of a few common cases where they aren't.
3563 const Expr *Inside = E->IgnoreImpCasts();
3564 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3565 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3566
3567 switch (Inside->getStmtClass()) {
3568 case Stmt::ArraySubscriptExprClass:
3569 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003570 case Stmt::CharacterLiteralClass:
3571 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003572 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003573 case Stmt::FloatingLiteralClass:
3574 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003575 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003576 case Stmt::ObjCArrayLiteralClass:
3577 case Stmt::ObjCBoolLiteralExprClass:
3578 case Stmt::ObjCBoxedExprClass:
3579 case Stmt::ObjCDictionaryLiteralClass:
3580 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003581 case Stmt::ObjCIvarRefExprClass:
3582 case Stmt::ObjCMessageExprClass:
3583 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003584 case Stmt::ObjCStringLiteralClass:
3585 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003586 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003587 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003588 case Stmt::UnaryOperatorClass:
3589 return false;
3590 default:
3591 return true;
3592 }
3593}
3594
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003595static std::pair<QualType, StringRef>
3596shouldNotPrintDirectly(const ASTContext &Context,
3597 QualType IntendedTy,
3598 const Expr *E) {
3599 // Use a 'while' to peel off layers of typedefs.
3600 QualType TyTy = IntendedTy;
3601 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3602 StringRef Name = UserTy->getDecl()->getName();
3603 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3604 .Case("NSInteger", Context.LongTy)
3605 .Case("NSUInteger", Context.UnsignedLongTy)
3606 .Case("SInt32", Context.IntTy)
3607 .Case("UInt32", Context.UnsignedIntTy)
3608 .Default(QualType());
3609
3610 if (!CastTy.isNull())
3611 return std::make_pair(CastTy, Name);
3612
3613 TyTy = UserTy->desugar();
3614 }
3615
3616 // Strip parens if necessary.
3617 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3618 return shouldNotPrintDirectly(Context,
3619 PE->getSubExpr()->getType(),
3620 PE->getSubExpr());
3621
3622 // If this is a conditional expression, then its result type is constructed
3623 // via usual arithmetic conversions and thus there might be no necessary
3624 // typedef sugar there. Recurse to operands to check for NSInteger &
3625 // Co. usage condition.
3626 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3627 QualType TrueTy, FalseTy;
3628 StringRef TrueName, FalseName;
3629
3630 std::tie(TrueTy, TrueName) =
3631 shouldNotPrintDirectly(Context,
3632 CO->getTrueExpr()->getType(),
3633 CO->getTrueExpr());
3634 std::tie(FalseTy, FalseName) =
3635 shouldNotPrintDirectly(Context,
3636 CO->getFalseExpr()->getType(),
3637 CO->getFalseExpr());
3638
3639 if (TrueTy == FalseTy)
3640 return std::make_pair(TrueTy, TrueName);
3641 else if (TrueTy.isNull())
3642 return std::make_pair(FalseTy, FalseName);
3643 else if (FalseTy.isNull())
3644 return std::make_pair(TrueTy, TrueName);
3645 }
3646
3647 return std::make_pair(QualType(), StringRef());
3648}
3649
Richard Smith55ce3522012-06-25 20:30:08 +00003650bool
3651CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3652 const char *StartSpecifier,
3653 unsigned SpecifierLen,
3654 const Expr *E) {
3655 using namespace analyze_format_string;
3656 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003657 // Now type check the data expression that matches the
3658 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003659 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3660 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003661 if (!AT.isValid())
3662 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003663
Jordan Rose598ec092012-12-05 18:44:40 +00003664 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003665 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3666 ExprTy = TET->getUnderlyingExpr()->getType();
3667 }
3668
Seth Cantrellb4802962015-03-04 03:12:10 +00003669 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
3670
3671 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00003672 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00003673 }
Jordan Rose98709982012-06-04 22:48:57 +00003674
Jordan Rose22b74712012-09-05 22:56:19 +00003675 // Look through argument promotions for our error message's reported type.
3676 // This includes the integral and floating promotions, but excludes array
3677 // and function pointer decay; seeing that an argument intended to be a
3678 // string has type 'char [6]' is probably more confusing than 'char *'.
3679 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3680 if (ICE->getCastKind() == CK_IntegralCast ||
3681 ICE->getCastKind() == CK_FloatingCast) {
3682 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003683 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003684
3685 // Check if we didn't match because of an implicit cast from a 'char'
3686 // or 'short' to an 'int'. This is done because printf is a varargs
3687 // function.
3688 if (ICE->getType() == S.Context.IntTy ||
3689 ICE->getType() == S.Context.UnsignedIntTy) {
3690 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003691 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003692 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003693 }
Jordan Rose98709982012-06-04 22:48:57 +00003694 }
Jordan Rose598ec092012-12-05 18:44:40 +00003695 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3696 // Special case for 'a', which has type 'int' in C.
3697 // Note, however, that we do /not/ want to treat multibyte constants like
3698 // 'MooV' as characters! This form is deprecated but still exists.
3699 if (ExprTy == S.Context.IntTy)
3700 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3701 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003702 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003703
Jordan Rosebc53ed12014-05-31 04:12:14 +00003704 // Look through enums to their underlying type.
3705 bool IsEnum = false;
3706 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3707 ExprTy = EnumTy->getDecl()->getIntegerType();
3708 IsEnum = true;
3709 }
3710
Jordan Rose0e5badd2012-12-05 18:44:49 +00003711 // %C in an Objective-C context prints a unichar, not a wchar_t.
3712 // If the argument is an integer of some kind, believe the %C and suggest
3713 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003714 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003715 if (ObjCContext &&
3716 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3717 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3718 !ExprTy->isCharType()) {
3719 // 'unichar' is defined as a typedef of unsigned short, but we should
3720 // prefer using the typedef if it is visible.
3721 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003722
3723 // While we are here, check if the value is an IntegerLiteral that happens
3724 // to be within the valid range.
3725 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3726 const llvm::APInt &V = IL->getValue();
3727 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3728 return true;
3729 }
3730
Jordan Rose0e5badd2012-12-05 18:44:49 +00003731 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3732 Sema::LookupOrdinaryName);
3733 if (S.LookupName(Result, S.getCurScope())) {
3734 NamedDecl *ND = Result.getFoundDecl();
3735 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3736 if (TD->getUnderlyingType() == IntendedTy)
3737 IntendedTy = S.Context.getTypedefType(TD);
3738 }
3739 }
3740 }
3741
3742 // Special-case some of Darwin's platform-independence types by suggesting
3743 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003744 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00003745 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003746 QualType CastTy;
3747 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3748 if (!CastTy.isNull()) {
3749 IntendedTy = CastTy;
3750 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00003751 }
3752 }
3753
Jordan Rose22b74712012-09-05 22:56:19 +00003754 // We may be able to offer a FixItHint if it is a supported type.
3755 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003756 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003757 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003758
Jordan Rose22b74712012-09-05 22:56:19 +00003759 if (success) {
3760 // Get the fix string from the fixed format specifier
3761 SmallString<16> buf;
3762 llvm::raw_svector_ostream os(buf);
3763 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003764
Jordan Roseaee34382012-09-05 22:56:26 +00003765 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3766
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003767 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00003768 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3769 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
3770 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3771 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00003772 // In this case, the specifier is wrong and should be changed to match
3773 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00003774 EmitFormatDiagnostic(S.PDiag(diag)
3775 << AT.getRepresentativeTypeName(S.Context)
3776 << IntendedTy << IsEnum << E->getSourceRange(),
3777 E->getLocStart(),
3778 /*IsStringLocation*/ false, SpecRange,
3779 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00003780
3781 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003782 // The canonical type for formatting this value is different from the
3783 // actual type of the expression. (This occurs, for example, with Darwin's
3784 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3785 // should be printed as 'long' for 64-bit compatibility.)
3786 // Rather than emitting a normal format/argument mismatch, we want to
3787 // add a cast to the recommended type (and correct the format string
3788 // if necessary).
3789 SmallString<16> CastBuf;
3790 llvm::raw_svector_ostream CastFix(CastBuf);
3791 CastFix << "(";
3792 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3793 CastFix << ")";
3794
3795 SmallVector<FixItHint,4> Hints;
3796 if (!AT.matchesType(S.Context, IntendedTy))
3797 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3798
3799 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3800 // If there's already a cast present, just replace it.
3801 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3802 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3803
3804 } else if (!requiresParensToAddCast(E)) {
3805 // If the expression has high enough precedence,
3806 // just write the C-style cast.
3807 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3808 CastFix.str()));
3809 } else {
3810 // Otherwise, add parens around the expression as well as the cast.
3811 CastFix << "(";
3812 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3813 CastFix.str()));
3814
Alp Tokerb6cc5922014-05-03 03:45:55 +00003815 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003816 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3817 }
3818
Jordan Rose0e5badd2012-12-05 18:44:49 +00003819 if (ShouldNotPrintDirectly) {
3820 // The expression has a type that should not be printed directly.
3821 // We extract the name from the typedef because we don't want to show
3822 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003823 StringRef Name;
3824 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3825 Name = TypedefTy->getDecl()->getName();
3826 else
3827 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003828 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003829 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003830 << E->getSourceRange(),
3831 E->getLocStart(), /*IsStringLocation=*/false,
3832 SpecRange, Hints);
3833 } else {
3834 // In this case, the expression could be printed using a different
3835 // specifier, but we've decided that the specifier is probably correct
3836 // and we should cast instead. Just use the normal warning message.
3837 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003838 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3839 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003840 << E->getSourceRange(),
3841 E->getLocStart(), /*IsStringLocation*/false,
3842 SpecRange, Hints);
3843 }
Jordan Roseaee34382012-09-05 22:56:26 +00003844 }
Jordan Rose22b74712012-09-05 22:56:19 +00003845 } else {
3846 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3847 SpecifierLen);
3848 // Since the warning for passing non-POD types to variadic functions
3849 // was deferred until now, we emit a warning for non-POD
3850 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003851 switch (S.isValidVarArgType(ExprTy)) {
3852 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00003853 case Sema::VAK_ValidInCXX11: {
3854 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3855 if (match == analyze_printf::ArgType::NoMatchPedantic) {
3856 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3857 }
Richard Smithd7293d72013-08-05 18:49:43 +00003858
Seth Cantrellb4802962015-03-04 03:12:10 +00003859 EmitFormatDiagnostic(
3860 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
3861 << IsEnum << CSR << E->getSourceRange(),
3862 E->getLocStart(), /*IsStringLocation*/ false, CSR);
3863 break;
3864 }
Richard Smithd7293d72013-08-05 18:49:43 +00003865 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00003866 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00003867 EmitFormatDiagnostic(
3868 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003869 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003870 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003871 << CallType
3872 << AT.getRepresentativeTypeName(S.Context)
3873 << CSR
3874 << E->getSourceRange(),
3875 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003876 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003877 break;
3878
3879 case Sema::VAK_Invalid:
3880 if (ExprTy->isObjCObjectType())
3881 EmitFormatDiagnostic(
3882 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3883 << S.getLangOpts().CPlusPlus11
3884 << ExprTy
3885 << CallType
3886 << AT.getRepresentativeTypeName(S.Context)
3887 << CSR
3888 << E->getSourceRange(),
3889 E->getLocStart(), /*IsStringLocation*/false, CSR);
3890 else
3891 // FIXME: If this is an initializer list, suggest removing the braces
3892 // or inserting a cast to the target type.
3893 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3894 << isa<InitListExpr>(E) << ExprTy << CallType
3895 << AT.getRepresentativeTypeName(S.Context)
3896 << E->getSourceRange();
3897 break;
3898 }
3899
3900 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3901 "format string specifier index out of range");
3902 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003903 }
3904
Ted Kremenekab278de2010-01-28 23:39:18 +00003905 return true;
3906}
3907
Ted Kremenek02087932010-07-16 02:11:22 +00003908//===--- CHECK: Scanf format string checking ------------------------------===//
3909
3910namespace {
3911class CheckScanfHandler : public CheckFormatHandler {
3912public:
3913 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3914 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003915 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003916 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003917 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003918 Sema::VariadicCallType CallType,
3919 llvm::SmallBitVector &CheckedVarArgs)
3920 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3921 numDataArgs, beg, hasVAListArg,
3922 Args, formatIdx, inFunctionCall, CallType,
3923 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003924 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003925
3926 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3927 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003928 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003929
3930 bool HandleInvalidScanfConversionSpecifier(
3931 const analyze_scanf::ScanfSpecifier &FS,
3932 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003933 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003934
Craig Toppere14c0f82014-03-12 04:55:44 +00003935 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003936};
Ted Kremenek019d2242010-01-29 01:50:07 +00003937}
Ted Kremenekab278de2010-01-28 23:39:18 +00003938
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003939void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3940 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003941 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3942 getLocationOfByte(end), /*IsStringLocation*/true,
3943 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003944}
3945
Ted Kremenekce815422010-07-19 21:25:57 +00003946bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3947 const analyze_scanf::ScanfSpecifier &FS,
3948 const char *startSpecifier,
3949 unsigned specifierLen) {
3950
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003951 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003952 FS.getConversionSpecifier();
3953
3954 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3955 getLocationOfByte(CS.getStart()),
3956 startSpecifier, specifierLen,
3957 CS.getStart(), CS.getLength());
3958}
3959
Ted Kremenek02087932010-07-16 02:11:22 +00003960bool CheckScanfHandler::HandleScanfSpecifier(
3961 const analyze_scanf::ScanfSpecifier &FS,
3962 const char *startSpecifier,
3963 unsigned specifierLen) {
3964
3965 using namespace analyze_scanf;
3966 using namespace analyze_format_string;
3967
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003968 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003969
Ted Kremenek6cd69422010-07-19 22:01:06 +00003970 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3971 // be used to decide if we are using positional arguments consistently.
3972 if (FS.consumesDataArgument()) {
3973 if (atFirstArg) {
3974 atFirstArg = false;
3975 usesPositionalArgs = FS.usesPositionalArg();
3976 }
3977 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003978 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3979 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003980 return false;
3981 }
Ted Kremenek02087932010-07-16 02:11:22 +00003982 }
3983
3984 // Check if the field with is non-zero.
3985 const OptionalAmount &Amt = FS.getFieldWidth();
3986 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3987 if (Amt.getConstantAmount() == 0) {
3988 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3989 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003990 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3991 getLocationOfByte(Amt.getStart()),
3992 /*IsStringLocation*/true, R,
3993 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003994 }
3995 }
Seth Cantrellb4802962015-03-04 03:12:10 +00003996
Ted Kremenek02087932010-07-16 02:11:22 +00003997 if (!FS.consumesDataArgument()) {
3998 // FIXME: Technically specifying a precision or field width here
3999 // makes no sense. Worth issuing a warning at some point.
4000 return true;
4001 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004002
Ted Kremenek02087932010-07-16 02:11:22 +00004003 // Consume the argument.
4004 unsigned argIndex = FS.getArgIndex();
4005 if (argIndex < NumDataArgs) {
4006 // The check to see if the argIndex is valid will come later.
4007 // We set the bit here because we may exit early from this
4008 // function if we encounter some other error.
4009 CoveredArgs.set(argIndex);
4010 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004011
Ted Kremenek4407ea42010-07-20 20:04:47 +00004012 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004013 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004014 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4015 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004016 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004017 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004018 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004019 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4020 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004021
Jordan Rose92303592012-09-08 04:00:03 +00004022 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4023 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4024
Ted Kremenek02087932010-07-16 02:11:22 +00004025 // The remaining checks depend on the data arguments.
4026 if (HasVAListArg)
4027 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004028
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004029 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004030 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004031
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004032 // Check that the argument type matches the format specifier.
4033 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004034 if (!Ex)
4035 return true;
4036
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004037 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004038
4039 if (!AT.isValid()) {
4040 return true;
4041 }
4042
Seth Cantrellb4802962015-03-04 03:12:10 +00004043 analyze_format_string::ArgType::MatchKind match =
4044 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004045 if (match == analyze_format_string::ArgType::Match) {
4046 return true;
4047 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004048
Seth Cantrell79340072015-03-04 05:58:08 +00004049 ScanfSpecifier fixedFS = FS;
4050 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4051 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004052
Seth Cantrell79340072015-03-04 05:58:08 +00004053 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4054 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4055 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4056 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004057
Seth Cantrell79340072015-03-04 05:58:08 +00004058 if (success) {
4059 // Get the fix string from the fixed format specifier.
4060 SmallString<128> buf;
4061 llvm::raw_svector_ostream os(buf);
4062 fixedFS.toString(os);
4063
4064 EmitFormatDiagnostic(
4065 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4066 << Ex->getType() << false << Ex->getSourceRange(),
4067 Ex->getLocStart(),
4068 /*IsStringLocation*/ false,
4069 getSpecifierRange(startSpecifier, specifierLen),
4070 FixItHint::CreateReplacement(
4071 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4072 } else {
4073 EmitFormatDiagnostic(S.PDiag(diag)
4074 << AT.getRepresentativeTypeName(S.Context)
4075 << Ex->getType() << false << Ex->getSourceRange(),
4076 Ex->getLocStart(),
4077 /*IsStringLocation*/ false,
4078 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004079 }
4080
Ted Kremenek02087932010-07-16 02:11:22 +00004081 return true;
4082}
4083
4084void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004085 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004086 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004087 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004088 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004089 bool inFunctionCall, VariadicCallType CallType,
4090 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004091
Ted Kremenekab278de2010-01-28 23:39:18 +00004092 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004093 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004094 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004095 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004096 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4097 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004098 return;
4099 }
Ted Kremenek02087932010-07-16 02:11:22 +00004100
Ted Kremenekab278de2010-01-28 23:39:18 +00004101 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004102 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004103 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004104 // Account for cases where the string literal is truncated in a declaration.
4105 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4106 assert(T && "String literal not of constant array type!");
4107 size_t TypeSize = T->getSize().getZExtValue();
4108 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004109 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004110
4111 // Emit a warning if the string literal is truncated and does not contain an
4112 // embedded null character.
4113 if (TypeSize <= StrRef.size() &&
4114 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4115 CheckFormatHandler::EmitFormatDiagnostic(
4116 *this, inFunctionCall, Args[format_idx],
4117 PDiag(diag::warn_printf_format_string_not_null_terminated),
4118 FExpr->getLocStart(),
4119 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4120 return;
4121 }
4122
Ted Kremenekab278de2010-01-28 23:39:18 +00004123 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004124 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004125 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004126 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004127 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4128 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004129 return;
4130 }
Ted Kremenek02087932010-07-16 02:11:22 +00004131
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004132 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004133 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004134 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004135 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004136 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004137 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004138
Hans Wennborg23926bd2011-12-15 10:25:47 +00004139 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004140 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004141 Context.getTargetInfo(),
4142 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004143 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004144 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004145 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004146 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004147 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004148
Hans Wennborg23926bd2011-12-15 10:25:47 +00004149 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004150 getLangOpts(),
4151 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004152 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004153 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004154}
4155
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004156bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4157 // Str - The format string. NOTE: this is NOT null-terminated!
4158 StringRef StrRef = FExpr->getString();
4159 const char *Str = StrRef.data();
4160 // Account for cases where the string literal is truncated in a declaration.
4161 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4162 assert(T && "String literal not of constant array type!");
4163 size_t TypeSize = T->getSize().getZExtValue();
4164 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4165 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4166 getLangOpts(),
4167 Context.getTargetInfo());
4168}
4169
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004170//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4171
4172// Returns the related absolute value function that is larger, of 0 if one
4173// does not exist.
4174static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4175 switch (AbsFunction) {
4176 default:
4177 return 0;
4178
4179 case Builtin::BI__builtin_abs:
4180 return Builtin::BI__builtin_labs;
4181 case Builtin::BI__builtin_labs:
4182 return Builtin::BI__builtin_llabs;
4183 case Builtin::BI__builtin_llabs:
4184 return 0;
4185
4186 case Builtin::BI__builtin_fabsf:
4187 return Builtin::BI__builtin_fabs;
4188 case Builtin::BI__builtin_fabs:
4189 return Builtin::BI__builtin_fabsl;
4190 case Builtin::BI__builtin_fabsl:
4191 return 0;
4192
4193 case Builtin::BI__builtin_cabsf:
4194 return Builtin::BI__builtin_cabs;
4195 case Builtin::BI__builtin_cabs:
4196 return Builtin::BI__builtin_cabsl;
4197 case Builtin::BI__builtin_cabsl:
4198 return 0;
4199
4200 case Builtin::BIabs:
4201 return Builtin::BIlabs;
4202 case Builtin::BIlabs:
4203 return Builtin::BIllabs;
4204 case Builtin::BIllabs:
4205 return 0;
4206
4207 case Builtin::BIfabsf:
4208 return Builtin::BIfabs;
4209 case Builtin::BIfabs:
4210 return Builtin::BIfabsl;
4211 case Builtin::BIfabsl:
4212 return 0;
4213
4214 case Builtin::BIcabsf:
4215 return Builtin::BIcabs;
4216 case Builtin::BIcabs:
4217 return Builtin::BIcabsl;
4218 case Builtin::BIcabsl:
4219 return 0;
4220 }
4221}
4222
4223// Returns the argument type of the absolute value function.
4224static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4225 unsigned AbsType) {
4226 if (AbsType == 0)
4227 return QualType();
4228
4229 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4230 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4231 if (Error != ASTContext::GE_None)
4232 return QualType();
4233
4234 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4235 if (!FT)
4236 return QualType();
4237
4238 if (FT->getNumParams() != 1)
4239 return QualType();
4240
4241 return FT->getParamType(0);
4242}
4243
4244// Returns the best absolute value function, or zero, based on type and
4245// current absolute value function.
4246static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4247 unsigned AbsFunctionKind) {
4248 unsigned BestKind = 0;
4249 uint64_t ArgSize = Context.getTypeSize(ArgType);
4250 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4251 Kind = getLargerAbsoluteValueFunction(Kind)) {
4252 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4253 if (Context.getTypeSize(ParamType) >= ArgSize) {
4254 if (BestKind == 0)
4255 BestKind = Kind;
4256 else if (Context.hasSameType(ParamType, ArgType)) {
4257 BestKind = Kind;
4258 break;
4259 }
4260 }
4261 }
4262 return BestKind;
4263}
4264
4265enum AbsoluteValueKind {
4266 AVK_Integer,
4267 AVK_Floating,
4268 AVK_Complex
4269};
4270
4271static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4272 if (T->isIntegralOrEnumerationType())
4273 return AVK_Integer;
4274 if (T->isRealFloatingType())
4275 return AVK_Floating;
4276 if (T->isAnyComplexType())
4277 return AVK_Complex;
4278
4279 llvm_unreachable("Type not integer, floating, or complex");
4280}
4281
4282// Changes the absolute value function to a different type. Preserves whether
4283// the function is a builtin.
4284static unsigned changeAbsFunction(unsigned AbsKind,
4285 AbsoluteValueKind ValueKind) {
4286 switch (ValueKind) {
4287 case AVK_Integer:
4288 switch (AbsKind) {
4289 default:
4290 return 0;
4291 case Builtin::BI__builtin_fabsf:
4292 case Builtin::BI__builtin_fabs:
4293 case Builtin::BI__builtin_fabsl:
4294 case Builtin::BI__builtin_cabsf:
4295 case Builtin::BI__builtin_cabs:
4296 case Builtin::BI__builtin_cabsl:
4297 return Builtin::BI__builtin_abs;
4298 case Builtin::BIfabsf:
4299 case Builtin::BIfabs:
4300 case Builtin::BIfabsl:
4301 case Builtin::BIcabsf:
4302 case Builtin::BIcabs:
4303 case Builtin::BIcabsl:
4304 return Builtin::BIabs;
4305 }
4306 case AVK_Floating:
4307 switch (AbsKind) {
4308 default:
4309 return 0;
4310 case Builtin::BI__builtin_abs:
4311 case Builtin::BI__builtin_labs:
4312 case Builtin::BI__builtin_llabs:
4313 case Builtin::BI__builtin_cabsf:
4314 case Builtin::BI__builtin_cabs:
4315 case Builtin::BI__builtin_cabsl:
4316 return Builtin::BI__builtin_fabsf;
4317 case Builtin::BIabs:
4318 case Builtin::BIlabs:
4319 case Builtin::BIllabs:
4320 case Builtin::BIcabsf:
4321 case Builtin::BIcabs:
4322 case Builtin::BIcabsl:
4323 return Builtin::BIfabsf;
4324 }
4325 case AVK_Complex:
4326 switch (AbsKind) {
4327 default:
4328 return 0;
4329 case Builtin::BI__builtin_abs:
4330 case Builtin::BI__builtin_labs:
4331 case Builtin::BI__builtin_llabs:
4332 case Builtin::BI__builtin_fabsf:
4333 case Builtin::BI__builtin_fabs:
4334 case Builtin::BI__builtin_fabsl:
4335 return Builtin::BI__builtin_cabsf;
4336 case Builtin::BIabs:
4337 case Builtin::BIlabs:
4338 case Builtin::BIllabs:
4339 case Builtin::BIfabsf:
4340 case Builtin::BIfabs:
4341 case Builtin::BIfabsl:
4342 return Builtin::BIcabsf;
4343 }
4344 }
4345 llvm_unreachable("Unable to convert function");
4346}
4347
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004348static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004349 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4350 if (!FnInfo)
4351 return 0;
4352
4353 switch (FDecl->getBuiltinID()) {
4354 default:
4355 return 0;
4356 case Builtin::BI__builtin_abs:
4357 case Builtin::BI__builtin_fabs:
4358 case Builtin::BI__builtin_fabsf:
4359 case Builtin::BI__builtin_fabsl:
4360 case Builtin::BI__builtin_labs:
4361 case Builtin::BI__builtin_llabs:
4362 case Builtin::BI__builtin_cabs:
4363 case Builtin::BI__builtin_cabsf:
4364 case Builtin::BI__builtin_cabsl:
4365 case Builtin::BIabs:
4366 case Builtin::BIlabs:
4367 case Builtin::BIllabs:
4368 case Builtin::BIfabs:
4369 case Builtin::BIfabsf:
4370 case Builtin::BIfabsl:
4371 case Builtin::BIcabs:
4372 case Builtin::BIcabsf:
4373 case Builtin::BIcabsl:
4374 return FDecl->getBuiltinID();
4375 }
4376 llvm_unreachable("Unknown Builtin type");
4377}
4378
4379// If the replacement is valid, emit a note with replacement function.
4380// Additionally, suggest including the proper header if not already included.
4381static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004382 unsigned AbsKind, QualType ArgType) {
4383 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004384 const char *HeaderName = nullptr;
4385 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004386 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4387 FunctionName = "std::abs";
4388 if (ArgType->isIntegralOrEnumerationType()) {
4389 HeaderName = "cstdlib";
4390 } else if (ArgType->isRealFloatingType()) {
4391 HeaderName = "cmath";
4392 } else {
4393 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004394 }
Richard Trieubeffb832014-04-15 23:47:53 +00004395
4396 // Lookup all std::abs
4397 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004398 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004399 R.suppressDiagnostics();
4400 S.LookupQualifiedName(R, Std);
4401
4402 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004403 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004404 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4405 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4406 } else {
4407 FDecl = dyn_cast<FunctionDecl>(I);
4408 }
4409 if (!FDecl)
4410 continue;
4411
4412 // Found std::abs(), check that they are the right ones.
4413 if (FDecl->getNumParams() != 1)
4414 continue;
4415
4416 // Check that the parameter type can handle the argument.
4417 QualType ParamType = FDecl->getParamDecl(0)->getType();
4418 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4419 S.Context.getTypeSize(ArgType) <=
4420 S.Context.getTypeSize(ParamType)) {
4421 // Found a function, don't need the header hint.
4422 EmitHeaderHint = false;
4423 break;
4424 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004425 }
Richard Trieubeffb832014-04-15 23:47:53 +00004426 }
4427 } else {
4428 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4429 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4430
4431 if (HeaderName) {
4432 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4433 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4434 R.suppressDiagnostics();
4435 S.LookupName(R, S.getCurScope());
4436
4437 if (R.isSingleResult()) {
4438 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4439 if (FD && FD->getBuiltinID() == AbsKind) {
4440 EmitHeaderHint = false;
4441 } else {
4442 return;
4443 }
4444 } else if (!R.empty()) {
4445 return;
4446 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004447 }
4448 }
4449
4450 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004451 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004452
Richard Trieubeffb832014-04-15 23:47:53 +00004453 if (!HeaderName)
4454 return;
4455
4456 if (!EmitHeaderHint)
4457 return;
4458
Alp Toker5d96e0a2014-07-11 20:53:51 +00004459 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4460 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004461}
4462
4463static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4464 if (!FDecl)
4465 return false;
4466
4467 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4468 return false;
4469
4470 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4471
4472 while (ND && ND->isInlineNamespace()) {
4473 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004474 }
Richard Trieubeffb832014-04-15 23:47:53 +00004475
4476 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4477 return false;
4478
4479 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4480 return false;
4481
4482 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004483}
4484
4485// Warn when using the wrong abs() function.
4486void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4487 const FunctionDecl *FDecl,
4488 IdentifierInfo *FnInfo) {
4489 if (Call->getNumArgs() != 1)
4490 return;
4491
4492 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004493 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4494 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004495 return;
4496
4497 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4498 QualType ParamType = Call->getArg(0)->getType();
4499
Alp Toker5d96e0a2014-07-11 20:53:51 +00004500 // Unsigned types cannot be negative. Suggest removing the absolute value
4501 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004502 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004503 const char *FunctionName =
4504 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004505 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4506 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004507 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004508 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4509 return;
4510 }
4511
Richard Trieubeffb832014-04-15 23:47:53 +00004512 // std::abs has overloads which prevent most of the absolute value problems
4513 // from occurring.
4514 if (IsStdAbs)
4515 return;
4516
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004517 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4518 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4519
4520 // The argument and parameter are the same kind. Check if they are the right
4521 // size.
4522 if (ArgValueKind == ParamValueKind) {
4523 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4524 return;
4525
4526 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4527 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4528 << FDecl << ArgType << ParamType;
4529
4530 if (NewAbsKind == 0)
4531 return;
4532
4533 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004534 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004535 return;
4536 }
4537
4538 // ArgValueKind != ParamValueKind
4539 // The wrong type of absolute value function was used. Attempt to find the
4540 // proper one.
4541 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4542 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4543 if (NewAbsKind == 0)
4544 return;
4545
4546 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4547 << FDecl << ParamValueKind << ArgValueKind;
4548
4549 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004550 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004551 return;
4552}
4553
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004554//===--- CHECK: Standard memory functions ---------------------------------===//
4555
Nico Weber0e6daef2013-12-26 23:38:39 +00004556/// \brief Takes the expression passed to the size_t parameter of functions
4557/// such as memcmp, strncat, etc and warns if it's a comparison.
4558///
4559/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4560static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4561 IdentifierInfo *FnName,
4562 SourceLocation FnLoc,
4563 SourceLocation RParenLoc) {
4564 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4565 if (!Size)
4566 return false;
4567
4568 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4569 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4570 return false;
4571
Nico Weber0e6daef2013-12-26 23:38:39 +00004572 SourceRange SizeRange = Size->getSourceRange();
4573 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4574 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004575 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004576 << FnName << FixItHint::CreateInsertion(
4577 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004578 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004579 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004580 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004581 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4582 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004583
4584 return true;
4585}
4586
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004587/// \brief Determine whether the given type is or contains a dynamic class type
4588/// (e.g., whether it has a vtable).
4589static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4590 bool &IsContained) {
4591 // Look through array types while ignoring qualifiers.
4592 const Type *Ty = T->getBaseElementTypeUnsafe();
4593 IsContained = false;
4594
4595 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4596 RD = RD ? RD->getDefinition() : nullptr;
4597 if (!RD)
4598 return nullptr;
4599
4600 if (RD->isDynamicClass())
4601 return RD;
4602
4603 // Check all the fields. If any bases were dynamic, the class is dynamic.
4604 // It's impossible for a class to transitively contain itself by value, so
4605 // infinite recursion is impossible.
4606 for (auto *FD : RD->fields()) {
4607 bool SubContained;
4608 if (const CXXRecordDecl *ContainedRD =
4609 getContainedDynamicClass(FD->getType(), SubContained)) {
4610 IsContained = true;
4611 return ContainedRD;
4612 }
4613 }
4614
4615 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004616}
4617
Chandler Carruth889ed862011-06-21 23:04:20 +00004618/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004619/// otherwise returns NULL.
4620static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004621 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004622 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4623 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4624 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004625
Craig Topperc3ec1492014-05-26 06:22:03 +00004626 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004627}
4628
Chandler Carruth889ed862011-06-21 23:04:20 +00004629/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004630static QualType getSizeOfArgType(const Expr* E) {
4631 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4632 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4633 if (SizeOf->getKind() == clang::UETT_SizeOf)
4634 return SizeOf->getTypeOfArgument();
4635
4636 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004637}
4638
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004639/// \brief Check for dangerous or invalid arguments to memset().
4640///
Chandler Carruthac687262011-06-03 06:23:57 +00004641/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004642/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4643/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004644///
4645/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004646void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004647 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004648 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004649 assert(BId != 0);
4650
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004651 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004652 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004653 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004654 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004655 return;
4656
Anna Zaks22122702012-01-17 00:37:07 +00004657 unsigned LastArg = (BId == Builtin::BImemset ||
4658 BId == Builtin::BIstrndup ? 1 : 2);
4659 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004660 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004661
Nico Weber0e6daef2013-12-26 23:38:39 +00004662 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4663 Call->getLocStart(), Call->getRParenLoc()))
4664 return;
4665
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004666 // We have special checking when the length is a sizeof expression.
4667 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4668 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4669 llvm::FoldingSetNodeID SizeOfArgID;
4670
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004671 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4672 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004673 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004674
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004675 QualType DestTy = Dest->getType();
4676 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4677 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004678
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004679 // Never warn about void type pointers. This can be used to suppress
4680 // false positives.
4681 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004682 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004683
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004684 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4685 // actually comparing the expressions for equality. Because computing the
4686 // expression IDs can be expensive, we only do this if the diagnostic is
4687 // enabled.
4688 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004689 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4690 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004691 // We only compute IDs for expressions if the warning is enabled, and
4692 // cache the sizeof arg's ID.
4693 if (SizeOfArgID == llvm::FoldingSetNodeID())
4694 SizeOfArg->Profile(SizeOfArgID, Context, true);
4695 llvm::FoldingSetNodeID DestID;
4696 Dest->Profile(DestID, Context, true);
4697 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004698 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4699 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004700 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004701 StringRef ReadableName = FnName->getName();
4702
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004703 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004704 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004705 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004706 if (!PointeeTy->isIncompleteType() &&
4707 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004708 ActionIdx = 2; // If the pointee's size is sizeof(char),
4709 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004710
4711 // If the function is defined as a builtin macro, do not show macro
4712 // expansion.
4713 SourceLocation SL = SizeOfArg->getExprLoc();
4714 SourceRange DSR = Dest->getSourceRange();
4715 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004716 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004717
4718 if (SM.isMacroArgExpansion(SL)) {
4719 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4720 SL = SM.getSpellingLoc(SL);
4721 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4722 SM.getSpellingLoc(DSR.getEnd()));
4723 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4724 SM.getSpellingLoc(SSR.getEnd()));
4725 }
4726
Anna Zaksd08d9152012-05-30 23:14:52 +00004727 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004728 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004729 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004730 << PointeeTy
4731 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004732 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004733 << SSR);
4734 DiagRuntimeBehavior(SL, SizeOfArg,
4735 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4736 << ActionIdx
4737 << SSR);
4738
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004739 break;
4740 }
4741 }
4742
4743 // Also check for cases where the sizeof argument is the exact same
4744 // type as the memory argument, and where it points to a user-defined
4745 // record type.
4746 if (SizeOfArgTy != QualType()) {
4747 if (PointeeTy->isRecordType() &&
4748 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4749 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4750 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4751 << FnName << SizeOfArgTy << ArgIdx
4752 << PointeeTy << Dest->getSourceRange()
4753 << LenExpr->getSourceRange());
4754 break;
4755 }
Nico Weberc5e73862011-06-14 16:14:58 +00004756 }
4757
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004758 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004759 bool IsContained;
4760 if (const CXXRecordDecl *ContainedRD =
4761 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004762
4763 unsigned OperationType = 0;
4764 // "overwritten" if we're warning about the destination for any call
4765 // but memcmp; otherwise a verb appropriate to the call.
4766 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4767 if (BId == Builtin::BImemcpy)
4768 OperationType = 1;
4769 else if(BId == Builtin::BImemmove)
4770 OperationType = 2;
4771 else if (BId == Builtin::BImemcmp)
4772 OperationType = 3;
4773 }
4774
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004775 DiagRuntimeBehavior(
4776 Dest->getExprLoc(), Dest,
4777 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004778 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004779 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004780 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004781 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4782 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004783 DiagRuntimeBehavior(
4784 Dest->getExprLoc(), Dest,
4785 PDiag(diag::warn_arc_object_memaccess)
4786 << ArgIdx << FnName << PointeeTy
4787 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004788 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004789 continue;
John McCall31168b02011-06-15 23:02:42 +00004790
4791 DiagRuntimeBehavior(
4792 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004793 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004794 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4795 break;
4796 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004797 }
4798}
4799
Ted Kremenek6865f772011-08-18 20:55:45 +00004800// A little helper routine: ignore addition and subtraction of integer literals.
4801// This intentionally does not ignore all integer constant expressions because
4802// we don't want to remove sizeof().
4803static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4804 Ex = Ex->IgnoreParenCasts();
4805
4806 for (;;) {
4807 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4808 if (!BO || !BO->isAdditiveOp())
4809 break;
4810
4811 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4812 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4813
4814 if (isa<IntegerLiteral>(RHS))
4815 Ex = LHS;
4816 else if (isa<IntegerLiteral>(LHS))
4817 Ex = RHS;
4818 else
4819 break;
4820 }
4821
4822 return Ex;
4823}
4824
Anna Zaks13b08572012-08-08 21:42:23 +00004825static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4826 ASTContext &Context) {
4827 // Only handle constant-sized or VLAs, but not flexible members.
4828 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4829 // Only issue the FIXIT for arrays of size > 1.
4830 if (CAT->getSize().getSExtValue() <= 1)
4831 return false;
4832 } else if (!Ty->isVariableArrayType()) {
4833 return false;
4834 }
4835 return true;
4836}
4837
Ted Kremenek6865f772011-08-18 20:55:45 +00004838// Warn if the user has made the 'size' argument to strlcpy or strlcat
4839// be the size of the source, instead of the destination.
4840void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4841 IdentifierInfo *FnName) {
4842
4843 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004844 unsigned NumArgs = Call->getNumArgs();
4845 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004846 return;
4847
4848 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4849 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004850 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004851
4852 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4853 Call->getLocStart(), Call->getRParenLoc()))
4854 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004855
4856 // Look for 'strlcpy(dst, x, sizeof(x))'
4857 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4858 CompareWithSrc = Ex;
4859 else {
4860 // Look for 'strlcpy(dst, x, strlen(x))'
4861 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004862 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4863 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004864 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4865 }
4866 }
4867
4868 if (!CompareWithSrc)
4869 return;
4870
4871 // Determine if the argument to sizeof/strlen is equal to the source
4872 // argument. In principle there's all kinds of things you could do
4873 // here, for instance creating an == expression and evaluating it with
4874 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4875 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4876 if (!SrcArgDRE)
4877 return;
4878
4879 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4880 if (!CompareWithSrcDRE ||
4881 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4882 return;
4883
4884 const Expr *OriginalSizeArg = Call->getArg(2);
4885 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4886 << OriginalSizeArg->getSourceRange() << FnName;
4887
4888 // Output a FIXIT hint if the destination is an array (rather than a
4889 // pointer to an array). This could be enhanced to handle some
4890 // pointers if we know the actual size, like if DstArg is 'array+2'
4891 // we could say 'sizeof(array)-2'.
4892 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004893 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004894 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004895
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004896 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004897 llvm::raw_svector_ostream OS(sizeString);
4898 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004899 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004900 OS << ")";
4901
4902 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4903 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4904 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004905}
4906
Anna Zaks314cd092012-02-01 19:08:57 +00004907/// Check if two expressions refer to the same declaration.
4908static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4909 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4910 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4911 return D1->getDecl() == D2->getDecl();
4912 return false;
4913}
4914
4915static const Expr *getStrlenExprArg(const Expr *E) {
4916 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4917 const FunctionDecl *FD = CE->getDirectCallee();
4918 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004919 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004920 return CE->getArg(0)->IgnoreParenCasts();
4921 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004922 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004923}
4924
4925// Warn on anti-patterns as the 'size' argument to strncat.
4926// The correct size argument should look like following:
4927// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4928void Sema::CheckStrncatArguments(const CallExpr *CE,
4929 IdentifierInfo *FnName) {
4930 // Don't crash if the user has the wrong number of arguments.
4931 if (CE->getNumArgs() < 3)
4932 return;
4933 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4934 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4935 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4936
Nico Weber0e6daef2013-12-26 23:38:39 +00004937 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4938 CE->getRParenLoc()))
4939 return;
4940
Anna Zaks314cd092012-02-01 19:08:57 +00004941 // Identify common expressions, which are wrongly used as the size argument
4942 // to strncat and may lead to buffer overflows.
4943 unsigned PatternType = 0;
4944 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4945 // - sizeof(dst)
4946 if (referToTheSameDecl(SizeOfArg, DstArg))
4947 PatternType = 1;
4948 // - sizeof(src)
4949 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4950 PatternType = 2;
4951 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4952 if (BE->getOpcode() == BO_Sub) {
4953 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4954 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4955 // - sizeof(dst) - strlen(dst)
4956 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4957 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4958 PatternType = 1;
4959 // - sizeof(src) - (anything)
4960 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4961 PatternType = 2;
4962 }
4963 }
4964
4965 if (PatternType == 0)
4966 return;
4967
Anna Zaks5069aa32012-02-03 01:27:37 +00004968 // Generate the diagnostic.
4969 SourceLocation SL = LenArg->getLocStart();
4970 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004971 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004972
4973 // If the function is defined as a builtin macro, do not show macro expansion.
4974 if (SM.isMacroArgExpansion(SL)) {
4975 SL = SM.getSpellingLoc(SL);
4976 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4977 SM.getSpellingLoc(SR.getEnd()));
4978 }
4979
Anna Zaks13b08572012-08-08 21:42:23 +00004980 // Check if the destination is an array (rather than a pointer to an array).
4981 QualType DstTy = DstArg->getType();
4982 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4983 Context);
4984 if (!isKnownSizeArray) {
4985 if (PatternType == 1)
4986 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4987 else
4988 Diag(SL, diag::warn_strncat_src_size) << SR;
4989 return;
4990 }
4991
Anna Zaks314cd092012-02-01 19:08:57 +00004992 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004993 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004994 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004995 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004996
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004997 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004998 llvm::raw_svector_ostream OS(sizeString);
4999 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005000 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005001 OS << ") - ";
5002 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005003 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005004 OS << ") - 1";
5005
Anna Zaks5069aa32012-02-03 01:27:37 +00005006 Diag(SL, diag::note_strncat_wrong_size)
5007 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005008}
5009
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005010//===--- CHECK: Return Address of Stack Variable --------------------------===//
5011
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005012static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5013 Decl *ParentDecl);
5014static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5015 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005016
5017/// CheckReturnStackAddr - Check if a return statement returns the address
5018/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005019static void
5020CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5021 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005022
Craig Topperc3ec1492014-05-26 06:22:03 +00005023 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005024 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005025
5026 // Perform checking for returned stack addresses, local blocks,
5027 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005028 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005029 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005030 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005031 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005032 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005033 }
5034
Craig Topperc3ec1492014-05-26 06:22:03 +00005035 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005036 return; // Nothing suspicious was found.
5037
5038 SourceLocation diagLoc;
5039 SourceRange diagRange;
5040 if (refVars.empty()) {
5041 diagLoc = stackE->getLocStart();
5042 diagRange = stackE->getSourceRange();
5043 } else {
5044 // We followed through a reference variable. 'stackE' contains the
5045 // problematic expression but we will warn at the return statement pointing
5046 // at the reference variable. We will later display the "trail" of
5047 // reference variables using notes.
5048 diagLoc = refVars[0]->getLocStart();
5049 diagRange = refVars[0]->getSourceRange();
5050 }
5051
5052 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005053 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005054 : diag::warn_ret_stack_addr)
5055 << DR->getDecl()->getDeclName() << diagRange;
5056 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005057 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005058 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005059 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005060 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005061 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5062 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005063 << diagRange;
5064 }
5065
5066 // Display the "trail" of reference variables that we followed until we
5067 // found the problematic expression using notes.
5068 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5069 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5070 // If this var binds to another reference var, show the range of the next
5071 // var, otherwise the var binds to the problematic expression, in which case
5072 // show the range of the expression.
5073 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5074 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005075 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5076 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005077 }
5078}
5079
5080/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5081/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005082/// to a location on the stack, a local block, an address of a label, or a
5083/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005084/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005085/// encounter a subexpression that (1) clearly does not lead to one of the
5086/// above problematic expressions (2) is something we cannot determine leads to
5087/// a problematic expression based on such local checking.
5088///
5089/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5090/// the expression that they point to. Such variables are added to the
5091/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005092///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005093/// EvalAddr processes expressions that are pointers that are used as
5094/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005095/// At the base case of the recursion is a check for the above problematic
5096/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005097///
5098/// This implementation handles:
5099///
5100/// * pointer-to-pointer casts
5101/// * implicit conversions from array references to pointers
5102/// * taking the address of fields
5103/// * arbitrary interplay between "&" and "*" operators
5104/// * pointer arithmetic from an address of a stack variable
5105/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005106static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5107 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005108 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005109 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005110
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005111 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005112 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005113 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005114 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005115 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005116
Peter Collingbourne91147592011-04-15 00:35:48 +00005117 E = E->IgnoreParens();
5118
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005119 // Our "symbolic interpreter" is just a dispatch off the currently
5120 // viewed AST node. We then recursively traverse the AST by calling
5121 // EvalAddr and EvalVal appropriately.
5122 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005123 case Stmt::DeclRefExprClass: {
5124 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5125
Richard Smith40f08eb2014-01-30 22:05:38 +00005126 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005127 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005128 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005129
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005130 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5131 // If this is a reference variable, follow through to the expression that
5132 // it points to.
5133 if (V->hasLocalStorage() &&
5134 V->getType()->isReferenceType() && V->hasInit()) {
5135 // Add the reference variable to the "trail".
5136 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005137 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005138 }
5139
Craig Topperc3ec1492014-05-26 06:22:03 +00005140 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005141 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005142
Chris Lattner934edb22007-12-28 05:31:15 +00005143 case Stmt::UnaryOperatorClass: {
5144 // The only unary operator that make sense to handle here
5145 // is AddrOf. All others don't make sense as pointers.
5146 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005147
John McCalle3027922010-08-25 11:45:40 +00005148 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005149 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005150 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005151 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005152 }
Mike Stump11289f42009-09-09 15:08:12 +00005153
Chris Lattner934edb22007-12-28 05:31:15 +00005154 case Stmt::BinaryOperatorClass: {
5155 // Handle pointer arithmetic. All other binary operators are not valid
5156 // in this context.
5157 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005158 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005159
John McCalle3027922010-08-25 11:45:40 +00005160 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005161 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005162
Chris Lattner934edb22007-12-28 05:31:15 +00005163 Expr *Base = B->getLHS();
5164
5165 // Determine which argument is the real pointer base. It could be
5166 // the RHS argument instead of the LHS.
5167 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005168
Chris Lattner934edb22007-12-28 05:31:15 +00005169 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005170 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005171 }
Steve Naroff2752a172008-09-10 19:17:48 +00005172
Chris Lattner934edb22007-12-28 05:31:15 +00005173 // For conditional operators we need to see if either the LHS or RHS are
5174 // valid DeclRefExpr*s. If one of them is valid, we return it.
5175 case Stmt::ConditionalOperatorClass: {
5176 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005177
Chris Lattner934edb22007-12-28 05:31:15 +00005178 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005179 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5180 if (Expr *LHSExpr = C->getLHS()) {
5181 // In C++, we can have a throw-expression, which has 'void' type.
5182 if (!LHSExpr->getType()->isVoidType())
5183 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005184 return LHS;
5185 }
Chris Lattner934edb22007-12-28 05:31:15 +00005186
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005187 // In C++, we can have a throw-expression, which has 'void' type.
5188 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005189 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005190
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005191 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005192 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005193
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005194 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005195 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005196 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005197 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005198
5199 case Stmt::AddrLabelExprClass:
5200 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005201
John McCall28fc7092011-11-10 05:35:25 +00005202 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005203 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5204 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005205
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005206 // For casts, we need to handle conversions from arrays to
5207 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005208 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005209 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005210 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005211 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005212 case Stmt::CXXStaticCastExprClass:
5213 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005214 case Stmt::CXXConstCastExprClass:
5215 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005216 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5217 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005218 case CK_LValueToRValue:
5219 case CK_NoOp:
5220 case CK_BaseToDerived:
5221 case CK_DerivedToBase:
5222 case CK_UncheckedDerivedToBase:
5223 case CK_Dynamic:
5224 case CK_CPointerToObjCPointerCast:
5225 case CK_BlockPointerToObjCPointerCast:
5226 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005227 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005228
5229 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005230 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005231
Richard Trieudadefde2014-07-02 04:39:38 +00005232 case CK_BitCast:
5233 if (SubExpr->getType()->isAnyPointerType() ||
5234 SubExpr->getType()->isBlockPointerType() ||
5235 SubExpr->getType()->isObjCQualifiedIdType())
5236 return EvalAddr(SubExpr, refVars, ParentDecl);
5237 else
5238 return nullptr;
5239
Eli Friedman8195ad72012-02-23 23:04:32 +00005240 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005241 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005242 }
Chris Lattner934edb22007-12-28 05:31:15 +00005243 }
Mike Stump11289f42009-09-09 15:08:12 +00005244
Douglas Gregorfe314812011-06-21 17:03:29 +00005245 case Stmt::MaterializeTemporaryExprClass:
5246 if (Expr *Result = EvalAddr(
5247 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005248 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005249 return Result;
5250
5251 return E;
5252
Chris Lattner934edb22007-12-28 05:31:15 +00005253 // Everything else: we simply don't reason about them.
5254 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005255 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005256 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005257}
Mike Stump11289f42009-09-09 15:08:12 +00005258
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005259
5260/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5261/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005262static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5263 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005264do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005265 // We should only be called for evaluating non-pointer expressions, or
5266 // expressions with a pointer type that are not used as references but instead
5267 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005268
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005269 // Our "symbolic interpreter" is just a dispatch off the currently
5270 // viewed AST node. We then recursively traverse the AST by calling
5271 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005272
5273 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005274 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005275 case Stmt::ImplicitCastExprClass: {
5276 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005277 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005278 E = IE->getSubExpr();
5279 continue;
5280 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005281 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005282 }
5283
John McCall28fc7092011-11-10 05:35:25 +00005284 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005285 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005286
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005287 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005288 // When we hit a DeclRefExpr we are looking at code that refers to a
5289 // variable's name. If it's not a reference variable we check if it has
5290 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005291 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005292
Richard Smith40f08eb2014-01-30 22:05:38 +00005293 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005294 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005295 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005296
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005297 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5298 // Check if it refers to itself, e.g. "int& i = i;".
5299 if (V == ParentDecl)
5300 return DR;
5301
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005302 if (V->hasLocalStorage()) {
5303 if (!V->getType()->isReferenceType())
5304 return DR;
5305
5306 // Reference variable, follow through to the expression that
5307 // it points to.
5308 if (V->hasInit()) {
5309 // Add the reference variable to the "trail".
5310 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005311 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005312 }
5313 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005314 }
Mike Stump11289f42009-09-09 15:08:12 +00005315
Craig Topperc3ec1492014-05-26 06:22:03 +00005316 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005317 }
Mike Stump11289f42009-09-09 15:08:12 +00005318
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005319 case Stmt::UnaryOperatorClass: {
5320 // The only unary operator that make sense to handle here
5321 // is Deref. All others don't resolve to a "name." This includes
5322 // handling all sorts of rvalues passed to a unary operator.
5323 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005324
John McCalle3027922010-08-25 11:45:40 +00005325 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005326 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005327
Craig Topperc3ec1492014-05-26 06:22:03 +00005328 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005329 }
Mike Stump11289f42009-09-09 15:08:12 +00005330
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005331 case Stmt::ArraySubscriptExprClass: {
5332 // Array subscripts are potential references to data on the stack. We
5333 // retrieve the DeclRefExpr* for the array variable if it indeed
5334 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005335 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005336 }
Mike Stump11289f42009-09-09 15:08:12 +00005337
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005338 case Stmt::ConditionalOperatorClass: {
5339 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005340 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005341 ConditionalOperator *C = cast<ConditionalOperator>(E);
5342
Anders Carlsson801c5c72007-11-30 19:04:31 +00005343 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005344 if (Expr *LHSExpr = C->getLHS()) {
5345 // In C++, we can have a throw-expression, which has 'void' type.
5346 if (!LHSExpr->getType()->isVoidType())
5347 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5348 return LHS;
5349 }
5350
5351 // In C++, we can have a throw-expression, which has 'void' type.
5352 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005353 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005354
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005355 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005356 }
Mike Stump11289f42009-09-09 15:08:12 +00005357
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005358 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005359 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005360 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005361
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005362 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005363 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005364 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005365
5366 // Check whether the member type is itself a reference, in which case
5367 // we're not going to refer to the member, but to what the member refers to.
5368 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005369 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005370
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005371 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005372 }
Mike Stump11289f42009-09-09 15:08:12 +00005373
Douglas Gregorfe314812011-06-21 17:03:29 +00005374 case Stmt::MaterializeTemporaryExprClass:
5375 if (Expr *Result = EvalVal(
5376 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005377 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005378 return Result;
5379
5380 return E;
5381
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005382 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005383 // Check that we don't return or take the address of a reference to a
5384 // temporary. This is only useful in C++.
5385 if (!E->isTypeDependent() && E->isRValue())
5386 return E;
5387
5388 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005389 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005390 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005391} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005392}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005393
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005394void
5395Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5396 SourceLocation ReturnLoc,
5397 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005398 const AttrVec *Attrs,
5399 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005400 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5401
5402 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005403 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5404 CheckNonNullExpr(*this, RetValExp))
5405 Diag(ReturnLoc, diag::warn_null_ret)
5406 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005407
5408 // C++11 [basic.stc.dynamic.allocation]p4:
5409 // If an allocation function declared with a non-throwing
5410 // exception-specification fails to allocate storage, it shall return
5411 // a null pointer. Any other allocation function that fails to allocate
5412 // storage shall indicate failure only by throwing an exception [...]
5413 if (FD) {
5414 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5415 if (Op == OO_New || Op == OO_Array_New) {
5416 const FunctionProtoType *Proto
5417 = FD->getType()->castAs<FunctionProtoType>();
5418 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5419 CheckNonNullExpr(*this, RetValExp))
5420 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5421 << FD << getLangOpts().CPlusPlus11;
5422 }
5423 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005424}
5425
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005426//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5427
5428/// Check for comparisons of floating point operands using != and ==.
5429/// Issue a warning if these are no self-comparisons, as they are not likely
5430/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005431void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005432 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5433 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005434
5435 // Special case: check for x == x (which is OK).
5436 // Do not emit warnings for such cases.
5437 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5438 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5439 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005440 return;
Mike Stump11289f42009-09-09 15:08:12 +00005441
5442
Ted Kremenekeda40e22007-11-29 00:59:04 +00005443 // Special case: check for comparisons against literals that can be exactly
5444 // represented by APFloat. In such cases, do not emit a warning. This
5445 // is a heuristic: often comparison against such literals are used to
5446 // detect if a value in a variable has not changed. This clearly can
5447 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005448 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5449 if (FLL->isExact())
5450 return;
5451 } else
5452 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5453 if (FLR->isExact())
5454 return;
Mike Stump11289f42009-09-09 15:08:12 +00005455
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005456 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005457 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005458 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005459 return;
Mike Stump11289f42009-09-09 15:08:12 +00005460
David Blaikie1f4ff152012-07-16 20:47:22 +00005461 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005462 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005463 return;
Mike Stump11289f42009-09-09 15:08:12 +00005464
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005465 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005466 Diag(Loc, diag::warn_floatingpoint_eq)
5467 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005468}
John McCallca01b222010-01-04 23:21:16 +00005469
John McCall70aa5392010-01-06 05:24:50 +00005470//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5471//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005472
John McCall70aa5392010-01-06 05:24:50 +00005473namespace {
John McCallca01b222010-01-04 23:21:16 +00005474
John McCall70aa5392010-01-06 05:24:50 +00005475/// Structure recording the 'active' range of an integer-valued
5476/// expression.
5477struct IntRange {
5478 /// The number of bits active in the int.
5479 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005480
John McCall70aa5392010-01-06 05:24:50 +00005481 /// True if the int is known not to have negative values.
5482 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005483
John McCall70aa5392010-01-06 05:24:50 +00005484 IntRange(unsigned Width, bool NonNegative)
5485 : Width(Width), NonNegative(NonNegative)
5486 {}
John McCallca01b222010-01-04 23:21:16 +00005487
John McCall817d4af2010-11-10 23:38:19 +00005488 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005489 static IntRange forBoolType() {
5490 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005491 }
5492
John McCall817d4af2010-11-10 23:38:19 +00005493 /// Returns the range of an opaque value of the given integral type.
5494 static IntRange forValueOfType(ASTContext &C, QualType T) {
5495 return forValueOfCanonicalType(C,
5496 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005497 }
5498
John McCall817d4af2010-11-10 23:38:19 +00005499 /// Returns the range of an opaque value of a canonical integral type.
5500 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005501 assert(T->isCanonicalUnqualified());
5502
5503 if (const VectorType *VT = dyn_cast<VectorType>(T))
5504 T = VT->getElementType().getTypePtr();
5505 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5506 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005507 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5508 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005509
David Majnemer6a426652013-06-07 22:07:20 +00005510 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005511 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005512 EnumDecl *Enum = ET->getDecl();
5513 if (!Enum->isCompleteDefinition())
5514 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005515
David Majnemer6a426652013-06-07 22:07:20 +00005516 unsigned NumPositive = Enum->getNumPositiveBits();
5517 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005518
David Majnemer6a426652013-06-07 22:07:20 +00005519 if (NumNegative == 0)
5520 return IntRange(NumPositive, true/*NonNegative*/);
5521 else
5522 return IntRange(std::max(NumPositive + 1, NumNegative),
5523 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005524 }
John McCall70aa5392010-01-06 05:24:50 +00005525
5526 const BuiltinType *BT = cast<BuiltinType>(T);
5527 assert(BT->isInteger());
5528
5529 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5530 }
5531
John McCall817d4af2010-11-10 23:38:19 +00005532 /// Returns the "target" range of a canonical integral type, i.e.
5533 /// the range of values expressible in the type.
5534 ///
5535 /// This matches forValueOfCanonicalType except that enums have the
5536 /// full range of their type, not the range of their enumerators.
5537 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5538 assert(T->isCanonicalUnqualified());
5539
5540 if (const VectorType *VT = dyn_cast<VectorType>(T))
5541 T = VT->getElementType().getTypePtr();
5542 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5543 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005544 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5545 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005546 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005547 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005548
5549 const BuiltinType *BT = cast<BuiltinType>(T);
5550 assert(BT->isInteger());
5551
5552 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5553 }
5554
5555 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005556 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005557 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005558 L.NonNegative && R.NonNegative);
5559 }
5560
John McCall817d4af2010-11-10 23:38:19 +00005561 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005562 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005563 return IntRange(std::min(L.Width, R.Width),
5564 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005565 }
5566};
5567
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005568static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5569 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005570 if (value.isSigned() && value.isNegative())
5571 return IntRange(value.getMinSignedBits(), false);
5572
5573 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005574 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005575
5576 // isNonNegative() just checks the sign bit without considering
5577 // signedness.
5578 return IntRange(value.getActiveBits(), true);
5579}
5580
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005581static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5582 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005583 if (result.isInt())
5584 return GetValueRange(C, result.getInt(), MaxWidth);
5585
5586 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005587 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5588 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5589 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5590 R = IntRange::join(R, El);
5591 }
John McCall70aa5392010-01-06 05:24:50 +00005592 return R;
5593 }
5594
5595 if (result.isComplexInt()) {
5596 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5597 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5598 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005599 }
5600
5601 // This can happen with lossless casts to intptr_t of "based" lvalues.
5602 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005603 // FIXME: The only reason we need to pass the type in here is to get
5604 // the sign right on this one case. It would be nice if APValue
5605 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005606 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005607 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005608}
John McCall70aa5392010-01-06 05:24:50 +00005609
Eli Friedmane6d33952013-07-08 20:20:06 +00005610static QualType GetExprType(Expr *E) {
5611 QualType Ty = E->getType();
5612 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5613 Ty = AtomicRHS->getValueType();
5614 return Ty;
5615}
5616
John McCall70aa5392010-01-06 05:24:50 +00005617/// Pseudo-evaluate the given integer expression, estimating the
5618/// range of values it might take.
5619///
5620/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005621static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005622 E = E->IgnoreParens();
5623
5624 // Try a full evaluation first.
5625 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005626 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005627 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005628
5629 // I think we only want to look through implicit casts here; if the
5630 // user has an explicit widening cast, we should treat the value as
5631 // being of the new, wider type.
5632 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005633 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005634 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5635
Eli Friedmane6d33952013-07-08 20:20:06 +00005636 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005637
John McCalle3027922010-08-25 11:45:40 +00005638 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005639
John McCall70aa5392010-01-06 05:24:50 +00005640 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005641 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005642 return OutputTypeRange;
5643
5644 IntRange SubRange
5645 = GetExprRange(C, CE->getSubExpr(),
5646 std::min(MaxWidth, OutputTypeRange.Width));
5647
5648 // Bail out if the subexpr's range is as wide as the cast type.
5649 if (SubRange.Width >= OutputTypeRange.Width)
5650 return OutputTypeRange;
5651
5652 // Otherwise, we take the smaller width, and we're non-negative if
5653 // either the output type or the subexpr is.
5654 return IntRange(SubRange.Width,
5655 SubRange.NonNegative || OutputTypeRange.NonNegative);
5656 }
5657
5658 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5659 // If we can fold the condition, just take that operand.
5660 bool CondResult;
5661 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5662 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5663 : CO->getFalseExpr(),
5664 MaxWidth);
5665
5666 // Otherwise, conservatively merge.
5667 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5668 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5669 return IntRange::join(L, R);
5670 }
5671
5672 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5673 switch (BO->getOpcode()) {
5674
5675 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005676 case BO_LAnd:
5677 case BO_LOr:
5678 case BO_LT:
5679 case BO_GT:
5680 case BO_LE:
5681 case BO_GE:
5682 case BO_EQ:
5683 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005684 return IntRange::forBoolType();
5685
John McCallc3688382011-07-13 06:35:24 +00005686 // The type of the assignments is the type of the LHS, so the RHS
5687 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005688 case BO_MulAssign:
5689 case BO_DivAssign:
5690 case BO_RemAssign:
5691 case BO_AddAssign:
5692 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005693 case BO_XorAssign:
5694 case BO_OrAssign:
5695 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005696 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005697
John McCallc3688382011-07-13 06:35:24 +00005698 // Simple assignments just pass through the RHS, which will have
5699 // been coerced to the LHS type.
5700 case BO_Assign:
5701 // TODO: bitfields?
5702 return GetExprRange(C, BO->getRHS(), MaxWidth);
5703
John McCall70aa5392010-01-06 05:24:50 +00005704 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005705 case BO_PtrMemD:
5706 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005707 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005708
John McCall2ce81ad2010-01-06 22:07:33 +00005709 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005710 case BO_And:
5711 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005712 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5713 GetExprRange(C, BO->getRHS(), MaxWidth));
5714
John McCall70aa5392010-01-06 05:24:50 +00005715 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005716 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005717 // ...except that we want to treat '1 << (blah)' as logically
5718 // positive. It's an important idiom.
5719 if (IntegerLiteral *I
5720 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5721 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005722 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005723 return IntRange(R.Width, /*NonNegative*/ true);
5724 }
5725 }
5726 // fallthrough
5727
John McCalle3027922010-08-25 11:45:40 +00005728 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005729 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005730
John McCall2ce81ad2010-01-06 22:07:33 +00005731 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005732 case BO_Shr:
5733 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005734 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5735
5736 // If the shift amount is a positive constant, drop the width by
5737 // that much.
5738 llvm::APSInt shift;
5739 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5740 shift.isNonNegative()) {
5741 unsigned zext = shift.getZExtValue();
5742 if (zext >= L.Width)
5743 L.Width = (L.NonNegative ? 0 : 1);
5744 else
5745 L.Width -= zext;
5746 }
5747
5748 return L;
5749 }
5750
5751 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005752 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005753 return GetExprRange(C, BO->getRHS(), MaxWidth);
5754
John McCall2ce81ad2010-01-06 22:07:33 +00005755 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005756 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005757 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005758 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005759 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005760
John McCall51431812011-07-14 22:39:48 +00005761 // The width of a division result is mostly determined by the size
5762 // of the LHS.
5763 case BO_Div: {
5764 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005765 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005766 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5767
5768 // If the divisor is constant, use that.
5769 llvm::APSInt divisor;
5770 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5771 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5772 if (log2 >= L.Width)
5773 L.Width = (L.NonNegative ? 0 : 1);
5774 else
5775 L.Width = std::min(L.Width - log2, MaxWidth);
5776 return L;
5777 }
5778
5779 // Otherwise, just use the LHS's width.
5780 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5781 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5782 }
5783
5784 // The result of a remainder can't be larger than the result of
5785 // either side.
5786 case BO_Rem: {
5787 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005788 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005789 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5790 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5791
5792 IntRange meet = IntRange::meet(L, R);
5793 meet.Width = std::min(meet.Width, MaxWidth);
5794 return meet;
5795 }
5796
5797 // The default behavior is okay for these.
5798 case BO_Mul:
5799 case BO_Add:
5800 case BO_Xor:
5801 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005802 break;
5803 }
5804
John McCall51431812011-07-14 22:39:48 +00005805 // The default case is to treat the operation as if it were closed
5806 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005807 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5808 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5809 return IntRange::join(L, R);
5810 }
5811
5812 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5813 switch (UO->getOpcode()) {
5814 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005815 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005816 return IntRange::forBoolType();
5817
5818 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005819 case UO_Deref:
5820 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005821 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005822
5823 default:
5824 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5825 }
5826 }
5827
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005828 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5829 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5830
John McCalld25db7e2013-05-06 21:39:12 +00005831 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005832 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005833 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005834
Eli Friedmane6d33952013-07-08 20:20:06 +00005835 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005836}
John McCall263a48b2010-01-04 23:31:57 +00005837
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005838static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005839 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005840}
5841
John McCall263a48b2010-01-04 23:31:57 +00005842/// Checks whether the given value, which currently has the given
5843/// source semantics, has the same value when coerced through the
5844/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005845static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5846 const llvm::fltSemantics &Src,
5847 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005848 llvm::APFloat truncated = value;
5849
5850 bool ignored;
5851 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5852 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5853
5854 return truncated.bitwiseIsEqual(value);
5855}
5856
5857/// Checks whether the given value, which currently has the given
5858/// source semantics, has the same value when coerced through the
5859/// target semantics.
5860///
5861/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005862static bool IsSameFloatAfterCast(const APValue &value,
5863 const llvm::fltSemantics &Src,
5864 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005865 if (value.isFloat())
5866 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5867
5868 if (value.isVector()) {
5869 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5870 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5871 return false;
5872 return true;
5873 }
5874
5875 assert(value.isComplexFloat());
5876 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5877 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5878}
5879
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005880static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005881
Ted Kremenek6274be42010-09-23 21:43:44 +00005882static bool IsZero(Sema &S, Expr *E) {
5883 // Suppress cases where we are comparing against an enum constant.
5884 if (const DeclRefExpr *DR =
5885 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5886 if (isa<EnumConstantDecl>(DR->getDecl()))
5887 return false;
5888
5889 // Suppress cases where the '0' value is expanded from a macro.
5890 if (E->getLocStart().isMacroID())
5891 return false;
5892
John McCallcc7e5bf2010-05-06 08:58:33 +00005893 llvm::APSInt Value;
5894 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5895}
5896
John McCall2551c1b2010-10-06 00:25:24 +00005897static bool HasEnumType(Expr *E) {
5898 // Strip off implicit integral promotions.
5899 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005900 if (ICE->getCastKind() != CK_IntegralCast &&
5901 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005902 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005903 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005904 }
5905
5906 return E->getType()->isEnumeralType();
5907}
5908
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005909static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005910 // Disable warning in template instantiations.
5911 if (!S.ActiveTemplateInstantiations.empty())
5912 return;
5913
John McCalle3027922010-08-25 11:45:40 +00005914 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005915 if (E->isValueDependent())
5916 return;
5917
John McCalle3027922010-08-25 11:45:40 +00005918 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005919 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005920 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005921 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005922 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005923 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005924 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005925 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005926 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005927 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005928 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005929 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005930 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005931 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005932 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005933 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5934 }
5935}
5936
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005937static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005938 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005939 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005940 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005941 // Disable warning in template instantiations.
5942 if (!S.ActiveTemplateInstantiations.empty())
5943 return;
5944
Richard Trieu0f097742014-04-04 04:13:47 +00005945 // TODO: Investigate using GetExprRange() to get tighter bounds
5946 // on the bit ranges.
5947 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005948 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5949 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005950 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5951 unsigned OtherWidth = OtherRange.Width;
5952
5953 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5954
Richard Trieu560910c2012-11-14 22:50:24 +00005955 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005956 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005957 return;
5958
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005959 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005960 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005961
Richard Trieu0f097742014-04-04 04:13:47 +00005962 // Used for diagnostic printout.
5963 enum {
5964 LiteralConstant = 0,
5965 CXXBoolLiteralTrue,
5966 CXXBoolLiteralFalse
5967 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005968
Richard Trieu0f097742014-04-04 04:13:47 +00005969 if (!OtherIsBooleanType) {
5970 QualType ConstantT = Constant->getType();
5971 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005972
Richard Trieu0f097742014-04-04 04:13:47 +00005973 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5974 return;
5975 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5976 "comparison with non-integer type");
5977
5978 bool ConstantSigned = ConstantT->isSignedIntegerType();
5979 bool CommonSigned = CommonT->isSignedIntegerType();
5980
5981 bool EqualityOnly = false;
5982
5983 if (CommonSigned) {
5984 // The common type is signed, therefore no signed to unsigned conversion.
5985 if (!OtherRange.NonNegative) {
5986 // Check that the constant is representable in type OtherT.
5987 if (ConstantSigned) {
5988 if (OtherWidth >= Value.getMinSignedBits())
5989 return;
5990 } else { // !ConstantSigned
5991 if (OtherWidth >= Value.getActiveBits() + 1)
5992 return;
5993 }
5994 } else { // !OtherSigned
5995 // Check that the constant is representable in type OtherT.
5996 // Negative values are out of range.
5997 if (ConstantSigned) {
5998 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5999 return;
6000 } else { // !ConstantSigned
6001 if (OtherWidth >= Value.getActiveBits())
6002 return;
6003 }
Richard Trieu560910c2012-11-14 22:50:24 +00006004 }
Richard Trieu0f097742014-04-04 04:13:47 +00006005 } else { // !CommonSigned
6006 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006007 if (OtherWidth >= Value.getActiveBits())
6008 return;
Craig Toppercf360162014-06-18 05:13:11 +00006009 } else { // OtherSigned
6010 assert(!ConstantSigned &&
6011 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006012 // Check to see if the constant is representable in OtherT.
6013 if (OtherWidth > Value.getActiveBits())
6014 return;
6015 // Check to see if the constant is equivalent to a negative value
6016 // cast to CommonT.
6017 if (S.Context.getIntWidth(ConstantT) ==
6018 S.Context.getIntWidth(CommonT) &&
6019 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6020 return;
6021 // The constant value rests between values that OtherT can represent
6022 // after conversion. Relational comparison still works, but equality
6023 // comparisons will be tautological.
6024 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006025 }
6026 }
Richard Trieu0f097742014-04-04 04:13:47 +00006027
6028 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6029
6030 if (op == BO_EQ || op == BO_NE) {
6031 IsTrue = op == BO_NE;
6032 } else if (EqualityOnly) {
6033 return;
6034 } else if (RhsConstant) {
6035 if (op == BO_GT || op == BO_GE)
6036 IsTrue = !PositiveConstant;
6037 else // op == BO_LT || op == BO_LE
6038 IsTrue = PositiveConstant;
6039 } else {
6040 if (op == BO_LT || op == BO_LE)
6041 IsTrue = !PositiveConstant;
6042 else // op == BO_GT || op == BO_GE
6043 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006044 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006045 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006046 // Other isKnownToHaveBooleanValue
6047 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6048 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6049 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6050
6051 static const struct LinkedConditions {
6052 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6053 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6054 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6055 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6056 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6057 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6058
6059 } TruthTable = {
6060 // Constant on LHS. | Constant on RHS. |
6061 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6062 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6063 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6064 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6065 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6066 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6067 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6068 };
6069
6070 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6071
6072 enum ConstantValue ConstVal = Zero;
6073 if (Value.isUnsigned() || Value.isNonNegative()) {
6074 if (Value == 0) {
6075 LiteralOrBoolConstant =
6076 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6077 ConstVal = Zero;
6078 } else if (Value == 1) {
6079 LiteralOrBoolConstant =
6080 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6081 ConstVal = One;
6082 } else {
6083 LiteralOrBoolConstant = LiteralConstant;
6084 ConstVal = GT_One;
6085 }
6086 } else {
6087 ConstVal = LT_Zero;
6088 }
6089
6090 CompareBoolWithConstantResult CmpRes;
6091
6092 switch (op) {
6093 case BO_LT:
6094 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6095 break;
6096 case BO_GT:
6097 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6098 break;
6099 case BO_LE:
6100 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6101 break;
6102 case BO_GE:
6103 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6104 break;
6105 case BO_EQ:
6106 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6107 break;
6108 case BO_NE:
6109 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6110 break;
6111 default:
6112 CmpRes = Unkwn;
6113 break;
6114 }
6115
6116 if (CmpRes == AFals) {
6117 IsTrue = false;
6118 } else if (CmpRes == ATrue) {
6119 IsTrue = true;
6120 } else {
6121 return;
6122 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006123 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006124
6125 // If this is a comparison to an enum constant, include that
6126 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006127 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006128 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6129 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6130
6131 SmallString<64> PrettySourceValue;
6132 llvm::raw_svector_ostream OS(PrettySourceValue);
6133 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006134 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006135 else
6136 OS << Value;
6137
Richard Trieu0f097742014-04-04 04:13:47 +00006138 S.DiagRuntimeBehavior(
6139 E->getOperatorLoc(), E,
6140 S.PDiag(diag::warn_out_of_range_compare)
6141 << OS.str() << LiteralOrBoolConstant
6142 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6143 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006144}
6145
John McCallcc7e5bf2010-05-06 08:58:33 +00006146/// Analyze the operands of the given comparison. Implements the
6147/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006148static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006149 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6150 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006151}
John McCall263a48b2010-01-04 23:31:57 +00006152
John McCallca01b222010-01-04 23:21:16 +00006153/// \brief Implements -Wsign-compare.
6154///
Richard Trieu82402a02011-09-15 21:56:47 +00006155/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006156static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006157 // The type the comparison is being performed in.
6158 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006159
6160 // Only analyze comparison operators where both sides have been converted to
6161 // the same type.
6162 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6163 return AnalyzeImpConvsInComparison(S, E);
6164
6165 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006166 if (E->isValueDependent())
6167 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006168
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006169 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6170 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006171
6172 bool IsComparisonConstant = false;
6173
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006174 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006175 // of 'true' or 'false'.
6176 if (T->isIntegralType(S.Context)) {
6177 llvm::APSInt RHSValue;
6178 bool IsRHSIntegralLiteral =
6179 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6180 llvm::APSInt LHSValue;
6181 bool IsLHSIntegralLiteral =
6182 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6183 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6184 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6185 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6186 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6187 else
6188 IsComparisonConstant =
6189 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006190 } else if (!T->hasUnsignedIntegerRepresentation())
6191 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006192
John McCallcc7e5bf2010-05-06 08:58:33 +00006193 // We don't do anything special if this isn't an unsigned integral
6194 // comparison: we're only interested in integral comparisons, and
6195 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006196 //
6197 // We also don't care about value-dependent expressions or expressions
6198 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006199 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006200 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006201
John McCallcc7e5bf2010-05-06 08:58:33 +00006202 // Check to see if one of the (unmodified) operands is of different
6203 // signedness.
6204 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006205 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6206 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006207 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006208 signedOperand = LHS;
6209 unsignedOperand = RHS;
6210 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6211 signedOperand = RHS;
6212 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006213 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006214 CheckTrivialUnsignedComparison(S, E);
6215 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006216 }
6217
John McCallcc7e5bf2010-05-06 08:58:33 +00006218 // Otherwise, calculate the effective range of the signed operand.
6219 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006220
John McCallcc7e5bf2010-05-06 08:58:33 +00006221 // Go ahead and analyze implicit conversions in the operands. Note
6222 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006223 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6224 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006225
John McCallcc7e5bf2010-05-06 08:58:33 +00006226 // If the signed range is non-negative, -Wsign-compare won't fire,
6227 // but we should still check for comparisons which are always true
6228 // or false.
6229 if (signedRange.NonNegative)
6230 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006231
6232 // For (in)equality comparisons, if the unsigned operand is a
6233 // constant which cannot collide with a overflowed signed operand,
6234 // then reinterpreting the signed operand as unsigned will not
6235 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006236 if (E->isEqualityOp()) {
6237 unsigned comparisonWidth = S.Context.getIntWidth(T);
6238 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006239
John McCallcc7e5bf2010-05-06 08:58:33 +00006240 // We should never be unable to prove that the unsigned operand is
6241 // non-negative.
6242 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6243
6244 if (unsignedRange.Width < comparisonWidth)
6245 return;
6246 }
6247
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006248 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6249 S.PDiag(diag::warn_mixed_sign_comparison)
6250 << LHS->getType() << RHS->getType()
6251 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006252}
6253
John McCall1f425642010-11-11 03:21:53 +00006254/// Analyzes an attempt to assign the given value to a bitfield.
6255///
6256/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006257static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6258 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006259 assert(Bitfield->isBitField());
6260 if (Bitfield->isInvalidDecl())
6261 return false;
6262
John McCalldeebbcf2010-11-11 05:33:51 +00006263 // White-list bool bitfields.
6264 if (Bitfield->getType()->isBooleanType())
6265 return false;
6266
Douglas Gregor789adec2011-02-04 13:09:01 +00006267 // Ignore value- or type-dependent expressions.
6268 if (Bitfield->getBitWidth()->isValueDependent() ||
6269 Bitfield->getBitWidth()->isTypeDependent() ||
6270 Init->isValueDependent() ||
6271 Init->isTypeDependent())
6272 return false;
6273
John McCall1f425642010-11-11 03:21:53 +00006274 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6275
Richard Smith5fab0c92011-12-28 19:48:30 +00006276 llvm::APSInt Value;
6277 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006278 return false;
6279
John McCall1f425642010-11-11 03:21:53 +00006280 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006281 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006282
6283 if (OriginalWidth <= FieldWidth)
6284 return false;
6285
Eli Friedmanc267a322012-01-26 23:11:39 +00006286 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006287 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006288 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006289
Eli Friedmanc267a322012-01-26 23:11:39 +00006290 // Check whether the stored value is equal to the original value.
6291 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006292 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006293 return false;
6294
Eli Friedmanc267a322012-01-26 23:11:39 +00006295 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006296 // therefore don't strictly fit into a signed bitfield of width 1.
6297 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006298 return false;
6299
John McCall1f425642010-11-11 03:21:53 +00006300 std::string PrettyValue = Value.toString(10);
6301 std::string PrettyTrunc = TruncatedValue.toString(10);
6302
6303 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6304 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6305 << Init->getSourceRange();
6306
6307 return true;
6308}
6309
John McCalld2a53122010-11-09 23:24:47 +00006310/// Analyze the given simple or compound assignment for warning-worthy
6311/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006312static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006313 // Just recurse on the LHS.
6314 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6315
6316 // We want to recurse on the RHS as normal unless we're assigning to
6317 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006318 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006319 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006320 E->getOperatorLoc())) {
6321 // Recurse, ignoring any implicit conversions on the RHS.
6322 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6323 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006324 }
6325 }
6326
6327 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6328}
6329
John McCall263a48b2010-01-04 23:31:57 +00006330/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006331static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006332 SourceLocation CContext, unsigned diag,
6333 bool pruneControlFlow = false) {
6334 if (pruneControlFlow) {
6335 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6336 S.PDiag(diag)
6337 << SourceType << T << E->getSourceRange()
6338 << SourceRange(CContext));
6339 return;
6340 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006341 S.Diag(E->getExprLoc(), diag)
6342 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6343}
6344
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006345/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006346static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006347 SourceLocation CContext, unsigned diag,
6348 bool pruneControlFlow = false) {
6349 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006350}
6351
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006352/// Diagnose an implicit cast from a literal expression. Does not warn when the
6353/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006354void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6355 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006356 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006357 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006358 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006359 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6360 T->hasUnsignedIntegerRepresentation());
6361 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006362 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006363 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006364 return;
6365
Eli Friedman07185912013-08-29 23:44:43 +00006366 // FIXME: Force the precision of the source value down so we don't print
6367 // digits which are usually useless (we don't really care here if we
6368 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6369 // would automatically print the shortest representation, but it's a bit
6370 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006371 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006372 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6373 precision = (precision * 59 + 195) / 196;
6374 Value.toString(PrettySourceValue, precision);
6375
David Blaikie9b88cc02012-05-15 17:18:27 +00006376 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006377 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6378 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6379 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006380 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006381
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006382 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006383 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6384 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006385}
6386
John McCall18a2c2c2010-11-09 22:22:12 +00006387std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6388 if (!Range.Width) return "0";
6389
6390 llvm::APSInt ValueInRange = Value;
6391 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006392 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006393 return ValueInRange.toString(10);
6394}
6395
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006396static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6397 if (!isa<ImplicitCastExpr>(Ex))
6398 return false;
6399
6400 Expr *InnerE = Ex->IgnoreParenImpCasts();
6401 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6402 const Type *Source =
6403 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6404 if (Target->isDependentType())
6405 return false;
6406
6407 const BuiltinType *FloatCandidateBT =
6408 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6409 const Type *BoolCandidateType = ToBool ? Target : Source;
6410
6411 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6412 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6413}
6414
6415void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6416 SourceLocation CC) {
6417 unsigned NumArgs = TheCall->getNumArgs();
6418 for (unsigned i = 0; i < NumArgs; ++i) {
6419 Expr *CurrA = TheCall->getArg(i);
6420 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6421 continue;
6422
6423 bool IsSwapped = ((i > 0) &&
6424 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6425 IsSwapped |= ((i < (NumArgs - 1)) &&
6426 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6427 if (IsSwapped) {
6428 // Warn on this floating-point to bool conversion.
6429 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6430 CurrA->getType(), CC,
6431 diag::warn_impcast_floating_point_to_bool);
6432 }
6433 }
6434}
6435
Richard Trieu5b993502014-10-15 03:42:06 +00006436static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6437 SourceLocation CC) {
6438 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6439 E->getExprLoc()))
6440 return;
6441
6442 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6443 const Expr::NullPointerConstantKind NullKind =
6444 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6445 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6446 return;
6447
6448 // Return if target type is a safe conversion.
6449 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6450 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6451 return;
6452
6453 SourceLocation Loc = E->getSourceRange().getBegin();
6454
6455 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6456 if (NullKind == Expr::NPCK_GNUNull) {
6457 if (Loc.isMacroID())
6458 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6459 }
6460
6461 // Only warn if the null and context location are in the same macro expansion.
6462 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6463 return;
6464
6465 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6466 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6467 << FixItHint::CreateReplacement(Loc,
6468 S.getFixItZeroLiteralForType(T, Loc));
6469}
6470
John McCallcc7e5bf2010-05-06 08:58:33 +00006471void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006472 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006473 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006474
John McCallcc7e5bf2010-05-06 08:58:33 +00006475 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6476 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6477 if (Source == Target) return;
6478 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006479
Chandler Carruthc22845a2011-07-26 05:40:03 +00006480 // If the conversion context location is invalid don't complain. We also
6481 // don't want to emit a warning if the issue occurs from the expansion of
6482 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6483 // delay this check as long as possible. Once we detect we are in that
6484 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006485 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006486 return;
6487
Richard Trieu021baa32011-09-23 20:10:00 +00006488 // Diagnose implicit casts to bool.
6489 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6490 if (isa<StringLiteral>(E))
6491 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006492 // and expressions, for instance, assert(0 && "error here"), are
6493 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006494 return DiagnoseImpCast(S, E, T, CC,
6495 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006496 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6497 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6498 // This covers the literal expressions that evaluate to Objective-C
6499 // objects.
6500 return DiagnoseImpCast(S, E, T, CC,
6501 diag::warn_impcast_objective_c_literal_to_bool);
6502 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006503 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6504 // Warn on pointer to bool conversion that is always true.
6505 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6506 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006507 }
Richard Trieu021baa32011-09-23 20:10:00 +00006508 }
John McCall263a48b2010-01-04 23:31:57 +00006509
6510 // Strip vector types.
6511 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006512 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006513 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006514 return;
John McCallacf0ee52010-10-08 02:01:28 +00006515 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006516 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006517
6518 // If the vector cast is cast between two vectors of the same size, it is
6519 // a bitcast, not a conversion.
6520 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6521 return;
John McCall263a48b2010-01-04 23:31:57 +00006522
6523 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6524 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6525 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006526 if (auto VecTy = dyn_cast<VectorType>(Target))
6527 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006528
6529 // Strip complex types.
6530 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006531 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006532 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006533 return;
6534
John McCallacf0ee52010-10-08 02:01:28 +00006535 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006536 }
John McCall263a48b2010-01-04 23:31:57 +00006537
6538 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6539 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6540 }
6541
6542 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6543 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6544
6545 // If the source is floating point...
6546 if (SourceBT && SourceBT->isFloatingPoint()) {
6547 // ...and the target is floating point...
6548 if (TargetBT && TargetBT->isFloatingPoint()) {
6549 // ...then warn if we're dropping FP rank.
6550
6551 // Builtin FP kinds are ordered by increasing FP rank.
6552 if (SourceBT->getKind() > TargetBT->getKind()) {
6553 // Don't warn about float constants that are precisely
6554 // representable in the target type.
6555 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006556 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006557 // Value might be a float, a float vector, or a float complex.
6558 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006559 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6560 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006561 return;
6562 }
6563
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006564 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006565 return;
6566
John McCallacf0ee52010-10-08 02:01:28 +00006567 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006568 }
6569 return;
6570 }
6571
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006572 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006573 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006574 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006575 return;
6576
Chandler Carruth22c7a792011-02-17 11:05:49 +00006577 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006578 // We also want to warn on, e.g., "int i = -1.234"
6579 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6580 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6581 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6582
Chandler Carruth016ef402011-04-10 08:36:24 +00006583 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6584 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006585 } else {
6586 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6587 }
6588 }
John McCall263a48b2010-01-04 23:31:57 +00006589
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006590 // If the target is bool, warn if expr is a function or method call.
6591 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6592 isa<CallExpr>(E)) {
6593 // Check last argument of function call to see if it is an
6594 // implicit cast from a type matching the type the result
6595 // is being cast to.
6596 CallExpr *CEx = cast<CallExpr>(E);
6597 unsigned NumArgs = CEx->getNumArgs();
6598 if (NumArgs > 0) {
6599 Expr *LastA = CEx->getArg(NumArgs - 1);
6600 Expr *InnerE = LastA->IgnoreParenImpCasts();
6601 const Type *InnerType =
6602 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6603 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6604 // Warn on this floating-point to bool conversion
6605 DiagnoseImpCast(S, E, T, CC,
6606 diag::warn_impcast_floating_point_to_bool);
6607 }
6608 }
6609 }
John McCall263a48b2010-01-04 23:31:57 +00006610 return;
6611 }
6612
Richard Trieu5b993502014-10-15 03:42:06 +00006613 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006614
David Blaikie9366d2b2012-06-19 21:19:06 +00006615 if (!Source->isIntegerType() || !Target->isIntegerType())
6616 return;
6617
David Blaikie7555b6a2012-05-15 16:56:36 +00006618 // TODO: remove this early return once the false positives for constant->bool
6619 // in templates, macros, etc, are reduced or removed.
6620 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6621 return;
6622
John McCallcc7e5bf2010-05-06 08:58:33 +00006623 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006624 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006625
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006626 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006627 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006628 // TODO: this should happen for bitfield stores, too.
6629 llvm::APSInt Value(32);
6630 if (E->isIntegerConstantExpr(Value, S.Context)) {
6631 if (S.SourceMgr.isInSystemMacro(CC))
6632 return;
6633
John McCall18a2c2c2010-11-09 22:22:12 +00006634 std::string PrettySourceValue = Value.toString(10);
6635 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006636
Ted Kremenek33ba9952011-10-22 02:37:33 +00006637 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6638 S.PDiag(diag::warn_impcast_integer_precision_constant)
6639 << PrettySourceValue << PrettyTargetValue
6640 << E->getType() << T << E->getSourceRange()
6641 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006642 return;
6643 }
6644
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006645 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6646 if (S.SourceMgr.isInSystemMacro(CC))
6647 return;
6648
David Blaikie9455da02012-04-12 22:40:54 +00006649 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006650 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6651 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006652 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006653 }
6654
6655 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6656 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6657 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006658
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006659 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006660 return;
6661
John McCallcc7e5bf2010-05-06 08:58:33 +00006662 unsigned DiagID = diag::warn_impcast_integer_sign;
6663
6664 // Traditionally, gcc has warned about this under -Wsign-compare.
6665 // We also want to warn about it in -Wconversion.
6666 // So if -Wconversion is off, use a completely identical diagnostic
6667 // in the sign-compare group.
6668 // The conditional-checking code will
6669 if (ICContext) {
6670 DiagID = diag::warn_impcast_integer_sign_conditional;
6671 *ICContext = true;
6672 }
6673
John McCallacf0ee52010-10-08 02:01:28 +00006674 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006675 }
6676
Douglas Gregora78f1932011-02-22 02:45:07 +00006677 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006678 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6679 // type, to give us better diagnostics.
6680 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006681 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006682 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6683 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6684 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6685 SourceType = S.Context.getTypeDeclType(Enum);
6686 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6687 }
6688 }
6689
Douglas Gregora78f1932011-02-22 02:45:07 +00006690 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6691 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006692 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6693 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006694 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006695 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006696 return;
6697
Douglas Gregor364f7db2011-03-12 00:14:31 +00006698 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006699 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006700 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006701
John McCall263a48b2010-01-04 23:31:57 +00006702 return;
6703}
6704
David Blaikie18e9ac72012-05-15 21:57:38 +00006705void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6706 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006707
6708void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006709 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006710 E = E->IgnoreParenImpCasts();
6711
6712 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006713 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006714
John McCallacf0ee52010-10-08 02:01:28 +00006715 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006716 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006717 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006718 return;
6719}
6720
David Blaikie18e9ac72012-05-15 21:57:38 +00006721void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6722 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006723 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006724
6725 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006726 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6727 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006728
6729 // If -Wconversion would have warned about either of the candidates
6730 // for a signedness conversion to the context type...
6731 if (!Suspicious) return;
6732
6733 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006734 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006735 return;
6736
John McCallcc7e5bf2010-05-06 08:58:33 +00006737 // ...then check whether it would have warned about either of the
6738 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006739 if (E->getType() == T) return;
6740
6741 Suspicious = false;
6742 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6743 E->getType(), CC, &Suspicious);
6744 if (!Suspicious)
6745 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006746 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006747}
6748
Richard Trieu65724892014-11-15 06:37:39 +00006749/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6750/// Input argument E is a logical expression.
6751static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6752 if (S.getLangOpts().Bool)
6753 return;
6754 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6755}
6756
John McCallcc7e5bf2010-05-06 08:58:33 +00006757/// AnalyzeImplicitConversions - Find and report any interesting
6758/// implicit conversions in the given expression. There are a couple
6759/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006760void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006761 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006762 Expr *E = OrigE->IgnoreParenImpCasts();
6763
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006764 if (E->isTypeDependent() || E->isValueDependent())
6765 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006766
John McCallcc7e5bf2010-05-06 08:58:33 +00006767 // For conditional operators, we analyze the arguments as if they
6768 // were being fed directly into the output.
6769 if (isa<ConditionalOperator>(E)) {
6770 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006771 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006772 return;
6773 }
6774
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006775 // Check implicit argument conversions for function calls.
6776 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6777 CheckImplicitArgumentConversions(S, Call, CC);
6778
John McCallcc7e5bf2010-05-06 08:58:33 +00006779 // Go ahead and check any implicit conversions we might have skipped.
6780 // The non-canonical typecheck is just an optimization;
6781 // CheckImplicitConversion will filter out dead implicit conversions.
6782 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006783 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006784
6785 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006786
6787 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006788 if (POE->getResultExpr())
6789 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006790 }
6791
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00006792 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
6793 if (OVE->getSourceExpr())
6794 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6795 return;
6796 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006797
John McCallcc7e5bf2010-05-06 08:58:33 +00006798 // Skip past explicit casts.
6799 if (isa<ExplicitCastExpr>(E)) {
6800 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006801 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006802 }
6803
John McCalld2a53122010-11-09 23:24:47 +00006804 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6805 // Do a somewhat different check with comparison operators.
6806 if (BO->isComparisonOp())
6807 return AnalyzeComparison(S, BO);
6808
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006809 // And with simple assignments.
6810 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006811 return AnalyzeAssignment(S, BO);
6812 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006813
6814 // These break the otherwise-useful invariant below. Fortunately,
6815 // we don't really need to recurse into them, because any internal
6816 // expressions should have been analyzed already when they were
6817 // built into statements.
6818 if (isa<StmtExpr>(E)) return;
6819
6820 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006821 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006822
6823 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006824 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006825 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006826 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006827 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006828 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006829 if (!ChildExpr)
6830 continue;
6831
Richard Trieu955231d2014-01-25 01:10:35 +00006832 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006833 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006834 // Ignore checking string literals that are in logical and operators.
6835 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006836 continue;
6837 AnalyzeImplicitConversions(S, ChildExpr, CC);
6838 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006839
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006840 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006841 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6842 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006843 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00006844
6845 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6846 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006847 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006848 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006849
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006850 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6851 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00006852 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006853}
6854
6855} // end anonymous namespace
6856
Richard Trieu3bb8b562014-02-26 02:36:06 +00006857enum {
6858 AddressOf,
6859 FunctionPointer,
6860 ArrayPointer
6861};
6862
Richard Trieuc1888e02014-06-28 23:25:37 +00006863// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6864// Returns true when emitting a warning about taking the address of a reference.
6865static bool CheckForReference(Sema &SemaRef, const Expr *E,
6866 PartialDiagnostic PD) {
6867 E = E->IgnoreParenImpCasts();
6868
6869 const FunctionDecl *FD = nullptr;
6870
6871 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6872 if (!DRE->getDecl()->getType()->isReferenceType())
6873 return false;
6874 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6875 if (!M->getMemberDecl()->getType()->isReferenceType())
6876 return false;
6877 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00006878 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00006879 return false;
6880 FD = Call->getDirectCallee();
6881 } else {
6882 return false;
6883 }
6884
6885 SemaRef.Diag(E->getExprLoc(), PD);
6886
6887 // If possible, point to location of function.
6888 if (FD) {
6889 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6890 }
6891
6892 return true;
6893}
6894
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006895// Returns true if the SourceLocation is expanded from any macro body.
6896// Returns false if the SourceLocation is invalid, is from not in a macro
6897// expansion, or is from expanded from a top-level macro argument.
6898static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6899 if (Loc.isInvalid())
6900 return false;
6901
6902 while (Loc.isMacroID()) {
6903 if (SM.isMacroBodyExpansion(Loc))
6904 return true;
6905 Loc = SM.getImmediateMacroCallerLoc(Loc);
6906 }
6907
6908 return false;
6909}
6910
Richard Trieu3bb8b562014-02-26 02:36:06 +00006911/// \brief Diagnose pointers that are always non-null.
6912/// \param E the expression containing the pointer
6913/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6914/// compared to a null pointer
6915/// \param IsEqual True when the comparison is equal to a null pointer
6916/// \param Range Extra SourceRange to highlight in the diagnostic
6917void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6918 Expr::NullPointerConstantKind NullKind,
6919 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006920 if (!E)
6921 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006922
6923 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006924 if (E->getExprLoc().isMacroID()) {
6925 const SourceManager &SM = getSourceManager();
6926 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6927 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006928 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006929 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006930 E = E->IgnoreImpCasts();
6931
6932 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6933
Richard Trieuf7432752014-06-06 21:39:26 +00006934 if (isa<CXXThisExpr>(E)) {
6935 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6936 : diag::warn_this_bool_conversion;
6937 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6938 return;
6939 }
6940
Richard Trieu3bb8b562014-02-26 02:36:06 +00006941 bool IsAddressOf = false;
6942
6943 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6944 if (UO->getOpcode() != UO_AddrOf)
6945 return;
6946 IsAddressOf = true;
6947 E = UO->getSubExpr();
6948 }
6949
Richard Trieuc1888e02014-06-28 23:25:37 +00006950 if (IsAddressOf) {
6951 unsigned DiagID = IsCompare
6952 ? diag::warn_address_of_reference_null_compare
6953 : diag::warn_address_of_reference_bool_conversion;
6954 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6955 << IsEqual;
6956 if (CheckForReference(*this, E, PD)) {
6957 return;
6958 }
6959 }
6960
Richard Trieu3bb8b562014-02-26 02:36:06 +00006961 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006962 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006963 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6964 D = R->getDecl();
6965 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6966 D = M->getMemberDecl();
6967 }
6968
6969 // Weak Decls can be null.
6970 if (!D || D->isWeak())
6971 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006972
6973 // Check for parameter decl with nonnull attribute
6974 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6975 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6976 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6977 unsigned NumArgs = FD->getNumParams();
6978 llvm::SmallBitVector AttrNonNull(NumArgs);
6979 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6980 if (!NonNull->args_size()) {
6981 AttrNonNull.set(0, NumArgs);
6982 break;
6983 }
6984 for (unsigned Val : NonNull->args()) {
6985 if (Val >= NumArgs)
6986 continue;
6987 AttrNonNull.set(Val);
6988 }
6989 }
6990 if (!AttrNonNull.empty())
6991 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00006992 if (FD->getParamDecl(i) == PV &&
6993 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006994 std::string Str;
6995 llvm::raw_string_ostream S(Str);
6996 E->printPretty(S, nullptr, getPrintingPolicy());
6997 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
6998 : diag::warn_cast_nonnull_to_bool;
6999 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7000 << Range << IsEqual;
7001 return;
7002 }
7003 }
7004 }
7005
Richard Trieu3bb8b562014-02-26 02:36:06 +00007006 QualType T = D->getType();
7007 const bool IsArray = T->isArrayType();
7008 const bool IsFunction = T->isFunctionType();
7009
Richard Trieuc1888e02014-06-28 23:25:37 +00007010 // Address of function is used to silence the function warning.
7011 if (IsAddressOf && IsFunction) {
7012 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007013 }
7014
7015 // Found nothing.
7016 if (!IsAddressOf && !IsFunction && !IsArray)
7017 return;
7018
7019 // Pretty print the expression for the diagnostic.
7020 std::string Str;
7021 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007022 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007023
7024 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7025 : diag::warn_impcast_pointer_to_bool;
7026 unsigned DiagType;
7027 if (IsAddressOf)
7028 DiagType = AddressOf;
7029 else if (IsFunction)
7030 DiagType = FunctionPointer;
7031 else if (IsArray)
7032 DiagType = ArrayPointer;
7033 else
7034 llvm_unreachable("Could not determine diagnostic.");
7035 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7036 << Range << IsEqual;
7037
7038 if (!IsFunction)
7039 return;
7040
7041 // Suggest '&' to silence the function warning.
7042 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7043 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7044
7045 // Check to see if '()' fixit should be emitted.
7046 QualType ReturnType;
7047 UnresolvedSet<4> NonTemplateOverloads;
7048 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7049 if (ReturnType.isNull())
7050 return;
7051
7052 if (IsCompare) {
7053 // There are two cases here. If there is null constant, the only suggest
7054 // for a pointer return type. If the null is 0, then suggest if the return
7055 // type is a pointer or an integer type.
7056 if (!ReturnType->isPointerType()) {
7057 if (NullKind == Expr::NPCK_ZeroExpression ||
7058 NullKind == Expr::NPCK_ZeroLiteral) {
7059 if (!ReturnType->isIntegerType())
7060 return;
7061 } else {
7062 return;
7063 }
7064 }
7065 } else { // !IsCompare
7066 // For function to bool, only suggest if the function pointer has bool
7067 // return type.
7068 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7069 return;
7070 }
7071 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007072 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007073}
7074
7075
John McCallcc7e5bf2010-05-06 08:58:33 +00007076/// Diagnoses "dangerous" implicit conversions within the given
7077/// expression (which is a full expression). Implements -Wconversion
7078/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007079///
7080/// \param CC the "context" location of the implicit conversion, i.e.
7081/// the most location of the syntactic entity requiring the implicit
7082/// conversion
7083void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007084 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007085 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007086 return;
7087
7088 // Don't diagnose for value- or type-dependent expressions.
7089 if (E->isTypeDependent() || E->isValueDependent())
7090 return;
7091
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007092 // Check for array bounds violations in cases where the check isn't triggered
7093 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7094 // ArraySubscriptExpr is on the RHS of a variable initialization.
7095 CheckArrayAccess(E);
7096
John McCallacf0ee52010-10-08 02:01:28 +00007097 // This is not the right CC for (e.g.) a variable initialization.
7098 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007099}
7100
Richard Trieu65724892014-11-15 06:37:39 +00007101/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7102/// Input argument E is a logical expression.
7103void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7104 ::CheckBoolLikeConversion(*this, E, CC);
7105}
7106
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007107/// Diagnose when expression is an integer constant expression and its evaluation
7108/// results in integer overflow
7109void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007110 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7111 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007112}
7113
Richard Smithc406cb72013-01-17 01:17:56 +00007114namespace {
7115/// \brief Visitor for expressions which looks for unsequenced operations on the
7116/// same object.
7117class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007118 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7119
Richard Smithc406cb72013-01-17 01:17:56 +00007120 /// \brief A tree of sequenced regions within an expression. Two regions are
7121 /// unsequenced if one is an ancestor or a descendent of the other. When we
7122 /// finish processing an expression with sequencing, such as a comma
7123 /// expression, we fold its tree nodes into its parent, since they are
7124 /// unsequenced with respect to nodes we will visit later.
7125 class SequenceTree {
7126 struct Value {
7127 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7128 unsigned Parent : 31;
7129 bool Merged : 1;
7130 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007131 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007132
7133 public:
7134 /// \brief A region within an expression which may be sequenced with respect
7135 /// to some other region.
7136 class Seq {
7137 explicit Seq(unsigned N) : Index(N) {}
7138 unsigned Index;
7139 friend class SequenceTree;
7140 public:
7141 Seq() : Index(0) {}
7142 };
7143
7144 SequenceTree() { Values.push_back(Value(0)); }
7145 Seq root() const { return Seq(0); }
7146
7147 /// \brief Create a new sequence of operations, which is an unsequenced
7148 /// subset of \p Parent. This sequence of operations is sequenced with
7149 /// respect to other children of \p Parent.
7150 Seq allocate(Seq Parent) {
7151 Values.push_back(Value(Parent.Index));
7152 return Seq(Values.size() - 1);
7153 }
7154
7155 /// \brief Merge a sequence of operations into its parent.
7156 void merge(Seq S) {
7157 Values[S.Index].Merged = true;
7158 }
7159
7160 /// \brief Determine whether two operations are unsequenced. This operation
7161 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7162 /// should have been merged into its parent as appropriate.
7163 bool isUnsequenced(Seq Cur, Seq Old) {
7164 unsigned C = representative(Cur.Index);
7165 unsigned Target = representative(Old.Index);
7166 while (C >= Target) {
7167 if (C == Target)
7168 return true;
7169 C = Values[C].Parent;
7170 }
7171 return false;
7172 }
7173
7174 private:
7175 /// \brief Pick a representative for a sequence.
7176 unsigned representative(unsigned K) {
7177 if (Values[K].Merged)
7178 // Perform path compression as we go.
7179 return Values[K].Parent = representative(Values[K].Parent);
7180 return K;
7181 }
7182 };
7183
7184 /// An object for which we can track unsequenced uses.
7185 typedef NamedDecl *Object;
7186
7187 /// Different flavors of object usage which we track. We only track the
7188 /// least-sequenced usage of each kind.
7189 enum UsageKind {
7190 /// A read of an object. Multiple unsequenced reads are OK.
7191 UK_Use,
7192 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007193 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007194 UK_ModAsValue,
7195 /// A modification of an object which is not sequenced before the value
7196 /// computation of the expression, such as n++.
7197 UK_ModAsSideEffect,
7198
7199 UK_Count = UK_ModAsSideEffect + 1
7200 };
7201
7202 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007203 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007204 Expr *Use;
7205 SequenceTree::Seq Seq;
7206 };
7207
7208 struct UsageInfo {
7209 UsageInfo() : Diagnosed(false) {}
7210 Usage Uses[UK_Count];
7211 /// Have we issued a diagnostic for this variable already?
7212 bool Diagnosed;
7213 };
7214 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7215
7216 Sema &SemaRef;
7217 /// Sequenced regions within the expression.
7218 SequenceTree Tree;
7219 /// Declaration modifications and references which we have seen.
7220 UsageInfoMap UsageMap;
7221 /// The region we are currently within.
7222 SequenceTree::Seq Region;
7223 /// Filled in with declarations which were modified as a side-effect
7224 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007225 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007226 /// Expressions to check later. We defer checking these to reduce
7227 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007228 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007229
7230 /// RAII object wrapping the visitation of a sequenced subexpression of an
7231 /// expression. At the end of this process, the side-effects of the evaluation
7232 /// become sequenced with respect to the value computation of the result, so
7233 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7234 /// UK_ModAsValue.
7235 struct SequencedSubexpression {
7236 SequencedSubexpression(SequenceChecker &Self)
7237 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7238 Self.ModAsSideEffect = &ModAsSideEffect;
7239 }
7240 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007241 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7242 MI != ME; ++MI) {
7243 UsageInfo &U = Self.UsageMap[MI->first];
7244 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7245 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7246 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007247 }
7248 Self.ModAsSideEffect = OldModAsSideEffect;
7249 }
7250
7251 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007252 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7253 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007254 };
7255
Richard Smith40238f02013-06-20 22:21:56 +00007256 /// RAII object wrapping the visitation of a subexpression which we might
7257 /// choose to evaluate as a constant. If any subexpression is evaluated and
7258 /// found to be non-constant, this allows us to suppress the evaluation of
7259 /// the outer expression.
7260 class EvaluationTracker {
7261 public:
7262 EvaluationTracker(SequenceChecker &Self)
7263 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7264 Self.EvalTracker = this;
7265 }
7266 ~EvaluationTracker() {
7267 Self.EvalTracker = Prev;
7268 if (Prev)
7269 Prev->EvalOK &= EvalOK;
7270 }
7271
7272 bool evaluate(const Expr *E, bool &Result) {
7273 if (!EvalOK || E->isValueDependent())
7274 return false;
7275 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7276 return EvalOK;
7277 }
7278
7279 private:
7280 SequenceChecker &Self;
7281 EvaluationTracker *Prev;
7282 bool EvalOK;
7283 } *EvalTracker;
7284
Richard Smithc406cb72013-01-17 01:17:56 +00007285 /// \brief Find the object which is produced by the specified expression,
7286 /// if any.
7287 Object getObject(Expr *E, bool Mod) const {
7288 E = E->IgnoreParenCasts();
7289 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7290 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7291 return getObject(UO->getSubExpr(), Mod);
7292 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7293 if (BO->getOpcode() == BO_Comma)
7294 return getObject(BO->getRHS(), Mod);
7295 if (Mod && BO->isAssignmentOp())
7296 return getObject(BO->getLHS(), Mod);
7297 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7298 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7299 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7300 return ME->getMemberDecl();
7301 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7302 // FIXME: If this is a reference, map through to its value.
7303 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007304 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007305 }
7306
7307 /// \brief Note that an object was modified or used by an expression.
7308 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7309 Usage &U = UI.Uses[UK];
7310 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7311 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7312 ModAsSideEffect->push_back(std::make_pair(O, U));
7313 U.Use = Ref;
7314 U.Seq = Region;
7315 }
7316 }
7317 /// \brief Check whether a modification or use conflicts with a prior usage.
7318 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7319 bool IsModMod) {
7320 if (UI.Diagnosed)
7321 return;
7322
7323 const Usage &U = UI.Uses[OtherKind];
7324 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7325 return;
7326
7327 Expr *Mod = U.Use;
7328 Expr *ModOrUse = Ref;
7329 if (OtherKind == UK_Use)
7330 std::swap(Mod, ModOrUse);
7331
7332 SemaRef.Diag(Mod->getExprLoc(),
7333 IsModMod ? diag::warn_unsequenced_mod_mod
7334 : diag::warn_unsequenced_mod_use)
7335 << O << SourceRange(ModOrUse->getExprLoc());
7336 UI.Diagnosed = true;
7337 }
7338
7339 void notePreUse(Object O, Expr *Use) {
7340 UsageInfo &U = UsageMap[O];
7341 // Uses conflict with other modifications.
7342 checkUsage(O, U, Use, UK_ModAsValue, false);
7343 }
7344 void notePostUse(Object O, Expr *Use) {
7345 UsageInfo &U = UsageMap[O];
7346 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7347 addUsage(U, O, Use, UK_Use);
7348 }
7349
7350 void notePreMod(Object O, Expr *Mod) {
7351 UsageInfo &U = UsageMap[O];
7352 // Modifications conflict with other modifications and with uses.
7353 checkUsage(O, U, Mod, UK_ModAsValue, true);
7354 checkUsage(O, U, Mod, UK_Use, false);
7355 }
7356 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7357 UsageInfo &U = UsageMap[O];
7358 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7359 addUsage(U, O, Use, UK);
7360 }
7361
7362public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007363 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007364 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7365 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007366 Visit(E);
7367 }
7368
7369 void VisitStmt(Stmt *S) {
7370 // Skip all statements which aren't expressions for now.
7371 }
7372
7373 void VisitExpr(Expr *E) {
7374 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007375 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007376 }
7377
7378 void VisitCastExpr(CastExpr *E) {
7379 Object O = Object();
7380 if (E->getCastKind() == CK_LValueToRValue)
7381 O = getObject(E->getSubExpr(), false);
7382
7383 if (O)
7384 notePreUse(O, E);
7385 VisitExpr(E);
7386 if (O)
7387 notePostUse(O, E);
7388 }
7389
7390 void VisitBinComma(BinaryOperator *BO) {
7391 // C++11 [expr.comma]p1:
7392 // Every value computation and side effect associated with the left
7393 // expression is sequenced before every value computation and side
7394 // effect associated with the right expression.
7395 SequenceTree::Seq LHS = Tree.allocate(Region);
7396 SequenceTree::Seq RHS = Tree.allocate(Region);
7397 SequenceTree::Seq OldRegion = Region;
7398
7399 {
7400 SequencedSubexpression SeqLHS(*this);
7401 Region = LHS;
7402 Visit(BO->getLHS());
7403 }
7404
7405 Region = RHS;
7406 Visit(BO->getRHS());
7407
7408 Region = OldRegion;
7409
7410 // Forget that LHS and RHS are sequenced. They are both unsequenced
7411 // with respect to other stuff.
7412 Tree.merge(LHS);
7413 Tree.merge(RHS);
7414 }
7415
7416 void VisitBinAssign(BinaryOperator *BO) {
7417 // The modification is sequenced after the value computation of the LHS
7418 // and RHS, so check it before inspecting the operands and update the
7419 // map afterwards.
7420 Object O = getObject(BO->getLHS(), true);
7421 if (!O)
7422 return VisitExpr(BO);
7423
7424 notePreMod(O, BO);
7425
7426 // C++11 [expr.ass]p7:
7427 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7428 // only once.
7429 //
7430 // Therefore, for a compound assignment operator, O is considered used
7431 // everywhere except within the evaluation of E1 itself.
7432 if (isa<CompoundAssignOperator>(BO))
7433 notePreUse(O, BO);
7434
7435 Visit(BO->getLHS());
7436
7437 if (isa<CompoundAssignOperator>(BO))
7438 notePostUse(O, BO);
7439
7440 Visit(BO->getRHS());
7441
Richard Smith83e37bee2013-06-26 23:16:51 +00007442 // C++11 [expr.ass]p1:
7443 // the assignment is sequenced [...] before the value computation of the
7444 // assignment expression.
7445 // C11 6.5.16/3 has no such rule.
7446 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7447 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007448 }
7449 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7450 VisitBinAssign(CAO);
7451 }
7452
7453 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7454 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7455 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7456 Object O = getObject(UO->getSubExpr(), true);
7457 if (!O)
7458 return VisitExpr(UO);
7459
7460 notePreMod(O, UO);
7461 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007462 // C++11 [expr.pre.incr]p1:
7463 // the expression ++x is equivalent to x+=1
7464 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7465 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007466 }
7467
7468 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7469 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7470 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7471 Object O = getObject(UO->getSubExpr(), true);
7472 if (!O)
7473 return VisitExpr(UO);
7474
7475 notePreMod(O, UO);
7476 Visit(UO->getSubExpr());
7477 notePostMod(O, UO, UK_ModAsSideEffect);
7478 }
7479
7480 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7481 void VisitBinLOr(BinaryOperator *BO) {
7482 // The side-effects of the LHS of an '&&' are sequenced before the
7483 // value computation of the RHS, and hence before the value computation
7484 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7485 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007486 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007487 {
7488 SequencedSubexpression Sequenced(*this);
7489 Visit(BO->getLHS());
7490 }
7491
7492 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007493 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007494 if (!Result)
7495 Visit(BO->getRHS());
7496 } else {
7497 // Check for unsequenced operations in the RHS, treating it as an
7498 // entirely separate evaluation.
7499 //
7500 // FIXME: If there are operations in the RHS which are unsequenced
7501 // with respect to operations outside the RHS, and those operations
7502 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007503 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007504 }
Richard Smithc406cb72013-01-17 01:17:56 +00007505 }
7506 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007507 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007508 {
7509 SequencedSubexpression Sequenced(*this);
7510 Visit(BO->getLHS());
7511 }
7512
7513 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007514 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007515 if (Result)
7516 Visit(BO->getRHS());
7517 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007518 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007519 }
Richard Smithc406cb72013-01-17 01:17:56 +00007520 }
7521
7522 // Only visit the condition, unless we can be sure which subexpression will
7523 // be chosen.
7524 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007525 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007526 {
7527 SequencedSubexpression Sequenced(*this);
7528 Visit(CO->getCond());
7529 }
Richard Smithc406cb72013-01-17 01:17:56 +00007530
7531 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007532 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007533 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007534 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007535 WorkList.push_back(CO->getTrueExpr());
7536 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007537 }
Richard Smithc406cb72013-01-17 01:17:56 +00007538 }
7539
Richard Smithe3dbfe02013-06-30 10:40:20 +00007540 void VisitCallExpr(CallExpr *CE) {
7541 // C++11 [intro.execution]p15:
7542 // When calling a function [...], every value computation and side effect
7543 // associated with any argument expression, or with the postfix expression
7544 // designating the called function, is sequenced before execution of every
7545 // expression or statement in the body of the function [and thus before
7546 // the value computation of its result].
7547 SequencedSubexpression Sequenced(*this);
7548 Base::VisitCallExpr(CE);
7549
7550 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7551 }
7552
Richard Smithc406cb72013-01-17 01:17:56 +00007553 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007554 // This is a call, so all subexpressions are sequenced before the result.
7555 SequencedSubexpression Sequenced(*this);
7556
Richard Smithc406cb72013-01-17 01:17:56 +00007557 if (!CCE->isListInitialization())
7558 return VisitExpr(CCE);
7559
7560 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007561 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007562 SequenceTree::Seq Parent = Region;
7563 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7564 E = CCE->arg_end();
7565 I != E; ++I) {
7566 Region = Tree.allocate(Parent);
7567 Elts.push_back(Region);
7568 Visit(*I);
7569 }
7570
7571 // Forget that the initializers are sequenced.
7572 Region = Parent;
7573 for (unsigned I = 0; I < Elts.size(); ++I)
7574 Tree.merge(Elts[I]);
7575 }
7576
7577 void VisitInitListExpr(InitListExpr *ILE) {
7578 if (!SemaRef.getLangOpts().CPlusPlus11)
7579 return VisitExpr(ILE);
7580
7581 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007582 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007583 SequenceTree::Seq Parent = Region;
7584 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7585 Expr *E = ILE->getInit(I);
7586 if (!E) continue;
7587 Region = Tree.allocate(Parent);
7588 Elts.push_back(Region);
7589 Visit(E);
7590 }
7591
7592 // Forget that the initializers are sequenced.
7593 Region = Parent;
7594 for (unsigned I = 0; I < Elts.size(); ++I)
7595 Tree.merge(Elts[I]);
7596 }
7597};
7598}
7599
7600void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007601 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007602 WorkList.push_back(E);
7603 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007604 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007605 SequenceChecker(*this, Item, WorkList);
7606 }
Richard Smithc406cb72013-01-17 01:17:56 +00007607}
7608
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007609void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7610 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007611 CheckImplicitConversions(E, CheckLoc);
7612 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007613 if (!IsConstexpr && !E->isValueDependent())
7614 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007615}
7616
John McCall1f425642010-11-11 03:21:53 +00007617void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7618 FieldDecl *BitField,
7619 Expr *Init) {
7620 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7621}
7622
Mike Stump0c2ec772010-01-21 03:59:47 +00007623/// CheckParmsForFunctionDef - Check that the parameters of the given
7624/// function are appropriate for the definition of a function. This
7625/// takes care of any checks that cannot be performed on the
7626/// declaration itself, e.g., that the types of each of the function
7627/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007628bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7629 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007630 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007631 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007632 for (; P != PEnd; ++P) {
7633 ParmVarDecl *Param = *P;
7634
Mike Stump0c2ec772010-01-21 03:59:47 +00007635 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7636 // function declarator that is part of a function definition of
7637 // that function shall not have incomplete type.
7638 //
7639 // This is also C++ [dcl.fct]p6.
7640 if (!Param->isInvalidDecl() &&
7641 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007642 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007643 Param->setInvalidDecl();
7644 HasInvalidParm = true;
7645 }
7646
7647 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7648 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007649 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007650 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007651 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007652 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007653 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007654
7655 // C99 6.7.5.3p12:
7656 // If the function declarator is not part of a definition of that
7657 // function, parameters may have incomplete type and may use the [*]
7658 // notation in their sequences of declarator specifiers to specify
7659 // variable length array types.
7660 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007661 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007662 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007663 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007664 // information is added for it.
7665 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007666 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007667 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007668 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007669 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007670
7671 // MSVC destroys objects passed by value in the callee. Therefore a
7672 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007673 // object's destructor. However, we don't perform any direct access check
7674 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007675 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7676 .getCXXABI()
7677 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007678 if (!Param->isInvalidDecl()) {
7679 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7680 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7681 if (!ClassDecl->isInvalidDecl() &&
7682 !ClassDecl->hasIrrelevantDestructor() &&
7683 !ClassDecl->isDependentContext()) {
7684 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7685 MarkFunctionReferenced(Param->getLocation(), Destructor);
7686 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7687 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007688 }
7689 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007690 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007691 }
7692
7693 return HasInvalidParm;
7694}
John McCall2b5c1b22010-08-12 21:44:57 +00007695
7696/// CheckCastAlign - Implements -Wcast-align, which warns when a
7697/// pointer cast increases the alignment requirements.
7698void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7699 // This is actually a lot of work to potentially be doing on every
7700 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007701 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007702 return;
7703
7704 // Ignore dependent types.
7705 if (T->isDependentType() || Op->getType()->isDependentType())
7706 return;
7707
7708 // Require that the destination be a pointer type.
7709 const PointerType *DestPtr = T->getAs<PointerType>();
7710 if (!DestPtr) return;
7711
7712 // If the destination has alignment 1, we're done.
7713 QualType DestPointee = DestPtr->getPointeeType();
7714 if (DestPointee->isIncompleteType()) return;
7715 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7716 if (DestAlign.isOne()) return;
7717
7718 // Require that the source be a pointer type.
7719 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7720 if (!SrcPtr) return;
7721 QualType SrcPointee = SrcPtr->getPointeeType();
7722
7723 // Whitelist casts from cv void*. We already implicitly
7724 // whitelisted casts to cv void*, since they have alignment 1.
7725 // Also whitelist casts involving incomplete types, which implicitly
7726 // includes 'void'.
7727 if (SrcPointee->isIncompleteType()) return;
7728
7729 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7730 if (SrcAlign >= DestAlign) return;
7731
7732 Diag(TRange.getBegin(), diag::warn_cast_align)
7733 << Op->getType() << T
7734 << static_cast<unsigned>(SrcAlign.getQuantity())
7735 << static_cast<unsigned>(DestAlign.getQuantity())
7736 << TRange << Op->getSourceRange();
7737}
7738
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007739static const Type* getElementType(const Expr *BaseExpr) {
7740 const Type* EltType = BaseExpr->getType().getTypePtr();
7741 if (EltType->isAnyPointerType())
7742 return EltType->getPointeeType().getTypePtr();
7743 else if (EltType->isArrayType())
7744 return EltType->getBaseElementTypeUnsafe();
7745 return EltType;
7746}
7747
Chandler Carruth28389f02011-08-05 09:10:50 +00007748/// \brief Check whether this array fits the idiom of a size-one tail padded
7749/// array member of a struct.
7750///
7751/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7752/// commonly used to emulate flexible arrays in C89 code.
7753static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7754 const NamedDecl *ND) {
7755 if (Size != 1 || !ND) return false;
7756
7757 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7758 if (!FD) return false;
7759
7760 // Don't consider sizes resulting from macro expansions or template argument
7761 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007762
7763 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007764 while (TInfo) {
7765 TypeLoc TL = TInfo->getTypeLoc();
7766 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007767 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7768 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007769 TInfo = TDL->getTypeSourceInfo();
7770 continue;
7771 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007772 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7773 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007774 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7775 return false;
7776 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007777 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007778 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007779
7780 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007781 if (!RD) return false;
7782 if (RD->isUnion()) return false;
7783 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7784 if (!CRD->isStandardLayout()) return false;
7785 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007786
Benjamin Kramer8c543672011-08-06 03:04:42 +00007787 // See if this is the last field decl in the record.
7788 const Decl *D = FD;
7789 while ((D = D->getNextDeclInContext()))
7790 if (isa<FieldDecl>(D))
7791 return false;
7792 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007793}
7794
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007795void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007796 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007797 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007798 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007799 if (IndexExpr->isValueDependent())
7800 return;
7801
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007802 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007803 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007804 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007805 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007806 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007807 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007808
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007809 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007810 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007811 return;
Richard Smith13f67182011-12-16 19:31:14 +00007812 if (IndexNegated)
7813 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007814
Craig Topperc3ec1492014-05-26 06:22:03 +00007815 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007816 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7817 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007818 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007819 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007820
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007821 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007822 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007823 if (!size.isStrictlyPositive())
7824 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007825
7826 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007827 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007828 // Make sure we're comparing apples to apples when comparing index to size
7829 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7830 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007831 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007832 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007833 if (ptrarith_typesize != array_typesize) {
7834 // There's a cast to a different size type involved
7835 uint64_t ratio = array_typesize / ptrarith_typesize;
7836 // TODO: Be smarter about handling cases where array_typesize is not a
7837 // multiple of ptrarith_typesize
7838 if (ptrarith_typesize * ratio == array_typesize)
7839 size *= llvm::APInt(size.getBitWidth(), ratio);
7840 }
7841 }
7842
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007843 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007844 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007845 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007846 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007847
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007848 // For array subscripting the index must be less than size, but for pointer
7849 // arithmetic also allow the index (offset) to be equal to size since
7850 // computing the next address after the end of the array is legal and
7851 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007852 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007853 return;
7854
7855 // Also don't warn for arrays of size 1 which are members of some
7856 // structure. These are often used to approximate flexible arrays in C89
7857 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007858 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007859 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007860
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007861 // Suppress the warning if the subscript expression (as identified by the
7862 // ']' location) and the index expression are both from macro expansions
7863 // within a system header.
7864 if (ASE) {
7865 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7866 ASE->getRBracketLoc());
7867 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7868 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7869 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007870 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007871 return;
7872 }
7873 }
7874
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007875 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007876 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007877 DiagID = diag::warn_array_index_exceeds_bounds;
7878
7879 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7880 PDiag(DiagID) << index.toString(10, true)
7881 << size.toString(10, true)
7882 << (unsigned)size.getLimitedValue(~0U)
7883 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007884 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007885 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007886 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007887 DiagID = diag::warn_ptr_arith_precedes_bounds;
7888 if (index.isNegative()) index = -index;
7889 }
7890
7891 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7892 PDiag(DiagID) << index.toString(10, true)
7893 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007894 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007895
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007896 if (!ND) {
7897 // Try harder to find a NamedDecl to point at in the note.
7898 while (const ArraySubscriptExpr *ASE =
7899 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7900 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7901 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7902 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7903 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7904 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7905 }
7906
Chandler Carruth1af88f12011-02-17 21:10:52 +00007907 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007908 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7909 PDiag(diag::note_array_index_out_of_bounds)
7910 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007911}
7912
Ted Kremenekdf26df72011-03-01 18:41:00 +00007913void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007914 int AllowOnePastEnd = 0;
7915 while (expr) {
7916 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007917 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007918 case Stmt::ArraySubscriptExprClass: {
7919 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007920 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007921 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007922 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007923 }
7924 case Stmt::UnaryOperatorClass: {
7925 // Only unwrap the * and & unary operators
7926 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7927 expr = UO->getSubExpr();
7928 switch (UO->getOpcode()) {
7929 case UO_AddrOf:
7930 AllowOnePastEnd++;
7931 break;
7932 case UO_Deref:
7933 AllowOnePastEnd--;
7934 break;
7935 default:
7936 return;
7937 }
7938 break;
7939 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007940 case Stmt::ConditionalOperatorClass: {
7941 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7942 if (const Expr *lhs = cond->getLHS())
7943 CheckArrayAccess(lhs);
7944 if (const Expr *rhs = cond->getRHS())
7945 CheckArrayAccess(rhs);
7946 return;
7947 }
7948 default:
7949 return;
7950 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007951 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007952}
John McCall31168b02011-06-15 23:02:42 +00007953
7954//===--- CHECK: Objective-C retain cycles ----------------------------------//
7955
7956namespace {
7957 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007958 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007959 VarDecl *Variable;
7960 SourceRange Range;
7961 SourceLocation Loc;
7962 bool Indirect;
7963
7964 void setLocsFrom(Expr *e) {
7965 Loc = e->getExprLoc();
7966 Range = e->getSourceRange();
7967 }
7968 };
7969}
7970
7971/// Consider whether capturing the given variable can possibly lead to
7972/// a retain cycle.
7973static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007974 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007975 // lifetime. In MRR, it's captured strongly if the variable is
7976 // __block and has an appropriate type.
7977 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7978 return false;
7979
7980 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007981 if (ref)
7982 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007983 return true;
7984}
7985
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007986static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007987 while (true) {
7988 e = e->IgnoreParens();
7989 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7990 switch (cast->getCastKind()) {
7991 case CK_BitCast:
7992 case CK_LValueBitCast:
7993 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007994 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007995 e = cast->getSubExpr();
7996 continue;
7997
John McCall31168b02011-06-15 23:02:42 +00007998 default:
7999 return false;
8000 }
8001 }
8002
8003 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8004 ObjCIvarDecl *ivar = ref->getDecl();
8005 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8006 return false;
8007
8008 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008009 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008010 return false;
8011
8012 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8013 owner.Indirect = true;
8014 return true;
8015 }
8016
8017 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8018 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8019 if (!var) return false;
8020 return considerVariable(var, ref, owner);
8021 }
8022
John McCall31168b02011-06-15 23:02:42 +00008023 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8024 if (member->isArrow()) return false;
8025
8026 // Don't count this as an indirect ownership.
8027 e = member->getBase();
8028 continue;
8029 }
8030
John McCallfe96e0b2011-11-06 09:01:30 +00008031 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8032 // Only pay attention to pseudo-objects on property references.
8033 ObjCPropertyRefExpr *pre
8034 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8035 ->IgnoreParens());
8036 if (!pre) return false;
8037 if (pre->isImplicitProperty()) return false;
8038 ObjCPropertyDecl *property = pre->getExplicitProperty();
8039 if (!property->isRetaining() &&
8040 !(property->getPropertyIvarDecl() &&
8041 property->getPropertyIvarDecl()->getType()
8042 .getObjCLifetime() == Qualifiers::OCL_Strong))
8043 return false;
8044
8045 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008046 if (pre->isSuperReceiver()) {
8047 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8048 if (!owner.Variable)
8049 return false;
8050 owner.Loc = pre->getLocation();
8051 owner.Range = pre->getSourceRange();
8052 return true;
8053 }
John McCallfe96e0b2011-11-06 09:01:30 +00008054 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8055 ->getSourceExpr());
8056 continue;
8057 }
8058
John McCall31168b02011-06-15 23:02:42 +00008059 // Array ivars?
8060
8061 return false;
8062 }
8063}
8064
8065namespace {
8066 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8067 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8068 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008069 Context(Context), Variable(variable), Capturer(nullptr),
8070 VarWillBeReased(false) {}
8071 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008072 VarDecl *Variable;
8073 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008074 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008075
8076 void VisitDeclRefExpr(DeclRefExpr *ref) {
8077 if (ref->getDecl() == Variable && !Capturer)
8078 Capturer = ref;
8079 }
8080
John McCall31168b02011-06-15 23:02:42 +00008081 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8082 if (Capturer) return;
8083 Visit(ref->getBase());
8084 if (Capturer && ref->isFreeIvar())
8085 Capturer = ref;
8086 }
8087
8088 void VisitBlockExpr(BlockExpr *block) {
8089 // Look inside nested blocks
8090 if (block->getBlockDecl()->capturesVariable(Variable))
8091 Visit(block->getBlockDecl()->getBody());
8092 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008093
8094 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8095 if (Capturer) return;
8096 if (OVE->getSourceExpr())
8097 Visit(OVE->getSourceExpr());
8098 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008099 void VisitBinaryOperator(BinaryOperator *BinOp) {
8100 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8101 return;
8102 Expr *LHS = BinOp->getLHS();
8103 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8104 if (DRE->getDecl() != Variable)
8105 return;
8106 if (Expr *RHS = BinOp->getRHS()) {
8107 RHS = RHS->IgnoreParenCasts();
8108 llvm::APSInt Value;
8109 VarWillBeReased =
8110 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8111 }
8112 }
8113 }
John McCall31168b02011-06-15 23:02:42 +00008114 };
8115}
8116
8117/// Check whether the given argument is a block which captures a
8118/// variable.
8119static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8120 assert(owner.Variable && owner.Loc.isValid());
8121
8122 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008123
8124 // Look through [^{...} copy] and Block_copy(^{...}).
8125 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8126 Selector Cmd = ME->getSelector();
8127 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8128 e = ME->getInstanceReceiver();
8129 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008130 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008131 e = e->IgnoreParenCasts();
8132 }
8133 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8134 if (CE->getNumArgs() == 1) {
8135 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008136 if (Fn) {
8137 const IdentifierInfo *FnI = Fn->getIdentifier();
8138 if (FnI && FnI->isStr("_Block_copy")) {
8139 e = CE->getArg(0)->IgnoreParenCasts();
8140 }
8141 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008142 }
8143 }
8144
John McCall31168b02011-06-15 23:02:42 +00008145 BlockExpr *block = dyn_cast<BlockExpr>(e);
8146 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008147 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008148
8149 FindCaptureVisitor visitor(S.Context, owner.Variable);
8150 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008151 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008152}
8153
8154static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8155 RetainCycleOwner &owner) {
8156 assert(capturer);
8157 assert(owner.Variable && owner.Loc.isValid());
8158
8159 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8160 << owner.Variable << capturer->getSourceRange();
8161 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8162 << owner.Indirect << owner.Range;
8163}
8164
8165/// Check for a keyword selector that starts with the word 'add' or
8166/// 'set'.
8167static bool isSetterLikeSelector(Selector sel) {
8168 if (sel.isUnarySelector()) return false;
8169
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008170 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008171 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008172 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008173 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008174 else if (str.startswith("add")) {
8175 // Specially whitelist 'addOperationWithBlock:'.
8176 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8177 return false;
8178 str = str.substr(3);
8179 }
John McCall31168b02011-06-15 23:02:42 +00008180 else
8181 return false;
8182
8183 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008184 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008185}
8186
Benjamin Kramer3a743452015-03-09 15:03:32 +00008187static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8188 ObjCMessageExpr *Message) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008189 if (S.NSMutableArrayPointer.isNull()) {
8190 IdentifierInfo *NSMutableArrayId =
8191 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableArray);
8192 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableArrayId,
8193 Message->getLocStart(),
8194 Sema::LookupOrdinaryName);
8195 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8196 if (!InterfaceDecl) {
8197 return None;
8198 }
8199 QualType NSMutableArrayObject =
8200 S.Context.getObjCInterfaceType(InterfaceDecl);
8201 S.NSMutableArrayPointer =
8202 S.Context.getObjCObjectPointerType(NSMutableArrayObject);
8203 }
8204
8205 if (S.NSMutableArrayPointer != Message->getReceiverType()) {
8206 return None;
8207 }
8208
8209 Selector Sel = Message->getSelector();
8210
8211 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8212 S.NSAPIObj->getNSArrayMethodKind(Sel);
8213 if (!MKOpt) {
8214 return None;
8215 }
8216
8217 NSAPI::NSArrayMethodKind MK = *MKOpt;
8218
8219 switch (MK) {
8220 case NSAPI::NSMutableArr_addObject:
8221 case NSAPI::NSMutableArr_insertObjectAtIndex:
8222 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8223 return 0;
8224 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8225 return 1;
8226
8227 default:
8228 return None;
8229 }
8230
8231 return None;
8232}
8233
8234static
8235Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8236 ObjCMessageExpr *Message) {
8237
8238 if (S.NSMutableDictionaryPointer.isNull()) {
8239 IdentifierInfo *NSMutableDictionaryId =
8240 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableDictionary);
8241 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableDictionaryId,
8242 Message->getLocStart(),
8243 Sema::LookupOrdinaryName);
8244 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8245 if (!InterfaceDecl) {
8246 return None;
8247 }
8248 QualType NSMutableDictionaryObject =
8249 S.Context.getObjCInterfaceType(InterfaceDecl);
8250 S.NSMutableDictionaryPointer =
8251 S.Context.getObjCObjectPointerType(NSMutableDictionaryObject);
8252 }
8253
8254 if (S.NSMutableDictionaryPointer != Message->getReceiverType()) {
8255 return None;
8256 }
8257
8258 Selector Sel = Message->getSelector();
8259
8260 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8261 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8262 if (!MKOpt) {
8263 return None;
8264 }
8265
8266 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8267
8268 switch (MK) {
8269 case NSAPI::NSMutableDict_setObjectForKey:
8270 case NSAPI::NSMutableDict_setValueForKey:
8271 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8272 return 0;
8273
8274 default:
8275 return None;
8276 }
8277
8278 return None;
8279}
8280
8281static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
8282
8283 ObjCInterfaceDecl *InterfaceDecl;
8284 if (S.NSMutableSetPointer.isNull()) {
8285 IdentifierInfo *NSMutableSetId =
8286 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableSet);
8287 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableSetId,
8288 Message->getLocStart(),
8289 Sema::LookupOrdinaryName);
8290 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8291 if (InterfaceDecl) {
8292 QualType NSMutableSetObject =
8293 S.Context.getObjCInterfaceType(InterfaceDecl);
8294 S.NSMutableSetPointer =
8295 S.Context.getObjCObjectPointerType(NSMutableSetObject);
8296 }
8297 }
8298
8299 if (S.NSCountedSetPointer.isNull()) {
8300 IdentifierInfo *NSCountedSetId =
8301 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSCountedSet);
8302 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSCountedSetId,
8303 Message->getLocStart(),
8304 Sema::LookupOrdinaryName);
8305 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8306 if (InterfaceDecl) {
8307 QualType NSCountedSetObject =
8308 S.Context.getObjCInterfaceType(InterfaceDecl);
8309 S.NSCountedSetPointer =
8310 S.Context.getObjCObjectPointerType(NSCountedSetObject);
8311 }
8312 }
8313
8314 if (S.NSMutableOrderedSetPointer.isNull()) {
8315 IdentifierInfo *NSOrderedSetId =
8316 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableOrderedSet);
8317 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSOrderedSetId,
8318 Message->getLocStart(),
8319 Sema::LookupOrdinaryName);
8320 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8321 if (InterfaceDecl) {
8322 QualType NSOrderedSetObject =
8323 S.Context.getObjCInterfaceType(InterfaceDecl);
8324 S.NSMutableOrderedSetPointer =
8325 S.Context.getObjCObjectPointerType(NSOrderedSetObject);
8326 }
8327 }
8328
8329 QualType ReceiverType = Message->getReceiverType();
8330
8331 bool IsMutableSet = !S.NSMutableSetPointer.isNull() &&
8332 ReceiverType == S.NSMutableSetPointer;
8333 bool IsMutableOrderedSet = !S.NSMutableOrderedSetPointer.isNull() &&
8334 ReceiverType == S.NSMutableOrderedSetPointer;
8335 bool IsCountedSet = !S.NSCountedSetPointer.isNull() &&
8336 ReceiverType == S.NSCountedSetPointer;
8337
8338 if (!IsMutableSet && !IsMutableOrderedSet && !IsCountedSet) {
8339 return None;
8340 }
8341
8342 Selector Sel = Message->getSelector();
8343
8344 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8345 if (!MKOpt) {
8346 return None;
8347 }
8348
8349 NSAPI::NSSetMethodKind MK = *MKOpt;
8350
8351 switch (MK) {
8352 case NSAPI::NSMutableSet_addObject:
8353 case NSAPI::NSOrderedSet_setObjectAtIndex:
8354 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8355 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8356 return 0;
8357 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8358 return 1;
8359 }
8360
8361 return None;
8362}
8363
8364void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8365 if (!Message->isInstanceMessage()) {
8366 return;
8367 }
8368
8369 Optional<int> ArgOpt;
8370
8371 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8372 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8373 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8374 return;
8375 }
8376
8377 int ArgIndex = *ArgOpt;
8378
8379 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8380 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
8381 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
8382 }
8383
8384 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8385 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8386 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8387 }
8388
8389 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8390 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8391 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
8392 ValueDecl *Decl = ReceiverRE->getDecl();
8393 Diag(Message->getSourceRange().getBegin(),
8394 diag::warn_objc_circular_container)
8395 << Decl->getName();
8396 Diag(Decl->getLocation(),
8397 diag::note_objc_circular_container_declared_here)
8398 << Decl->getName();
8399 }
8400 }
8401 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
8402 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
8403 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
8404 ObjCIvarDecl *Decl = IvarRE->getDecl();
8405 Diag(Message->getSourceRange().getBegin(),
8406 diag::warn_objc_circular_container)
8407 << Decl->getName();
8408 Diag(Decl->getLocation(),
8409 diag::note_objc_circular_container_declared_here)
8410 << Decl->getName();
8411 }
8412 }
8413 }
8414
8415}
8416
John McCall31168b02011-06-15 23:02:42 +00008417/// Check a message send to see if it's likely to cause a retain cycle.
8418void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8419 // Only check instance methods whose selector looks like a setter.
8420 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8421 return;
8422
8423 // Try to find a variable that the receiver is strongly owned by.
8424 RetainCycleOwner owner;
8425 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008426 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008427 return;
8428 } else {
8429 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8430 owner.Variable = getCurMethodDecl()->getSelfDecl();
8431 owner.Loc = msg->getSuperLoc();
8432 owner.Range = msg->getSuperLoc();
8433 }
8434
8435 // Check whether the receiver is captured by any of the arguments.
8436 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8437 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8438 return diagnoseRetainCycle(*this, capturer, owner);
8439}
8440
8441/// Check a property assign to see if it's likely to cause a retain cycle.
8442void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8443 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008444 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008445 return;
8446
8447 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8448 diagnoseRetainCycle(*this, capturer, owner);
8449}
8450
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008451void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8452 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008453 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008454 return;
8455
8456 // Because we don't have an expression for the variable, we have to set the
8457 // location explicitly here.
8458 Owner.Loc = Var->getLocation();
8459 Owner.Range = Var->getSourceRange();
8460
8461 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8462 diagnoseRetainCycle(*this, Capturer, Owner);
8463}
8464
Ted Kremenek9304da92012-12-21 08:04:28 +00008465static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8466 Expr *RHS, bool isProperty) {
8467 // Check if RHS is an Objective-C object literal, which also can get
8468 // immediately zapped in a weak reference. Note that we explicitly
8469 // allow ObjCStringLiterals, since those are designed to never really die.
8470 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008471
Ted Kremenek64873352012-12-21 22:46:35 +00008472 // This enum needs to match with the 'select' in
8473 // warn_objc_arc_literal_assign (off-by-1).
8474 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8475 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8476 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008477
8478 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008479 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008480 << (isProperty ? 0 : 1)
8481 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008482
8483 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008484}
8485
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008486static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8487 Qualifiers::ObjCLifetime LT,
8488 Expr *RHS, bool isProperty) {
8489 // Strip off any implicit cast added to get to the one ARC-specific.
8490 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8491 if (cast->getCastKind() == CK_ARCConsumeObject) {
8492 S.Diag(Loc, diag::warn_arc_retained_assign)
8493 << (LT == Qualifiers::OCL_ExplicitNone)
8494 << (isProperty ? 0 : 1)
8495 << RHS->getSourceRange();
8496 return true;
8497 }
8498 RHS = cast->getSubExpr();
8499 }
8500
8501 if (LT == Qualifiers::OCL_Weak &&
8502 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8503 return true;
8504
8505 return false;
8506}
8507
Ted Kremenekb36234d2012-12-21 08:04:20 +00008508bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8509 QualType LHS, Expr *RHS) {
8510 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8511
8512 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8513 return false;
8514
8515 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8516 return true;
8517
8518 return false;
8519}
8520
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008521void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8522 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008523 QualType LHSType;
8524 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008525 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008526 ObjCPropertyRefExpr *PRE
8527 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8528 if (PRE && !PRE->isImplicitProperty()) {
8529 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8530 if (PD)
8531 LHSType = PD->getType();
8532 }
8533
8534 if (LHSType.isNull())
8535 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008536
8537 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8538
8539 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008540 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008541 getCurFunction()->markSafeWeakUse(LHS);
8542 }
8543
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008544 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8545 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008546
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008547 // FIXME. Check for other life times.
8548 if (LT != Qualifiers::OCL_None)
8549 return;
8550
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008551 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008552 if (PRE->isImplicitProperty())
8553 return;
8554 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8555 if (!PD)
8556 return;
8557
Bill Wendling44426052012-12-20 19:22:21 +00008558 unsigned Attributes = PD->getPropertyAttributes();
8559 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008560 // when 'assign' attribute was not explicitly specified
8561 // by user, ignore it and rely on property type itself
8562 // for lifetime info.
8563 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8564 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8565 LHSType->isObjCRetainableType())
8566 return;
8567
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008568 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008569 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008570 Diag(Loc, diag::warn_arc_retained_property_assign)
8571 << RHS->getSourceRange();
8572 return;
8573 }
8574 RHS = cast->getSubExpr();
8575 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008576 }
Bill Wendling44426052012-12-20 19:22:21 +00008577 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008578 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8579 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008580 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008581 }
8582}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008583
8584//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8585
8586namespace {
8587bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8588 SourceLocation StmtLoc,
8589 const NullStmt *Body) {
8590 // Do not warn if the body is a macro that expands to nothing, e.g:
8591 //
8592 // #define CALL(x)
8593 // if (condition)
8594 // CALL(0);
8595 //
8596 if (Body->hasLeadingEmptyMacro())
8597 return false;
8598
8599 // Get line numbers of statement and body.
8600 bool StmtLineInvalid;
8601 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8602 &StmtLineInvalid);
8603 if (StmtLineInvalid)
8604 return false;
8605
8606 bool BodyLineInvalid;
8607 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8608 &BodyLineInvalid);
8609 if (BodyLineInvalid)
8610 return false;
8611
8612 // Warn if null statement and body are on the same line.
8613 if (StmtLine != BodyLine)
8614 return false;
8615
8616 return true;
8617}
8618} // Unnamed namespace
8619
8620void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8621 const Stmt *Body,
8622 unsigned DiagID) {
8623 // Since this is a syntactic check, don't emit diagnostic for template
8624 // instantiations, this just adds noise.
8625 if (CurrentInstantiationScope)
8626 return;
8627
8628 // The body should be a null statement.
8629 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8630 if (!NBody)
8631 return;
8632
8633 // Do the usual checks.
8634 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8635 return;
8636
8637 Diag(NBody->getSemiLoc(), DiagID);
8638 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8639}
8640
8641void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8642 const Stmt *PossibleBody) {
8643 assert(!CurrentInstantiationScope); // Ensured by caller
8644
8645 SourceLocation StmtLoc;
8646 const Stmt *Body;
8647 unsigned DiagID;
8648 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8649 StmtLoc = FS->getRParenLoc();
8650 Body = FS->getBody();
8651 DiagID = diag::warn_empty_for_body;
8652 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8653 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8654 Body = WS->getBody();
8655 DiagID = diag::warn_empty_while_body;
8656 } else
8657 return; // Neither `for' nor `while'.
8658
8659 // The body should be a null statement.
8660 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8661 if (!NBody)
8662 return;
8663
8664 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008665 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008666 return;
8667
8668 // Do the usual checks.
8669 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8670 return;
8671
8672 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8673 // noise level low, emit diagnostics only if for/while is followed by a
8674 // CompoundStmt, e.g.:
8675 // for (int i = 0; i < n; i++);
8676 // {
8677 // a(i);
8678 // }
8679 // or if for/while is followed by a statement with more indentation
8680 // than for/while itself:
8681 // for (int i = 0; i < n; i++);
8682 // a(i);
8683 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8684 if (!ProbableTypo) {
8685 bool BodyColInvalid;
8686 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8687 PossibleBody->getLocStart(),
8688 &BodyColInvalid);
8689 if (BodyColInvalid)
8690 return;
8691
8692 bool StmtColInvalid;
8693 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8694 S->getLocStart(),
8695 &StmtColInvalid);
8696 if (StmtColInvalid)
8697 return;
8698
8699 if (BodyCol > StmtCol)
8700 ProbableTypo = true;
8701 }
8702
8703 if (ProbableTypo) {
8704 Diag(NBody->getSemiLoc(), DiagID);
8705 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8706 }
8707}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008708
Richard Trieu36d0b2b2015-01-13 02:32:02 +00008709//===--- CHECK: Warn on self move with std::move. -------------------------===//
8710
8711/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8712void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8713 SourceLocation OpLoc) {
8714
8715 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8716 return;
8717
8718 if (!ActiveTemplateInstantiations.empty())
8719 return;
8720
8721 // Strip parens and casts away.
8722 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8723 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8724
8725 // Check for a call expression
8726 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8727 if (!CE || CE->getNumArgs() != 1)
8728 return;
8729
8730 // Check for a call to std::move
8731 const FunctionDecl *FD = CE->getDirectCallee();
8732 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8733 !FD->getIdentifier()->isStr("move"))
8734 return;
8735
8736 // Get argument from std::move
8737 RHSExpr = CE->getArg(0);
8738
8739 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8740 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8741
8742 // Two DeclRefExpr's, check that the decls are the same.
8743 if (LHSDeclRef && RHSDeclRef) {
8744 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8745 return;
8746 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8747 RHSDeclRef->getDecl()->getCanonicalDecl())
8748 return;
8749
8750 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8751 << LHSExpr->getSourceRange()
8752 << RHSExpr->getSourceRange();
8753 return;
8754 }
8755
8756 // Member variables require a different approach to check for self moves.
8757 // MemberExpr's are the same if every nested MemberExpr refers to the same
8758 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8759 // the base Expr's are CXXThisExpr's.
8760 const Expr *LHSBase = LHSExpr;
8761 const Expr *RHSBase = RHSExpr;
8762 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8763 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8764 if (!LHSME || !RHSME)
8765 return;
8766
8767 while (LHSME && RHSME) {
8768 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8769 RHSME->getMemberDecl()->getCanonicalDecl())
8770 return;
8771
8772 LHSBase = LHSME->getBase();
8773 RHSBase = RHSME->getBase();
8774 LHSME = dyn_cast<MemberExpr>(LHSBase);
8775 RHSME = dyn_cast<MemberExpr>(RHSBase);
8776 }
8777
8778 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8779 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8780 if (LHSDeclRef && RHSDeclRef) {
8781 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8782 return;
8783 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8784 RHSDeclRef->getDecl()->getCanonicalDecl())
8785 return;
8786
8787 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8788 << LHSExpr->getSourceRange()
8789 << RHSExpr->getSourceRange();
8790 return;
8791 }
8792
8793 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8794 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8795 << LHSExpr->getSourceRange()
8796 << RHSExpr->getSourceRange();
8797}
8798
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008799//===--- Layout compatibility ----------------------------------------------//
8800
8801namespace {
8802
8803bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8804
8805/// \brief Check if two enumeration types are layout-compatible.
8806bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8807 // C++11 [dcl.enum] p8:
8808 // Two enumeration types are layout-compatible if they have the same
8809 // underlying type.
8810 return ED1->isComplete() && ED2->isComplete() &&
8811 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8812}
8813
8814/// \brief Check if two fields are layout-compatible.
8815bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8816 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8817 return false;
8818
8819 if (Field1->isBitField() != Field2->isBitField())
8820 return false;
8821
8822 if (Field1->isBitField()) {
8823 // Make sure that the bit-fields are the same length.
8824 unsigned Bits1 = Field1->getBitWidthValue(C);
8825 unsigned Bits2 = Field2->getBitWidthValue(C);
8826
8827 if (Bits1 != Bits2)
8828 return false;
8829 }
8830
8831 return true;
8832}
8833
8834/// \brief Check if two standard-layout structs are layout-compatible.
8835/// (C++11 [class.mem] p17)
8836bool isLayoutCompatibleStruct(ASTContext &C,
8837 RecordDecl *RD1,
8838 RecordDecl *RD2) {
8839 // If both records are C++ classes, check that base classes match.
8840 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8841 // If one of records is a CXXRecordDecl we are in C++ mode,
8842 // thus the other one is a CXXRecordDecl, too.
8843 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8844 // Check number of base classes.
8845 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8846 return false;
8847
8848 // Check the base classes.
8849 for (CXXRecordDecl::base_class_const_iterator
8850 Base1 = D1CXX->bases_begin(),
8851 BaseEnd1 = D1CXX->bases_end(),
8852 Base2 = D2CXX->bases_begin();
8853 Base1 != BaseEnd1;
8854 ++Base1, ++Base2) {
8855 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8856 return false;
8857 }
8858 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8859 // If only RD2 is a C++ class, it should have zero base classes.
8860 if (D2CXX->getNumBases() > 0)
8861 return false;
8862 }
8863
8864 // Check the fields.
8865 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8866 Field2End = RD2->field_end(),
8867 Field1 = RD1->field_begin(),
8868 Field1End = RD1->field_end();
8869 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8870 if (!isLayoutCompatible(C, *Field1, *Field2))
8871 return false;
8872 }
8873 if (Field1 != Field1End || Field2 != Field2End)
8874 return false;
8875
8876 return true;
8877}
8878
8879/// \brief Check if two standard-layout unions are layout-compatible.
8880/// (C++11 [class.mem] p18)
8881bool isLayoutCompatibleUnion(ASTContext &C,
8882 RecordDecl *RD1,
8883 RecordDecl *RD2) {
8884 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008885 for (auto *Field2 : RD2->fields())
8886 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008887
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008888 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008889 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8890 I = UnmatchedFields.begin(),
8891 E = UnmatchedFields.end();
8892
8893 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008894 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008895 bool Result = UnmatchedFields.erase(*I);
8896 (void) Result;
8897 assert(Result);
8898 break;
8899 }
8900 }
8901 if (I == E)
8902 return false;
8903 }
8904
8905 return UnmatchedFields.empty();
8906}
8907
8908bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8909 if (RD1->isUnion() != RD2->isUnion())
8910 return false;
8911
8912 if (RD1->isUnion())
8913 return isLayoutCompatibleUnion(C, RD1, RD2);
8914 else
8915 return isLayoutCompatibleStruct(C, RD1, RD2);
8916}
8917
8918/// \brief Check if two types are layout-compatible in C++11 sense.
8919bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8920 if (T1.isNull() || T2.isNull())
8921 return false;
8922
8923 // C++11 [basic.types] p11:
8924 // If two types T1 and T2 are the same type, then T1 and T2 are
8925 // layout-compatible types.
8926 if (C.hasSameType(T1, T2))
8927 return true;
8928
8929 T1 = T1.getCanonicalType().getUnqualifiedType();
8930 T2 = T2.getCanonicalType().getUnqualifiedType();
8931
8932 const Type::TypeClass TC1 = T1->getTypeClass();
8933 const Type::TypeClass TC2 = T2->getTypeClass();
8934
8935 if (TC1 != TC2)
8936 return false;
8937
8938 if (TC1 == Type::Enum) {
8939 return isLayoutCompatible(C,
8940 cast<EnumType>(T1)->getDecl(),
8941 cast<EnumType>(T2)->getDecl());
8942 } else if (TC1 == Type::Record) {
8943 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8944 return false;
8945
8946 return isLayoutCompatible(C,
8947 cast<RecordType>(T1)->getDecl(),
8948 cast<RecordType>(T2)->getDecl());
8949 }
8950
8951 return false;
8952}
8953}
8954
8955//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8956
8957namespace {
8958/// \brief Given a type tag expression find the type tag itself.
8959///
8960/// \param TypeExpr Type tag expression, as it appears in user's code.
8961///
8962/// \param VD Declaration of an identifier that appears in a type tag.
8963///
8964/// \param MagicValue Type tag magic value.
8965bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8966 const ValueDecl **VD, uint64_t *MagicValue) {
8967 while(true) {
8968 if (!TypeExpr)
8969 return false;
8970
8971 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8972
8973 switch (TypeExpr->getStmtClass()) {
8974 case Stmt::UnaryOperatorClass: {
8975 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8976 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8977 TypeExpr = UO->getSubExpr();
8978 continue;
8979 }
8980 return false;
8981 }
8982
8983 case Stmt::DeclRefExprClass: {
8984 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8985 *VD = DRE->getDecl();
8986 return true;
8987 }
8988
8989 case Stmt::IntegerLiteralClass: {
8990 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8991 llvm::APInt MagicValueAPInt = IL->getValue();
8992 if (MagicValueAPInt.getActiveBits() <= 64) {
8993 *MagicValue = MagicValueAPInt.getZExtValue();
8994 return true;
8995 } else
8996 return false;
8997 }
8998
8999 case Stmt::BinaryConditionalOperatorClass:
9000 case Stmt::ConditionalOperatorClass: {
9001 const AbstractConditionalOperator *ACO =
9002 cast<AbstractConditionalOperator>(TypeExpr);
9003 bool Result;
9004 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9005 if (Result)
9006 TypeExpr = ACO->getTrueExpr();
9007 else
9008 TypeExpr = ACO->getFalseExpr();
9009 continue;
9010 }
9011 return false;
9012 }
9013
9014 case Stmt::BinaryOperatorClass: {
9015 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9016 if (BO->getOpcode() == BO_Comma) {
9017 TypeExpr = BO->getRHS();
9018 continue;
9019 }
9020 return false;
9021 }
9022
9023 default:
9024 return false;
9025 }
9026 }
9027}
9028
9029/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9030///
9031/// \param TypeExpr Expression that specifies a type tag.
9032///
9033/// \param MagicValues Registered magic values.
9034///
9035/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9036/// kind.
9037///
9038/// \param TypeInfo Information about the corresponding C type.
9039///
9040/// \returns true if the corresponding C type was found.
9041bool GetMatchingCType(
9042 const IdentifierInfo *ArgumentKind,
9043 const Expr *TypeExpr, const ASTContext &Ctx,
9044 const llvm::DenseMap<Sema::TypeTagMagicValue,
9045 Sema::TypeTagData> *MagicValues,
9046 bool &FoundWrongKind,
9047 Sema::TypeTagData &TypeInfo) {
9048 FoundWrongKind = false;
9049
9050 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009051 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009052
9053 uint64_t MagicValue;
9054
9055 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9056 return false;
9057
9058 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009059 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009060 if (I->getArgumentKind() != ArgumentKind) {
9061 FoundWrongKind = true;
9062 return false;
9063 }
9064 TypeInfo.Type = I->getMatchingCType();
9065 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9066 TypeInfo.MustBeNull = I->getMustBeNull();
9067 return true;
9068 }
9069 return false;
9070 }
9071
9072 if (!MagicValues)
9073 return false;
9074
9075 llvm::DenseMap<Sema::TypeTagMagicValue,
9076 Sema::TypeTagData>::const_iterator I =
9077 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9078 if (I == MagicValues->end())
9079 return false;
9080
9081 TypeInfo = I->second;
9082 return true;
9083}
9084} // unnamed namespace
9085
9086void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9087 uint64_t MagicValue, QualType Type,
9088 bool LayoutCompatible,
9089 bool MustBeNull) {
9090 if (!TypeTagForDatatypeMagicValues)
9091 TypeTagForDatatypeMagicValues.reset(
9092 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9093
9094 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9095 (*TypeTagForDatatypeMagicValues)[Magic] =
9096 TypeTagData(Type, LayoutCompatible, MustBeNull);
9097}
9098
9099namespace {
9100bool IsSameCharType(QualType T1, QualType T2) {
9101 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9102 if (!BT1)
9103 return false;
9104
9105 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9106 if (!BT2)
9107 return false;
9108
9109 BuiltinType::Kind T1Kind = BT1->getKind();
9110 BuiltinType::Kind T2Kind = BT2->getKind();
9111
9112 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9113 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9114 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9115 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9116}
9117} // unnamed namespace
9118
9119void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9120 const Expr * const *ExprArgs) {
9121 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9122 bool IsPointerAttr = Attr->getIsPointer();
9123
9124 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9125 bool FoundWrongKind;
9126 TypeTagData TypeInfo;
9127 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9128 TypeTagForDatatypeMagicValues.get(),
9129 FoundWrongKind, TypeInfo)) {
9130 if (FoundWrongKind)
9131 Diag(TypeTagExpr->getExprLoc(),
9132 diag::warn_type_tag_for_datatype_wrong_kind)
9133 << TypeTagExpr->getSourceRange();
9134 return;
9135 }
9136
9137 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9138 if (IsPointerAttr) {
9139 // Skip implicit cast of pointer to `void *' (as a function argument).
9140 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009141 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009142 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009143 ArgumentExpr = ICE->getSubExpr();
9144 }
9145 QualType ArgumentType = ArgumentExpr->getType();
9146
9147 // Passing a `void*' pointer shouldn't trigger a warning.
9148 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9149 return;
9150
9151 if (TypeInfo.MustBeNull) {
9152 // Type tag with matching void type requires a null pointer.
9153 if (!ArgumentExpr->isNullPointerConstant(Context,
9154 Expr::NPC_ValueDependentIsNotNull)) {
9155 Diag(ArgumentExpr->getExprLoc(),
9156 diag::warn_type_safety_null_pointer_required)
9157 << ArgumentKind->getName()
9158 << ArgumentExpr->getSourceRange()
9159 << TypeTagExpr->getSourceRange();
9160 }
9161 return;
9162 }
9163
9164 QualType RequiredType = TypeInfo.Type;
9165 if (IsPointerAttr)
9166 RequiredType = Context.getPointerType(RequiredType);
9167
9168 bool mismatch = false;
9169 if (!TypeInfo.LayoutCompatible) {
9170 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9171
9172 // C++11 [basic.fundamental] p1:
9173 // Plain char, signed char, and unsigned char are three distinct types.
9174 //
9175 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9176 // char' depending on the current char signedness mode.
9177 if (mismatch)
9178 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9179 RequiredType->getPointeeType())) ||
9180 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9181 mismatch = false;
9182 } else
9183 if (IsPointerAttr)
9184 mismatch = !isLayoutCompatible(Context,
9185 ArgumentType->getPointeeType(),
9186 RequiredType->getPointeeType());
9187 else
9188 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9189
9190 if (mismatch)
9191 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009192 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009193 << TypeInfo.LayoutCompatible << RequiredType
9194 << ArgumentExpr->getSourceRange()
9195 << TypeTagExpr->getSourceRange();
9196}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009197