blob: 7d5aed9f5eb76165e60230a5a2413765a6480920 [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;
885 case X86::BI__builtin_ia32_vinsertf128_pd256:
886 case X86::BI__builtin_ia32_vinsertf128_ps256:
887 case X86::BI__builtin_ia32_vinsertf128_si256:
Craig Topper1e2f8852015-02-26 06:23:15 +0000888 case X86::BI__builtin_ia32_insert128i256: i = 2, l = 0; u = 1; break;
889 case X86::BI__builtin_ia32_blendpd:
Craig Topper16015252015-01-31 06:31:23 +0000890 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +0000891 case X86::BI__builtin_ia32_vpermil2pd:
892 case X86::BI__builtin_ia32_vpermil2pd256:
893 case X86::BI__builtin_ia32_vpermil2ps:
894 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +0000895 case X86::BI__builtin_ia32_cmpb128_mask:
896 case X86::BI__builtin_ia32_cmpw128_mask:
897 case X86::BI__builtin_ia32_cmpd128_mask:
898 case X86::BI__builtin_ia32_cmpq128_mask:
899 case X86::BI__builtin_ia32_cmpb256_mask:
900 case X86::BI__builtin_ia32_cmpw256_mask:
901 case X86::BI__builtin_ia32_cmpd256_mask:
902 case X86::BI__builtin_ia32_cmpq256_mask:
903 case X86::BI__builtin_ia32_cmpb512_mask:
904 case X86::BI__builtin_ia32_cmpw512_mask:
905 case X86::BI__builtin_ia32_cmpd512_mask:
906 case X86::BI__builtin_ia32_cmpq512_mask:
907 case X86::BI__builtin_ia32_ucmpb128_mask:
908 case X86::BI__builtin_ia32_ucmpw128_mask:
909 case X86::BI__builtin_ia32_ucmpd128_mask:
910 case X86::BI__builtin_ia32_ucmpq128_mask:
911 case X86::BI__builtin_ia32_ucmpb256_mask:
912 case X86::BI__builtin_ia32_ucmpw256_mask:
913 case X86::BI__builtin_ia32_ucmpd256_mask:
914 case X86::BI__builtin_ia32_ucmpq256_mask:
915 case X86::BI__builtin_ia32_ucmpb512_mask:
916 case X86::BI__builtin_ia32_ucmpw512_mask:
917 case X86::BI__builtin_ia32_ucmpd512_mask:
918 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +0000919 case X86::BI__builtin_ia32_roundps:
920 case X86::BI__builtin_ia32_roundpd:
921 case X86::BI__builtin_ia32_roundps256:
922 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
Craig Topper1e2f8852015-02-26 06:23:15 +0000923 case X86::BI__builtin_ia32_blendps:
924 case X86::BI__builtin_ia32_blendpd256:
Craig Topper16015252015-01-31 06:31:23 +0000925 case X86::BI__builtin_ia32_roundss:
926 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
927 case X86::BI__builtin_ia32_cmpps:
928 case X86::BI__builtin_ia32_cmpss:
929 case X86::BI__builtin_ia32_cmppd:
930 case X86::BI__builtin_ia32_cmpsd:
931 case X86::BI__builtin_ia32_cmpps256:
932 case X86::BI__builtin_ia32_cmppd256:
933 case X86::BI__builtin_ia32_cmpps512_mask:
934 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +0000935 case X86::BI__builtin_ia32_vpcomub:
936 case X86::BI__builtin_ia32_vpcomuw:
937 case X86::BI__builtin_ia32_vpcomud:
938 case X86::BI__builtin_ia32_vpcomuq:
939 case X86::BI__builtin_ia32_vpcomb:
940 case X86::BI__builtin_ia32_vpcomw:
941 case X86::BI__builtin_ia32_vpcomd:
942 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000943 }
Craig Topperdd84ec52014-12-27 07:00:08 +0000944 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000945}
946
Richard Smith55ce3522012-06-25 20:30:08 +0000947/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
948/// parameter with the FormatAttr's correct format_idx and firstDataArg.
949/// Returns true when the format fits the function and the FormatStringInfo has
950/// been populated.
951bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
952 FormatStringInfo *FSI) {
953 FSI->HasVAListArg = Format->getFirstArg() == 0;
954 FSI->FormatIdx = Format->getFormatIdx() - 1;
955 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000956
Richard Smith55ce3522012-06-25 20:30:08 +0000957 // The way the format attribute works in GCC, the implicit this argument
958 // of member functions is counted. However, it doesn't appear in our own
959 // lists, so decrement format_idx in that case.
960 if (IsCXXMember) {
961 if(FSI->FormatIdx == 0)
962 return false;
963 --FSI->FormatIdx;
964 if (FSI->FirstDataArg != 0)
965 --FSI->FirstDataArg;
966 }
967 return true;
968}
Mike Stump11289f42009-09-09 15:08:12 +0000969
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000970/// Checks if a the given expression evaluates to null.
971///
972/// \brief Returns true if the value evaluates to null.
973static bool CheckNonNullExpr(Sema &S,
974 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000975 // As a special case, transparent unions initialized with zero are
976 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000977 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000978 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
979 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000980 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000981 if (const InitListExpr *ILE =
982 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000983 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000984 }
985
986 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000987 return (!Expr->isValueDependent() &&
988 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
989 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000990}
991
992static void CheckNonNullArgument(Sema &S,
993 const Expr *ArgExpr,
994 SourceLocation CallSiteLoc) {
995 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000996 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
997}
998
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000999bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1000 FormatStringInfo FSI;
1001 if ((GetFormatStringType(Format) == FST_NSString) &&
1002 getFormatStringInfo(Format, false, &FSI)) {
1003 Idx = FSI.FormatIdx;
1004 return true;
1005 }
1006 return false;
1007}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001008/// \brief Diagnose use of %s directive in an NSString which is being passed
1009/// as formatting string to formatting method.
1010static void
1011DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1012 const NamedDecl *FDecl,
1013 Expr **Args,
1014 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001015 unsigned Idx = 0;
1016 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001017 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1018 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001019 Idx = 2;
1020 Format = true;
1021 }
1022 else
1023 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1024 if (S.GetFormatNSStringIdx(I, Idx)) {
1025 Format = true;
1026 break;
1027 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001028 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001029 if (!Format || NumArgs <= Idx)
1030 return;
1031 const Expr *FormatExpr = Args[Idx];
1032 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1033 FormatExpr = CSCE->getSubExpr();
1034 const StringLiteral *FormatString;
1035 if (const ObjCStringLiteral *OSL =
1036 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1037 FormatString = OSL->getString();
1038 else
1039 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1040 if (!FormatString)
1041 return;
1042 if (S.FormatStringHasSArg(FormatString)) {
1043 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1044 << "%s" << 1 << 1;
1045 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1046 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001047 }
1048}
1049
Ted Kremenek2bc73332014-01-17 06:24:43 +00001050static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001051 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +00001052 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001053 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001054 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001055 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001056 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001057 if (!NonNull->args_size()) {
1058 // Easy case: all pointer arguments are nonnull.
1059 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +00001060 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +00001061 CheckNonNullArgument(S, Arg, CallSiteLoc);
1062 return;
1063 }
1064
1065 for (unsigned Val : NonNull->args()) {
1066 if (Val >= Args.size())
1067 continue;
1068 if (NonNullArgs.empty())
1069 NonNullArgs.resize(Args.size());
1070 NonNullArgs.set(Val);
1071 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001072 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001073
1074 // Check the attributes on the parameters.
1075 ArrayRef<ParmVarDecl*> parms;
1076 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1077 parms = FD->parameters();
1078 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1079 parms = MD->parameters();
1080
Richard Smith588bd9b2014-08-27 04:59:42 +00001081 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001082 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +00001083 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001084 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +00001085 if (PVD->hasAttr<NonNullAttr>() ||
1086 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1087 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +00001088 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001089
1090 // In case this is a variadic call, check any remaining arguments.
1091 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1092 if (NonNullArgs[ArgIndex])
1093 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +00001094}
1095
Richard Smith55ce3522012-06-25 20:30:08 +00001096/// Handles the checks for format strings, non-POD arguments to vararg
1097/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00001098void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1099 unsigned NumParams, bool IsMemberFunction,
1100 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001101 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001102 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001103 if (CurContext->isDependentContext())
1104 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001105
Ted Kremenekb8176da2010-09-09 04:33:05 +00001106 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001107 llvm::SmallBitVector CheckedVarArgs;
1108 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001109 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001110 // Only create vector if there are format attributes.
1111 CheckedVarArgs.resize(Args.size());
1112
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001113 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001114 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001115 }
Richard Smithd7293d72013-08-05 18:49:43 +00001116 }
Richard Smith55ce3522012-06-25 20:30:08 +00001117
1118 // Refuse POD arguments that weren't caught by the format string
1119 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001120 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001121 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001122 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001123 if (const Expr *Arg = Args[ArgIdx]) {
1124 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1125 checkVariadicArgument(Arg, CallType);
1126 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001127 }
Richard Smithd7293d72013-08-05 18:49:43 +00001128 }
Mike Stump11289f42009-09-09 15:08:12 +00001129
Richard Trieu41bc0992013-06-22 00:20:41 +00001130 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001131 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001132
Richard Trieu41bc0992013-06-22 00:20:41 +00001133 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001134 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1135 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001136 }
Richard Smith55ce3522012-06-25 20:30:08 +00001137}
1138
1139/// CheckConstructorCall - Check a constructor call for correctness and safety
1140/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001141void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1142 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001143 const FunctionProtoType *Proto,
1144 SourceLocation Loc) {
1145 VariadicCallType CallType =
1146 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +00001147 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +00001148 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1149}
1150
1151/// CheckFunctionCall - Check a direct function call for various correctness
1152/// and safety properties not strictly enforced by the C type system.
1153bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1154 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001155 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1156 isa<CXXMethodDecl>(FDecl);
1157 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1158 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001159 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1160 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001161 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +00001162 Expr** Args = TheCall->getArgs();
1163 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001164 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001165 // If this is a call to a member operator, hide the first argument
1166 // from checkCall.
1167 // FIXME: Our choice of AST representation here is less than ideal.
1168 ++Args;
1169 --NumArgs;
1170 }
Craig Topper8c2a2a02014-08-30 16:55:39 +00001171 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +00001172 IsMemberFunction, TheCall->getRParenLoc(),
1173 TheCall->getCallee()->getSourceRange(), CallType);
1174
1175 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1176 // None of the checks below are needed for functions that don't have
1177 // simple names (e.g., C++ conversion functions).
1178 if (!FnInfo)
1179 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001180
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001181 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001182 if (getLangOpts().ObjC1)
1183 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001184
Anna Zaks22122702012-01-17 00:37:07 +00001185 unsigned CMId = FDecl->getMemoryFunctionKind();
1186 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001187 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001188
Anna Zaks201d4892012-01-13 21:52:01 +00001189 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001190 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001191 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001192 else if (CMId == Builtin::BIstrncat)
1193 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001194 else
Anna Zaks22122702012-01-17 00:37:07 +00001195 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001196
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001197 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001198}
1199
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001200bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001201 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001202 VariadicCallType CallType =
1203 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001204
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001205 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001206 /*IsMemberFunction=*/false,
1207 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001208
1209 return false;
1210}
1211
Richard Trieu664c4c62013-06-20 21:03:13 +00001212bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1213 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001214 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1215 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001216 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001217
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001218 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +00001219 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001220 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001221
Richard Trieu664c4c62013-06-20 21:03:13 +00001222 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001223 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001224 CallType = VariadicDoesNotApply;
1225 } else if (Ty->isBlockPointerType()) {
1226 CallType = VariadicBlock;
1227 } else { // Ty->isFunctionPointerType()
1228 CallType = VariadicFunction;
1229 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001230 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001231
Craig Topper8c2a2a02014-08-30 16:55:39 +00001232 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1233 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001234 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001235 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001236
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001237 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001238}
1239
Richard Trieu41bc0992013-06-22 00:20:41 +00001240/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1241/// such as function pointers returned from functions.
1242bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001243 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001244 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001245 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001246
Craig Topperc3ec1492014-05-26 06:22:03 +00001247 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001248 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001249 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001250 TheCall->getCallee()->getSourceRange(), CallType);
1251
1252 return false;
1253}
1254
Tim Northovere94a34c2014-03-11 10:49:14 +00001255static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1256 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1257 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1258 return false;
1259
1260 switch (Op) {
1261 case AtomicExpr::AO__c11_atomic_init:
1262 llvm_unreachable("There is no ordering argument for an init");
1263
1264 case AtomicExpr::AO__c11_atomic_load:
1265 case AtomicExpr::AO__atomic_load_n:
1266 case AtomicExpr::AO__atomic_load:
1267 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1268 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1269
1270 case AtomicExpr::AO__c11_atomic_store:
1271 case AtomicExpr::AO__atomic_store:
1272 case AtomicExpr::AO__atomic_store_n:
1273 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1274 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1275 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1276
1277 default:
1278 return true;
1279 }
1280}
1281
Richard Smithfeea8832012-04-12 05:08:17 +00001282ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1283 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001284 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1285 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001286
Richard Smithfeea8832012-04-12 05:08:17 +00001287 // All these operations take one of the following forms:
1288 enum {
1289 // C __c11_atomic_init(A *, C)
1290 Init,
1291 // C __c11_atomic_load(A *, int)
1292 Load,
1293 // void __atomic_load(A *, CP, int)
1294 Copy,
1295 // C __c11_atomic_add(A *, M, int)
1296 Arithmetic,
1297 // C __atomic_exchange_n(A *, CP, int)
1298 Xchg,
1299 // void __atomic_exchange(A *, C *, CP, int)
1300 GNUXchg,
1301 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1302 C11CmpXchg,
1303 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1304 GNUCmpXchg
1305 } Form = Init;
1306 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1307 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1308 // where:
1309 // C is an appropriate type,
1310 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1311 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1312 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1313 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001314
Richard Smithfeea8832012-04-12 05:08:17 +00001315 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1316 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1317 && "need to update code for modified C11 atomics");
1318 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1319 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1320 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1321 Op == AtomicExpr::AO__atomic_store_n ||
1322 Op == AtomicExpr::AO__atomic_exchange_n ||
1323 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1324 bool IsAddSub = false;
1325
1326 switch (Op) {
1327 case AtomicExpr::AO__c11_atomic_init:
1328 Form = Init;
1329 break;
1330
1331 case AtomicExpr::AO__c11_atomic_load:
1332 case AtomicExpr::AO__atomic_load_n:
1333 Form = Load;
1334 break;
1335
1336 case AtomicExpr::AO__c11_atomic_store:
1337 case AtomicExpr::AO__atomic_load:
1338 case AtomicExpr::AO__atomic_store:
1339 case AtomicExpr::AO__atomic_store_n:
1340 Form = Copy;
1341 break;
1342
1343 case AtomicExpr::AO__c11_atomic_fetch_add:
1344 case AtomicExpr::AO__c11_atomic_fetch_sub:
1345 case AtomicExpr::AO__atomic_fetch_add:
1346 case AtomicExpr::AO__atomic_fetch_sub:
1347 case AtomicExpr::AO__atomic_add_fetch:
1348 case AtomicExpr::AO__atomic_sub_fetch:
1349 IsAddSub = true;
1350 // Fall through.
1351 case AtomicExpr::AO__c11_atomic_fetch_and:
1352 case AtomicExpr::AO__c11_atomic_fetch_or:
1353 case AtomicExpr::AO__c11_atomic_fetch_xor:
1354 case AtomicExpr::AO__atomic_fetch_and:
1355 case AtomicExpr::AO__atomic_fetch_or:
1356 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001357 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001358 case AtomicExpr::AO__atomic_and_fetch:
1359 case AtomicExpr::AO__atomic_or_fetch:
1360 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001361 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001362 Form = Arithmetic;
1363 break;
1364
1365 case AtomicExpr::AO__c11_atomic_exchange:
1366 case AtomicExpr::AO__atomic_exchange_n:
1367 Form = Xchg;
1368 break;
1369
1370 case AtomicExpr::AO__atomic_exchange:
1371 Form = GNUXchg;
1372 break;
1373
1374 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1375 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1376 Form = C11CmpXchg;
1377 break;
1378
1379 case AtomicExpr::AO__atomic_compare_exchange:
1380 case AtomicExpr::AO__atomic_compare_exchange_n:
1381 Form = GNUCmpXchg;
1382 break;
1383 }
1384
1385 // Check we have the right number of arguments.
1386 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001387 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_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();
Richard Smithfeea8832012-04-12 05:08:17 +00001391 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1392 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001393 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001394 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001395 << TheCall->getCallee()->getSourceRange();
1396 return ExprError();
1397 }
1398
Richard Smithfeea8832012-04-12 05:08:17 +00001399 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001400 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001401 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1402 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1403 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001404 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001405 << Ptr->getType() << Ptr->getSourceRange();
1406 return ExprError();
1407 }
1408
Richard Smithfeea8832012-04-12 05:08:17 +00001409 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1410 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1411 QualType ValType = AtomTy; // 'C'
1412 if (IsC11) {
1413 if (!AtomTy->isAtomicType()) {
1414 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1415 << Ptr->getType() << Ptr->getSourceRange();
1416 return ExprError();
1417 }
Richard Smithe00921a2012-09-15 06:09:58 +00001418 if (AtomTy.isConstQualified()) {
1419 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1420 << Ptr->getType() << Ptr->getSourceRange();
1421 return ExprError();
1422 }
Richard Smithfeea8832012-04-12 05:08:17 +00001423 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001424 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001425
Richard Smithfeea8832012-04-12 05:08:17 +00001426 // For an arithmetic operation, the implied arithmetic must be well-formed.
1427 if (Form == Arithmetic) {
1428 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1429 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1430 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1431 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1432 return ExprError();
1433 }
1434 if (!IsAddSub && !ValType->isIntegerType()) {
1435 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1436 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1437 return ExprError();
1438 }
David Majnemere85cff82015-01-28 05:48:06 +00001439 if (IsC11 && ValType->isPointerType() &&
1440 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1441 diag::err_incomplete_type)) {
1442 return ExprError();
1443 }
Richard Smithfeea8832012-04-12 05:08:17 +00001444 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1445 // For __atomic_*_n operations, the value type must be a scalar integral or
1446 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001447 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001448 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1449 return ExprError();
1450 }
1451
Eli Friedmanaa769812013-09-11 03:49:34 +00001452 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1453 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001454 // For GNU atomics, require a trivially-copyable type. This is not part of
1455 // the GNU atomics specification, but we enforce it for sanity.
1456 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001457 << Ptr->getType() << Ptr->getSourceRange();
1458 return ExprError();
1459 }
1460
Richard Smithfeea8832012-04-12 05:08:17 +00001461 // FIXME: For any builtin other than a load, the ValType must not be
1462 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001463
1464 switch (ValType.getObjCLifetime()) {
1465 case Qualifiers::OCL_None:
1466 case Qualifiers::OCL_ExplicitNone:
1467 // okay
1468 break;
1469
1470 case Qualifiers::OCL_Weak:
1471 case Qualifiers::OCL_Strong:
1472 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001473 // FIXME: Can this happen? By this point, ValType should be known
1474 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001475 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1476 << ValType << Ptr->getSourceRange();
1477 return ExprError();
1478 }
1479
1480 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001481 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001482 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001483 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001484 ResultType = Context.BoolTy;
1485
Richard Smithfeea8832012-04-12 05:08:17 +00001486 // The type of a parameter passed 'by value'. In the GNU atomics, such
1487 // arguments are actually passed as pointers.
1488 QualType ByValType = ValType; // 'CP'
1489 if (!IsC11 && !IsN)
1490 ByValType = Ptr->getType();
1491
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001492 // The first argument --- the pointer --- has a fixed type; we
1493 // deduce the types of the rest of the arguments accordingly. Walk
1494 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001495 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001496 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001497 if (i < NumVals[Form] + 1) {
1498 switch (i) {
1499 case 1:
1500 // The second argument is the non-atomic operand. For arithmetic, this
1501 // is always passed by value, and for a compare_exchange it is always
1502 // passed by address. For the rest, GNU uses by-address and C11 uses
1503 // by-value.
1504 assert(Form != Load);
1505 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1506 Ty = ValType;
1507 else if (Form == Copy || Form == Xchg)
1508 Ty = ByValType;
1509 else if (Form == Arithmetic)
1510 Ty = Context.getPointerDiffType();
1511 else
1512 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1513 break;
1514 case 2:
1515 // The third argument to compare_exchange / GNU exchange is a
1516 // (pointer to a) desired value.
1517 Ty = ByValType;
1518 break;
1519 case 3:
1520 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1521 Ty = Context.BoolTy;
1522 break;
1523 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001524 } else {
1525 // The order(s) are always converted to int.
1526 Ty = Context.IntTy;
1527 }
Richard Smithfeea8832012-04-12 05:08:17 +00001528
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001529 InitializedEntity Entity =
1530 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001531 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001532 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1533 if (Arg.isInvalid())
1534 return true;
1535 TheCall->setArg(i, Arg.get());
1536 }
1537
Richard Smithfeea8832012-04-12 05:08:17 +00001538 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001539 SmallVector<Expr*, 5> SubExprs;
1540 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001541 switch (Form) {
1542 case Init:
1543 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001544 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001545 break;
1546 case Load:
1547 SubExprs.push_back(TheCall->getArg(1)); // Order
1548 break;
1549 case Copy:
1550 case Arithmetic:
1551 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001552 SubExprs.push_back(TheCall->getArg(2)); // Order
1553 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001554 break;
1555 case GNUXchg:
1556 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1557 SubExprs.push_back(TheCall->getArg(3)); // Order
1558 SubExprs.push_back(TheCall->getArg(1)); // Val1
1559 SubExprs.push_back(TheCall->getArg(2)); // Val2
1560 break;
1561 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001562 SubExprs.push_back(TheCall->getArg(3)); // Order
1563 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001564 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001565 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001566 break;
1567 case GNUCmpXchg:
1568 SubExprs.push_back(TheCall->getArg(4)); // Order
1569 SubExprs.push_back(TheCall->getArg(1)); // Val1
1570 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1571 SubExprs.push_back(TheCall->getArg(2)); // Val2
1572 SubExprs.push_back(TheCall->getArg(3)); // Weak
1573 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001574 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001575
1576 if (SubExprs.size() >= 2 && Form != Init) {
1577 llvm::APSInt Result(32);
1578 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1579 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001580 Diag(SubExprs[1]->getLocStart(),
1581 diag::warn_atomic_op_has_invalid_memory_order)
1582 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001583 }
1584
Fariborz Jahanian615de762013-05-28 17:37:39 +00001585 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1586 SubExprs, ResultType, Op,
1587 TheCall->getRParenLoc());
1588
1589 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1590 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1591 Context.AtomicUsesUnsupportedLibcall(AE))
1592 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1593 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001594
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001595 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001596}
1597
1598
John McCall29ad95b2011-08-27 01:09:30 +00001599/// checkBuiltinArgument - Given a call to a builtin function, perform
1600/// normal type-checking on the given argument, updating the call in
1601/// place. This is useful when a builtin function requires custom
1602/// type-checking for some of its arguments but not necessarily all of
1603/// them.
1604///
1605/// Returns true on error.
1606static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1607 FunctionDecl *Fn = E->getDirectCallee();
1608 assert(Fn && "builtin call without direct callee!");
1609
1610 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1611 InitializedEntity Entity =
1612 InitializedEntity::InitializeParameter(S.Context, Param);
1613
1614 ExprResult Arg = E->getArg(0);
1615 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1616 if (Arg.isInvalid())
1617 return true;
1618
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001619 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001620 return false;
1621}
1622
Chris Lattnerdc046542009-05-08 06:58:22 +00001623/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1624/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1625/// type of its first argument. The main ActOnCallExpr routines have already
1626/// promoted the types of arguments because all of these calls are prototyped as
1627/// void(...).
1628///
1629/// This function goes through and does final semantic checking for these
1630/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001631ExprResult
1632Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001633 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001634 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1635 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1636
1637 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001638 if (TheCall->getNumArgs() < 1) {
1639 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1640 << 0 << 1 << TheCall->getNumArgs()
1641 << TheCall->getCallee()->getSourceRange();
1642 return ExprError();
1643 }
Mike Stump11289f42009-09-09 15:08:12 +00001644
Chris Lattnerdc046542009-05-08 06:58:22 +00001645 // Inspect the first argument of the atomic builtin. This should always be
1646 // a pointer type, whose element is an integral scalar or pointer type.
1647 // Because it is a pointer type, we don't have to worry about any implicit
1648 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001649 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001650 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001651 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1652 if (FirstArgResult.isInvalid())
1653 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001654 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001655 TheCall->setArg(0, FirstArg);
1656
John McCall31168b02011-06-15 23:02:42 +00001657 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1658 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001659 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1660 << FirstArg->getType() << FirstArg->getSourceRange();
1661 return ExprError();
1662 }
Mike Stump11289f42009-09-09 15:08:12 +00001663
John McCall31168b02011-06-15 23:02:42 +00001664 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001665 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001666 !ValType->isBlockPointerType()) {
1667 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1668 << FirstArg->getType() << FirstArg->getSourceRange();
1669 return ExprError();
1670 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001671
John McCall31168b02011-06-15 23:02:42 +00001672 switch (ValType.getObjCLifetime()) {
1673 case Qualifiers::OCL_None:
1674 case Qualifiers::OCL_ExplicitNone:
1675 // okay
1676 break;
1677
1678 case Qualifiers::OCL_Weak:
1679 case Qualifiers::OCL_Strong:
1680 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001681 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001682 << ValType << FirstArg->getSourceRange();
1683 return ExprError();
1684 }
1685
John McCallb50451a2011-10-05 07:41:44 +00001686 // Strip any qualifiers off ValType.
1687 ValType = ValType.getUnqualifiedType();
1688
Chandler Carruth3973af72010-07-18 20:54:12 +00001689 // The majority of builtins return a value, but a few have special return
1690 // types, so allow them to override appropriately below.
1691 QualType ResultType = ValType;
1692
Chris Lattnerdc046542009-05-08 06:58:22 +00001693 // We need to figure out which concrete builtin this maps onto. For example,
1694 // __sync_fetch_and_add with a 2 byte object turns into
1695 // __sync_fetch_and_add_2.
1696#define BUILTIN_ROW(x) \
1697 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1698 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001699
Chris Lattnerdc046542009-05-08 06:58:22 +00001700 static const unsigned BuiltinIndices[][5] = {
1701 BUILTIN_ROW(__sync_fetch_and_add),
1702 BUILTIN_ROW(__sync_fetch_and_sub),
1703 BUILTIN_ROW(__sync_fetch_and_or),
1704 BUILTIN_ROW(__sync_fetch_and_and),
1705 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001706 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001707
Chris Lattnerdc046542009-05-08 06:58:22 +00001708 BUILTIN_ROW(__sync_add_and_fetch),
1709 BUILTIN_ROW(__sync_sub_and_fetch),
1710 BUILTIN_ROW(__sync_and_and_fetch),
1711 BUILTIN_ROW(__sync_or_and_fetch),
1712 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001713 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001714
Chris Lattnerdc046542009-05-08 06:58:22 +00001715 BUILTIN_ROW(__sync_val_compare_and_swap),
1716 BUILTIN_ROW(__sync_bool_compare_and_swap),
1717 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001718 BUILTIN_ROW(__sync_lock_release),
1719 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001720 };
Mike Stump11289f42009-09-09 15:08:12 +00001721#undef BUILTIN_ROW
1722
Chris Lattnerdc046542009-05-08 06:58:22 +00001723 // Determine the index of the size.
1724 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001725 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001726 case 1: SizeIndex = 0; break;
1727 case 2: SizeIndex = 1; break;
1728 case 4: SizeIndex = 2; break;
1729 case 8: SizeIndex = 3; break;
1730 case 16: SizeIndex = 4; break;
1731 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001732 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1733 << FirstArg->getType() << FirstArg->getSourceRange();
1734 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001735 }
Mike Stump11289f42009-09-09 15:08:12 +00001736
Chris Lattnerdc046542009-05-08 06:58:22 +00001737 // Each of these builtins has one pointer argument, followed by some number of
1738 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1739 // that we ignore. Find out which row of BuiltinIndices to read from as well
1740 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001741 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001742 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001743 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001744 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001745 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001746 case Builtin::BI__sync_fetch_and_add:
1747 case Builtin::BI__sync_fetch_and_add_1:
1748 case Builtin::BI__sync_fetch_and_add_2:
1749 case Builtin::BI__sync_fetch_and_add_4:
1750 case Builtin::BI__sync_fetch_and_add_8:
1751 case Builtin::BI__sync_fetch_and_add_16:
1752 BuiltinIndex = 0;
1753 break;
1754
1755 case Builtin::BI__sync_fetch_and_sub:
1756 case Builtin::BI__sync_fetch_and_sub_1:
1757 case Builtin::BI__sync_fetch_and_sub_2:
1758 case Builtin::BI__sync_fetch_and_sub_4:
1759 case Builtin::BI__sync_fetch_and_sub_8:
1760 case Builtin::BI__sync_fetch_and_sub_16:
1761 BuiltinIndex = 1;
1762 break;
1763
1764 case Builtin::BI__sync_fetch_and_or:
1765 case Builtin::BI__sync_fetch_and_or_1:
1766 case Builtin::BI__sync_fetch_and_or_2:
1767 case Builtin::BI__sync_fetch_and_or_4:
1768 case Builtin::BI__sync_fetch_and_or_8:
1769 case Builtin::BI__sync_fetch_and_or_16:
1770 BuiltinIndex = 2;
1771 break;
1772
1773 case Builtin::BI__sync_fetch_and_and:
1774 case Builtin::BI__sync_fetch_and_and_1:
1775 case Builtin::BI__sync_fetch_and_and_2:
1776 case Builtin::BI__sync_fetch_and_and_4:
1777 case Builtin::BI__sync_fetch_and_and_8:
1778 case Builtin::BI__sync_fetch_and_and_16:
1779 BuiltinIndex = 3;
1780 break;
Mike Stump11289f42009-09-09 15:08:12 +00001781
Douglas Gregor73722482011-11-28 16:30:08 +00001782 case Builtin::BI__sync_fetch_and_xor:
1783 case Builtin::BI__sync_fetch_and_xor_1:
1784 case Builtin::BI__sync_fetch_and_xor_2:
1785 case Builtin::BI__sync_fetch_and_xor_4:
1786 case Builtin::BI__sync_fetch_and_xor_8:
1787 case Builtin::BI__sync_fetch_and_xor_16:
1788 BuiltinIndex = 4;
1789 break;
1790
Hal Finkeld2208b52014-10-02 20:53:50 +00001791 case Builtin::BI__sync_fetch_and_nand:
1792 case Builtin::BI__sync_fetch_and_nand_1:
1793 case Builtin::BI__sync_fetch_and_nand_2:
1794 case Builtin::BI__sync_fetch_and_nand_4:
1795 case Builtin::BI__sync_fetch_and_nand_8:
1796 case Builtin::BI__sync_fetch_and_nand_16:
1797 BuiltinIndex = 5;
1798 WarnAboutSemanticsChange = true;
1799 break;
1800
Douglas Gregor73722482011-11-28 16:30:08 +00001801 case Builtin::BI__sync_add_and_fetch:
1802 case Builtin::BI__sync_add_and_fetch_1:
1803 case Builtin::BI__sync_add_and_fetch_2:
1804 case Builtin::BI__sync_add_and_fetch_4:
1805 case Builtin::BI__sync_add_and_fetch_8:
1806 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001807 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00001808 break;
1809
1810 case Builtin::BI__sync_sub_and_fetch:
1811 case Builtin::BI__sync_sub_and_fetch_1:
1812 case Builtin::BI__sync_sub_and_fetch_2:
1813 case Builtin::BI__sync_sub_and_fetch_4:
1814 case Builtin::BI__sync_sub_and_fetch_8:
1815 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001816 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00001817 break;
1818
1819 case Builtin::BI__sync_and_and_fetch:
1820 case Builtin::BI__sync_and_and_fetch_1:
1821 case Builtin::BI__sync_and_and_fetch_2:
1822 case Builtin::BI__sync_and_and_fetch_4:
1823 case Builtin::BI__sync_and_and_fetch_8:
1824 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001825 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00001826 break;
1827
1828 case Builtin::BI__sync_or_and_fetch:
1829 case Builtin::BI__sync_or_and_fetch_1:
1830 case Builtin::BI__sync_or_and_fetch_2:
1831 case Builtin::BI__sync_or_and_fetch_4:
1832 case Builtin::BI__sync_or_and_fetch_8:
1833 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001834 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00001835 break;
1836
1837 case Builtin::BI__sync_xor_and_fetch:
1838 case Builtin::BI__sync_xor_and_fetch_1:
1839 case Builtin::BI__sync_xor_and_fetch_2:
1840 case Builtin::BI__sync_xor_and_fetch_4:
1841 case Builtin::BI__sync_xor_and_fetch_8:
1842 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001843 BuiltinIndex = 10;
1844 break;
1845
1846 case Builtin::BI__sync_nand_and_fetch:
1847 case Builtin::BI__sync_nand_and_fetch_1:
1848 case Builtin::BI__sync_nand_and_fetch_2:
1849 case Builtin::BI__sync_nand_and_fetch_4:
1850 case Builtin::BI__sync_nand_and_fetch_8:
1851 case Builtin::BI__sync_nand_and_fetch_16:
1852 BuiltinIndex = 11;
1853 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00001854 break;
Mike Stump11289f42009-09-09 15:08:12 +00001855
Chris Lattnerdc046542009-05-08 06:58:22 +00001856 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001857 case Builtin::BI__sync_val_compare_and_swap_1:
1858 case Builtin::BI__sync_val_compare_and_swap_2:
1859 case Builtin::BI__sync_val_compare_and_swap_4:
1860 case Builtin::BI__sync_val_compare_and_swap_8:
1861 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001862 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00001863 NumFixed = 2;
1864 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001865
Chris Lattnerdc046542009-05-08 06:58:22 +00001866 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001867 case Builtin::BI__sync_bool_compare_and_swap_1:
1868 case Builtin::BI__sync_bool_compare_and_swap_2:
1869 case Builtin::BI__sync_bool_compare_and_swap_4:
1870 case Builtin::BI__sync_bool_compare_and_swap_8:
1871 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001872 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001873 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001874 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001875 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001876
1877 case Builtin::BI__sync_lock_test_and_set:
1878 case Builtin::BI__sync_lock_test_and_set_1:
1879 case Builtin::BI__sync_lock_test_and_set_2:
1880 case Builtin::BI__sync_lock_test_and_set_4:
1881 case Builtin::BI__sync_lock_test_and_set_8:
1882 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001883 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00001884 break;
1885
Chris Lattnerdc046542009-05-08 06:58:22 +00001886 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001887 case Builtin::BI__sync_lock_release_1:
1888 case Builtin::BI__sync_lock_release_2:
1889 case Builtin::BI__sync_lock_release_4:
1890 case Builtin::BI__sync_lock_release_8:
1891 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001892 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00001893 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001894 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001895 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001896
1897 case Builtin::BI__sync_swap:
1898 case Builtin::BI__sync_swap_1:
1899 case Builtin::BI__sync_swap_2:
1900 case Builtin::BI__sync_swap_4:
1901 case Builtin::BI__sync_swap_8:
1902 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001903 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00001904 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001905 }
Mike Stump11289f42009-09-09 15:08:12 +00001906
Chris Lattnerdc046542009-05-08 06:58:22 +00001907 // Now that we know how many fixed arguments we expect, first check that we
1908 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001909 if (TheCall->getNumArgs() < 1+NumFixed) {
1910 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1911 << 0 << 1+NumFixed << TheCall->getNumArgs()
1912 << TheCall->getCallee()->getSourceRange();
1913 return ExprError();
1914 }
Mike Stump11289f42009-09-09 15:08:12 +00001915
Hal Finkeld2208b52014-10-02 20:53:50 +00001916 if (WarnAboutSemanticsChange) {
1917 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1918 << TheCall->getCallee()->getSourceRange();
1919 }
1920
Chris Lattner5b9241b2009-05-08 15:36:58 +00001921 // Get the decl for the concrete builtin from this, we can tell what the
1922 // concrete integer type we should convert to is.
1923 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1924 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001925 FunctionDecl *NewBuiltinDecl;
1926 if (NewBuiltinID == BuiltinID)
1927 NewBuiltinDecl = FDecl;
1928 else {
1929 // Perform builtin lookup to avoid redeclaring it.
1930 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1931 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1932 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1933 assert(Res.getFoundDecl());
1934 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001935 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001936 return ExprError();
1937 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001938
John McCallcf142162010-08-07 06:22:56 +00001939 // The first argument --- the pointer --- has a fixed type; we
1940 // deduce the types of the rest of the arguments accordingly. Walk
1941 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001942 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001943 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001944
Chris Lattnerdc046542009-05-08 06:58:22 +00001945 // GCC does an implicit conversion to the pointer or integer ValType. This
1946 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001947 // Initialize the argument.
1948 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1949 ValType, /*consume*/ false);
1950 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001951 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001952 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001953
Chris Lattnerdc046542009-05-08 06:58:22 +00001954 // Okay, we have something that *can* be converted to the right type. Check
1955 // to see if there is a potentially weird extension going on here. This can
1956 // happen when you do an atomic operation on something like an char* and
1957 // pass in 42. The 42 gets converted to char. This is even more strange
1958 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001959 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001960 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001961 }
Mike Stump11289f42009-09-09 15:08:12 +00001962
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001963 ASTContext& Context = this->getASTContext();
1964
1965 // Create a new DeclRefExpr to refer to the new decl.
1966 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1967 Context,
1968 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001969 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001970 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001971 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001972 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001973 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001974 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001975
Chris Lattnerdc046542009-05-08 06:58:22 +00001976 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001977 // FIXME: This loses syntactic information.
1978 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1979 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1980 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001981 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001982
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001983 // Change the result type of the call to match the original value type. This
1984 // is arbitrary, but the codegen for these builtins ins design to handle it
1985 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001986 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001987
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001988 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001989}
1990
Chris Lattner6436fb62009-02-18 06:01:06 +00001991/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001992/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001993/// Note: It might also make sense to do the UTF-16 conversion here (would
1994/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001995bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001996 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001997 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1998
Douglas Gregorfb65e592011-07-27 05:40:30 +00001999 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002000 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2001 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002002 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002003 }
Mike Stump11289f42009-09-09 15:08:12 +00002004
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002005 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002006 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002007 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002008 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002009 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002010 UTF16 *ToPtr = &ToBuf[0];
2011
2012 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2013 &ToPtr, ToPtr + NumBytes,
2014 strictConversion);
2015 // Check for conversion failure.
2016 if (Result != conversionOK)
2017 Diag(Arg->getLocStart(),
2018 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2019 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002020 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002021}
2022
Chris Lattnere202e6a2007-12-20 00:05:45 +00002023/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2024/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00002025bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2026 Expr *Fn = TheCall->getCallee();
2027 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002028 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002029 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002030 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2031 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002032 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002033 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002034 return true;
2035 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002036
2037 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002038 return Diag(TheCall->getLocEnd(),
2039 diag::err_typecheck_call_too_few_args_at_least)
2040 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002041 }
2042
John McCall29ad95b2011-08-27 01:09:30 +00002043 // Type-check the first argument normally.
2044 if (checkBuiltinArgument(*this, TheCall, 0))
2045 return true;
2046
Chris Lattnere202e6a2007-12-20 00:05:45 +00002047 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002048 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002049 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002050 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002051 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002052 else if (FunctionDecl *FD = getCurFunctionDecl())
2053 isVariadic = FD->isVariadic();
2054 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002055 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002056
Chris Lattnere202e6a2007-12-20 00:05:45 +00002057 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002058 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2059 return true;
2060 }
Mike Stump11289f42009-09-09 15:08:12 +00002061
Chris Lattner43be2e62007-12-19 23:59:04 +00002062 // Verify that the second argument to the builtin is the last argument of the
2063 // current function or method.
2064 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002065 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002066
Nico Weber9eea7642013-05-24 23:31:57 +00002067 // These are valid if SecondArgIsLastNamedArgument is false after the next
2068 // block.
2069 QualType Type;
2070 SourceLocation ParamLoc;
2071
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002072 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2073 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002074 // FIXME: This isn't correct for methods (results in bogus warning).
2075 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002076 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002077 if (CurBlock)
2078 LastArg = *(CurBlock->TheDecl->param_end()-1);
2079 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002080 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002081 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002082 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002083 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002084
2085 Type = PV->getType();
2086 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002087 }
2088 }
Mike Stump11289f42009-09-09 15:08:12 +00002089
Chris Lattner43be2e62007-12-19 23:59:04 +00002090 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002091 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002092 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002093 else if (Type->isReferenceType()) {
2094 Diag(Arg->getLocStart(),
2095 diag::warn_va_start_of_reference_type_is_undefined);
2096 Diag(ParamLoc, diag::note_parameter_type) << Type;
2097 }
2098
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002099 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002100 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002101}
Chris Lattner43be2e62007-12-19 23:59:04 +00002102
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002103bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2104 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2105 // const char *named_addr);
2106
2107 Expr *Func = Call->getCallee();
2108
2109 if (Call->getNumArgs() < 3)
2110 return Diag(Call->getLocEnd(),
2111 diag::err_typecheck_call_too_few_args_at_least)
2112 << 0 /*function call*/ << 3 << Call->getNumArgs();
2113
2114 // Determine whether the current function is variadic or not.
2115 bool IsVariadic;
2116 if (BlockScopeInfo *CurBlock = getCurBlock())
2117 IsVariadic = CurBlock->TheDecl->isVariadic();
2118 else if (FunctionDecl *FD = getCurFunctionDecl())
2119 IsVariadic = FD->isVariadic();
2120 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2121 IsVariadic = MD->isVariadic();
2122 else
2123 llvm_unreachable("unexpected statement type");
2124
2125 if (!IsVariadic) {
2126 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2127 return true;
2128 }
2129
2130 // Type-check the first argument normally.
2131 if (checkBuiltinArgument(*this, Call, 0))
2132 return true;
2133
2134 static const struct {
2135 unsigned ArgNo;
2136 QualType Type;
2137 } ArgumentTypes[] = {
2138 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2139 { 2, Context.getSizeType() },
2140 };
2141
2142 for (const auto &AT : ArgumentTypes) {
2143 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2144 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2145 continue;
2146 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2147 << Arg->getType() << AT.Type << 1 /* different class */
2148 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2149 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2150 }
2151
2152 return false;
2153}
2154
Chris Lattner2da14fb2007-12-20 00:26:33 +00002155/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2156/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002157bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2158 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002159 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002160 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002161 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002162 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002163 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002164 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002165 << SourceRange(TheCall->getArg(2)->getLocStart(),
2166 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002167
John Wiegley01296292011-04-08 18:41:53 +00002168 ExprResult OrigArg0 = TheCall->getArg(0);
2169 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002170
Chris Lattner2da14fb2007-12-20 00:26:33 +00002171 // Do standard promotions between the two arguments, returning their common
2172 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002173 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002174 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2175 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002176
2177 // Make sure any conversions are pushed back into the call; this is
2178 // type safe since unordered compare builtins are declared as "_Bool
2179 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002180 TheCall->setArg(0, OrigArg0.get());
2181 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002182
John Wiegley01296292011-04-08 18:41:53 +00002183 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002184 return false;
2185
Chris Lattner2da14fb2007-12-20 00:26:33 +00002186 // If the common type isn't a real floating type, then the arguments were
2187 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002188 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002189 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002190 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002191 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2192 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002193
Chris Lattner2da14fb2007-12-20 00:26:33 +00002194 return false;
2195}
2196
Benjamin Kramer634fc102010-02-15 22:42:31 +00002197/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2198/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002199/// to check everything. We expect the last argument to be a floating point
2200/// value.
2201bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2202 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002203 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002204 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002205 if (TheCall->getNumArgs() > NumArgs)
2206 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002207 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002208 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002209 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002210 (*(TheCall->arg_end()-1))->getLocEnd());
2211
Benjamin Kramer64aae502010-02-16 10:07:31 +00002212 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002213
Eli Friedman7e4faac2009-08-31 20:06:00 +00002214 if (OrigArg->isTypeDependent())
2215 return false;
2216
Chris Lattner68784ef2010-05-06 05:50:07 +00002217 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002218 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002219 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002220 diag::err_typecheck_call_invalid_unary_fp)
2221 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002222
Chris Lattner68784ef2010-05-06 05:50:07 +00002223 // If this is an implicit conversion from float -> double, remove it.
2224 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2225 Expr *CastArg = Cast->getSubExpr();
2226 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2227 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2228 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002229 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002230 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002231 }
2232 }
2233
Eli Friedman7e4faac2009-08-31 20:06:00 +00002234 return false;
2235}
2236
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002237/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2238// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002239ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002240 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002241 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002242 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002243 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2244 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002245
Nate Begemana0110022010-06-08 00:16:34 +00002246 // Determine which of the following types of shufflevector we're checking:
2247 // 1) unary, vector mask: (lhs, mask)
2248 // 2) binary, vector mask: (lhs, rhs, mask)
2249 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2250 QualType resType = TheCall->getArg(0)->getType();
2251 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002252
Douglas Gregorc25f7662009-05-19 22:10:17 +00002253 if (!TheCall->getArg(0)->isTypeDependent() &&
2254 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002255 QualType LHSType = TheCall->getArg(0)->getType();
2256 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002257
Craig Topperbaca3892013-07-29 06:47:04 +00002258 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2259 return ExprError(Diag(TheCall->getLocStart(),
2260 diag::err_shufflevector_non_vector)
2261 << SourceRange(TheCall->getArg(0)->getLocStart(),
2262 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002263
Nate Begemana0110022010-06-08 00:16:34 +00002264 numElements = LHSType->getAs<VectorType>()->getNumElements();
2265 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002266
Nate Begemana0110022010-06-08 00:16:34 +00002267 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2268 // with mask. If so, verify that RHS is an integer vector type with the
2269 // same number of elts as lhs.
2270 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002271 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002272 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002273 return ExprError(Diag(TheCall->getLocStart(),
2274 diag::err_shufflevector_incompatible_vector)
2275 << SourceRange(TheCall->getArg(1)->getLocStart(),
2276 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002277 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002278 return ExprError(Diag(TheCall->getLocStart(),
2279 diag::err_shufflevector_incompatible_vector)
2280 << SourceRange(TheCall->getArg(0)->getLocStart(),
2281 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002282 } else if (numElements != numResElements) {
2283 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002284 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002285 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002286 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002287 }
2288
2289 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002290 if (TheCall->getArg(i)->isTypeDependent() ||
2291 TheCall->getArg(i)->isValueDependent())
2292 continue;
2293
Nate Begemana0110022010-06-08 00:16:34 +00002294 llvm::APSInt Result(32);
2295 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2296 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002297 diag::err_shufflevector_nonconstant_argument)
2298 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002299
Craig Topper50ad5b72013-08-03 17:40:38 +00002300 // Allow -1 which will be translated to undef in the IR.
2301 if (Result.isSigned() && Result.isAllOnesValue())
2302 continue;
2303
Chris Lattner7ab824e2008-08-10 02:05:13 +00002304 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002305 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002306 diag::err_shufflevector_argument_too_large)
2307 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002308 }
2309
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002310 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002311
Chris Lattner7ab824e2008-08-10 02:05:13 +00002312 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002313 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002314 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002315 }
2316
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002317 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2318 TheCall->getCallee()->getLocStart(),
2319 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002320}
Chris Lattner43be2e62007-12-19 23:59:04 +00002321
Hal Finkelc4d7c822013-09-18 03:29:45 +00002322/// SemaConvertVectorExpr - Handle __builtin_convertvector
2323ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2324 SourceLocation BuiltinLoc,
2325 SourceLocation RParenLoc) {
2326 ExprValueKind VK = VK_RValue;
2327 ExprObjectKind OK = OK_Ordinary;
2328 QualType DstTy = TInfo->getType();
2329 QualType SrcTy = E->getType();
2330
2331 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2332 return ExprError(Diag(BuiltinLoc,
2333 diag::err_convertvector_non_vector)
2334 << E->getSourceRange());
2335 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2336 return ExprError(Diag(BuiltinLoc,
2337 diag::err_convertvector_non_vector_type));
2338
2339 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2340 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2341 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2342 if (SrcElts != DstElts)
2343 return ExprError(Diag(BuiltinLoc,
2344 diag::err_convertvector_incompatible_vector)
2345 << E->getSourceRange());
2346 }
2347
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002348 return new (Context)
2349 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002350}
2351
Daniel Dunbarb7257262008-07-21 22:59:13 +00002352/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2353// This is declared to take (const void*, ...) and can take two
2354// optional constant int args.
2355bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002356 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002357
Chris Lattner3b054132008-11-19 05:08:23 +00002358 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002359 return Diag(TheCall->getLocEnd(),
2360 diag::err_typecheck_call_too_many_args_at_most)
2361 << 0 /*function call*/ << 3 << NumArgs
2362 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002363
2364 // Argument 0 is checked for us and the remaining arguments must be
2365 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002366 for (unsigned i = 1; i != NumArgs; ++i)
2367 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002368 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002369
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002370 return false;
2371}
2372
Hal Finkelf0417332014-07-17 14:25:55 +00002373/// SemaBuiltinAssume - Handle __assume (MS Extension).
2374// __assume does not evaluate its arguments, and should warn if its argument
2375// has side effects.
2376bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2377 Expr *Arg = TheCall->getArg(0);
2378 if (Arg->isInstantiationDependent()) return false;
2379
2380 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002381 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002382 << Arg->getSourceRange()
2383 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2384
2385 return false;
2386}
2387
2388/// Handle __builtin_assume_aligned. This is declared
2389/// as (const void*, size_t, ...) and can take one optional constant int arg.
2390bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2391 unsigned NumArgs = TheCall->getNumArgs();
2392
2393 if (NumArgs > 3)
2394 return Diag(TheCall->getLocEnd(),
2395 diag::err_typecheck_call_too_many_args_at_most)
2396 << 0 /*function call*/ << 3 << NumArgs
2397 << TheCall->getSourceRange();
2398
2399 // The alignment must be a constant integer.
2400 Expr *Arg = TheCall->getArg(1);
2401
2402 // We can't check the value of a dependent argument.
2403 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2404 llvm::APSInt Result;
2405 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2406 return true;
2407
2408 if (!Result.isPowerOf2())
2409 return Diag(TheCall->getLocStart(),
2410 diag::err_alignment_not_power_of_two)
2411 << Arg->getSourceRange();
2412 }
2413
2414 if (NumArgs > 2) {
2415 ExprResult Arg(TheCall->getArg(2));
2416 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2417 Context.getSizeType(), false);
2418 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2419 if (Arg.isInvalid()) return true;
2420 TheCall->setArg(2, Arg.get());
2421 }
Hal Finkelf0417332014-07-17 14:25:55 +00002422
2423 return false;
2424}
2425
Eric Christopher8d0c6212010-04-17 02:26:23 +00002426/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2427/// TheCall is a constant expression.
2428bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2429 llvm::APSInt &Result) {
2430 Expr *Arg = TheCall->getArg(ArgNum);
2431 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2432 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2433
2434 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2435
2436 if (!Arg->isIntegerConstantExpr(Result, Context))
2437 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002438 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002439
Chris Lattnerd545ad12009-09-23 06:06:36 +00002440 return false;
2441}
2442
Richard Sandiford28940af2014-04-16 08:47:51 +00002443/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2444/// TheCall is a constant expression in the range [Low, High].
2445bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2446 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002447 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002448
2449 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002450 Expr *Arg = TheCall->getArg(ArgNum);
2451 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002452 return false;
2453
Eric Christopher8d0c6212010-04-17 02:26:23 +00002454 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002455 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002456 return true;
2457
Richard Sandiford28940af2014-04-16 08:47:51 +00002458 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002459 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002460 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002461
2462 return false;
2463}
2464
Eli Friedmanc97d0142009-05-03 06:04:26 +00002465/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002466/// This checks that val is a constant 1.
2467bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2468 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002469 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002470
Eric Christopher8d0c6212010-04-17 02:26:23 +00002471 // TODO: This is less than ideal. Overload this to take a value.
2472 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2473 return true;
2474
2475 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002476 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2477 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2478
2479 return false;
2480}
2481
Richard Smithd7293d72013-08-05 18:49:43 +00002482namespace {
2483enum StringLiteralCheckType {
2484 SLCT_NotALiteral,
2485 SLCT_UncheckedLiteral,
2486 SLCT_CheckedLiteral
2487};
2488}
2489
Richard Smith55ce3522012-06-25 20:30:08 +00002490// Determine if an expression is a string literal or constant string.
2491// If this function returns false on the arguments to a function expecting a
2492// format string, we will usually need to emit a warning.
2493// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002494static StringLiteralCheckType
2495checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2496 bool HasVAListArg, unsigned format_idx,
2497 unsigned firstDataArg, Sema::FormatStringType Type,
2498 Sema::VariadicCallType CallType, bool InFunctionCall,
2499 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002500 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002501 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002502 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002503
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002504 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002505
Richard Smithd7293d72013-08-05 18:49:43 +00002506 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002507 // Technically -Wformat-nonliteral does not warn about this case.
2508 // The behavior of printf and friends in this case is implementation
2509 // dependent. Ideally if the format string cannot be null then
2510 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002511 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002512
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002513 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002514 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002515 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002516 // The expression is a literal if both sub-expressions were, and it was
2517 // completely checked only if both sub-expressions were checked.
2518 const AbstractConditionalOperator *C =
2519 cast<AbstractConditionalOperator>(E);
2520 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002521 checkFormatStringExpr(S, C->getTrueExpr(), 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 if (Left == SLCT_NotALiteral)
2525 return SLCT_NotALiteral;
2526 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002527 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002528 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002529 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002530 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002531 }
2532
2533 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002534 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2535 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002536 }
2537
John McCallc07a0c72011-02-17 10:25:35 +00002538 case Stmt::OpaqueValueExprClass:
2539 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2540 E = src;
2541 goto tryAgain;
2542 }
Richard Smith55ce3522012-06-25 20:30:08 +00002543 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002544
Ted Kremeneka8890832011-02-24 23:03:04 +00002545 case Stmt::PredefinedExprClass:
2546 // While __func__, etc., are technically not string literals, they
2547 // cannot contain format specifiers and thus are not a security
2548 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002549 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002550
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002551 case Stmt::DeclRefExprClass: {
2552 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002553
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002554 // As an exception, do not flag errors for variables binding to
2555 // const string literals.
2556 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2557 bool isConstant = false;
2558 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002559
Richard Smithd7293d72013-08-05 18:49:43 +00002560 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2561 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002562 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002563 isConstant = T.isConstant(S.Context) &&
2564 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002565 } else if (T->isObjCObjectPointerType()) {
2566 // In ObjC, there is usually no "const ObjectPointer" type,
2567 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002568 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002569 }
Mike Stump11289f42009-09-09 15:08:12 +00002570
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002571 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002572 if (const Expr *Init = VD->getAnyInitializer()) {
2573 // Look through initializers like const char c[] = { "foo" }
2574 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2575 if (InitList->isStringLiteralInit())
2576 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2577 }
Richard Smithd7293d72013-08-05 18:49:43 +00002578 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002579 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002580 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002581 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002582 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002583 }
Mike Stump11289f42009-09-09 15:08:12 +00002584
Anders Carlssonb012ca92009-06-28 19:55:58 +00002585 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2586 // special check to see if the format string is a function parameter
2587 // of the function calling the printf function. If the function
2588 // has an attribute indicating it is a printf-like function, then we
2589 // should suppress warnings concerning non-literals being used in a call
2590 // to a vprintf function. For example:
2591 //
2592 // void
2593 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2594 // va_list ap;
2595 // va_start(ap, fmt);
2596 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2597 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002598 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002599 if (HasVAListArg) {
2600 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2601 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2602 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002603 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002604 // adjust for implicit parameter
2605 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2606 if (MD->isInstance())
2607 ++PVIndex;
2608 // We also check if the formats are compatible.
2609 // We can't pass a 'scanf' string to a 'printf' function.
2610 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002611 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002612 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002613 }
2614 }
2615 }
2616 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002617 }
Mike Stump11289f42009-09-09 15:08:12 +00002618
Richard Smith55ce3522012-06-25 20:30:08 +00002619 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002620 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002621
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002622 case Stmt::CallExprClass:
2623 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002624 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002625 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2626 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2627 unsigned ArgIndex = FA->getFormatIdx();
2628 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2629 if (MD->isInstance())
2630 --ArgIndex;
2631 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002632
Richard Smithd7293d72013-08-05 18:49:43 +00002633 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002634 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002635 Type, CallType, InFunctionCall,
2636 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002637 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2638 unsigned BuiltinID = FD->getBuiltinID();
2639 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2640 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2641 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002642 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002643 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002644 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002645 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002646 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002647 }
2648 }
Mike Stump11289f42009-09-09 15:08:12 +00002649
Richard Smith55ce3522012-06-25 20:30:08 +00002650 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002651 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002652 case Stmt::ObjCStringLiteralClass:
2653 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002654 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002655
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002656 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002657 StrE = ObjCFExpr->getString();
2658 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002659 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002660
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002661 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002662 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2663 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002664 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002665 }
Mike Stump11289f42009-09-09 15:08:12 +00002666
Richard Smith55ce3522012-06-25 20:30:08 +00002667 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002668 }
Mike Stump11289f42009-09-09 15:08:12 +00002669
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002670 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002671 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002672 }
2673}
2674
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002675Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002676 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002677 .Case("scanf", FST_Scanf)
2678 .Cases("printf", "printf0", FST_Printf)
2679 .Cases("NSString", "CFString", FST_NSString)
2680 .Case("strftime", FST_Strftime)
2681 .Case("strfmon", FST_Strfmon)
2682 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00002683 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00002684 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002685 .Default(FST_Unknown);
2686}
2687
Jordan Rose3e0ec582012-07-19 18:10:23 +00002688/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002689/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002690/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002691bool Sema::CheckFormatArguments(const FormatAttr *Format,
2692 ArrayRef<const Expr *> Args,
2693 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002694 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002695 SourceLocation Loc, SourceRange Range,
2696 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002697 FormatStringInfo FSI;
2698 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002699 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002700 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002701 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002702 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002703}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002704
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002705bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002706 bool HasVAListArg, unsigned format_idx,
2707 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002708 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002709 SourceLocation Loc, SourceRange Range,
2710 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002711 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002712 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002713 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002714 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002715 }
Mike Stump11289f42009-09-09 15:08:12 +00002716
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002717 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002718
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002719 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002720 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002721 // Dynamically generated format strings are difficult to
2722 // automatically vet at compile time. Requiring that format strings
2723 // are string literals: (1) permits the checking of format strings by
2724 // the compiler and thereby (2) can practically remove the source of
2725 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002726
Mike Stump11289f42009-09-09 15:08:12 +00002727 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002728 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002729 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002730 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002731 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002732 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2733 format_idx, firstDataArg, Type, CallType,
2734 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002735 if (CT != SLCT_NotALiteral)
2736 // Literal format string found, check done!
2737 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002738
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002739 // Strftime is particular as it always uses a single 'time' argument,
2740 // so it is safe to pass a non-literal string.
2741 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002742 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002743
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002744 // Do not emit diag when the string param is a macro expansion and the
2745 // format is either NSString or CFString. This is a hack to prevent
2746 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2747 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002748 if (Type == FST_NSString &&
2749 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002750 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002751
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002752 // If there are no arguments specified, warn with -Wformat-security, otherwise
2753 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002754 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002755 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002756 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002757 << OrigFormatExpr->getSourceRange();
2758 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002759 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002760 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002761 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002762 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002763}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002764
Ted Kremenekab278de2010-01-28 23:39:18 +00002765namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002766class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2767protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002768 Sema &S;
2769 const StringLiteral *FExpr;
2770 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002771 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002772 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002773 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002774 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002775 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002776 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002777 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002778 bool usesPositionalArgs;
2779 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002780 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002781 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002782 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002783public:
Ted Kremenek02087932010-07-16 02:11:22 +00002784 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002785 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002786 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002787 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002788 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002789 Sema::VariadicCallType callType,
2790 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002791 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002792 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2793 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002794 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002795 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002796 inFunctionCall(inFunctionCall), CallType(callType),
2797 CheckedVarArgs(CheckedVarArgs) {
2798 CoveredArgs.resize(numDataArgs);
2799 CoveredArgs.reset();
2800 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002801
Ted Kremenek019d2242010-01-29 01:50:07 +00002802 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002803
Ted Kremenek02087932010-07-16 02:11:22 +00002804 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002805 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002806
Jordan Rose92303592012-09-08 04:00:03 +00002807 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002808 const analyze_format_string::FormatSpecifier &FS,
2809 const analyze_format_string::ConversionSpecifier &CS,
2810 const char *startSpecifier, unsigned specifierLen,
2811 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002812
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002813 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002814 const analyze_format_string::FormatSpecifier &FS,
2815 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002816
2817 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002818 const analyze_format_string::ConversionSpecifier &CS,
2819 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002820
Craig Toppere14c0f82014-03-12 04:55:44 +00002821 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002822
Craig Toppere14c0f82014-03-12 04:55:44 +00002823 void HandleInvalidPosition(const char *startSpecifier,
2824 unsigned specifierLen,
2825 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002826
Craig Toppere14c0f82014-03-12 04:55:44 +00002827 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002828
Craig Toppere14c0f82014-03-12 04:55:44 +00002829 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002830
Richard Trieu03cf7b72011-10-28 00:41:25 +00002831 template <typename Range>
2832 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2833 const Expr *ArgumentExpr,
2834 PartialDiagnostic PDiag,
2835 SourceLocation StringLoc,
2836 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002837 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002838
Ted Kremenek02087932010-07-16 02:11:22 +00002839protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002840 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2841 const char *startSpec,
2842 unsigned specifierLen,
2843 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002844
2845 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2846 const char *startSpec,
2847 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002848
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002849 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002850 CharSourceRange getSpecifierRange(const char *startSpecifier,
2851 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002852 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002853
Ted Kremenek5739de72010-01-29 01:06:55 +00002854 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002855
2856 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2857 const analyze_format_string::ConversionSpecifier &CS,
2858 const char *startSpecifier, unsigned specifierLen,
2859 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002860
2861 template <typename Range>
2862 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2863 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002864 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002865};
2866}
2867
Ted Kremenek02087932010-07-16 02:11:22 +00002868SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002869 return OrigFormatExpr->getSourceRange();
2870}
2871
Ted Kremenek02087932010-07-16 02:11:22 +00002872CharSourceRange CheckFormatHandler::
2873getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002874 SourceLocation Start = getLocationOfByte(startSpecifier);
2875 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2876
2877 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002878 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002879
2880 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002881}
2882
Ted Kremenek02087932010-07-16 02:11:22 +00002883SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002884 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002885}
2886
Ted Kremenek02087932010-07-16 02:11:22 +00002887void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2888 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002889 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2890 getLocationOfByte(startSpecifier),
2891 /*IsStringLocation*/true,
2892 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002893}
2894
Jordan Rose92303592012-09-08 04:00:03 +00002895void CheckFormatHandler::HandleInvalidLengthModifier(
2896 const analyze_format_string::FormatSpecifier &FS,
2897 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002898 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002899 using namespace analyze_format_string;
2900
2901 const LengthModifier &LM = FS.getLengthModifier();
2902 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2903
2904 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002905 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002906 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002907 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002908 getLocationOfByte(LM.getStart()),
2909 /*IsStringLocation*/true,
2910 getSpecifierRange(startSpecifier, specifierLen));
2911
2912 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2913 << FixedLM->toString()
2914 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2915
2916 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002917 FixItHint Hint;
2918 if (DiagID == diag::warn_format_nonsensical_length)
2919 Hint = FixItHint::CreateRemoval(LMRange);
2920
2921 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002922 getLocationOfByte(LM.getStart()),
2923 /*IsStringLocation*/true,
2924 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002925 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002926 }
2927}
2928
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002929void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002930 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002931 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002932 using namespace analyze_format_string;
2933
2934 const LengthModifier &LM = FS.getLengthModifier();
2935 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2936
2937 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002938 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002939 if (FixedLM) {
2940 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2941 << LM.toString() << 0,
2942 getLocationOfByte(LM.getStart()),
2943 /*IsStringLocation*/true,
2944 getSpecifierRange(startSpecifier, specifierLen));
2945
2946 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2947 << FixedLM->toString()
2948 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2949
2950 } else {
2951 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2952 << LM.toString() << 0,
2953 getLocationOfByte(LM.getStart()),
2954 /*IsStringLocation*/true,
2955 getSpecifierRange(startSpecifier, specifierLen));
2956 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002957}
2958
2959void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2960 const analyze_format_string::ConversionSpecifier &CS,
2961 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002962 using namespace analyze_format_string;
2963
2964 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002965 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002966 if (FixedCS) {
2967 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2968 << CS.toString() << /*conversion specifier*/1,
2969 getLocationOfByte(CS.getStart()),
2970 /*IsStringLocation*/true,
2971 getSpecifierRange(startSpecifier, specifierLen));
2972
2973 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2974 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2975 << FixedCS->toString()
2976 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2977 } else {
2978 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2979 << CS.toString() << /*conversion specifier*/1,
2980 getLocationOfByte(CS.getStart()),
2981 /*IsStringLocation*/true,
2982 getSpecifierRange(startSpecifier, specifierLen));
2983 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002984}
2985
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002986void CheckFormatHandler::HandlePosition(const char *startPos,
2987 unsigned posLen) {
2988 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2989 getLocationOfByte(startPos),
2990 /*IsStringLocation*/true,
2991 getSpecifierRange(startPos, posLen));
2992}
2993
Ted Kremenekd1668192010-02-27 01:41:03 +00002994void
Ted Kremenek02087932010-07-16 02:11:22 +00002995CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2996 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002997 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2998 << (unsigned) p,
2999 getLocationOfByte(startPos), /*IsStringLocation*/true,
3000 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003001}
3002
Ted Kremenek02087932010-07-16 02:11:22 +00003003void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003004 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003005 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3006 getLocationOfByte(startPos),
3007 /*IsStringLocation*/true,
3008 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003009}
3010
Ted Kremenek02087932010-07-16 02:11:22 +00003011void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003012 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003013 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003014 EmitFormatDiagnostic(
3015 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3016 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3017 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003018 }
Ted Kremenek02087932010-07-16 02:11:22 +00003019}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003020
Jordan Rose58bbe422012-07-19 18:10:08 +00003021// Note that this may return NULL if there was an error parsing or building
3022// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003023const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003024 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003025}
3026
3027void CheckFormatHandler::DoneProcessing() {
3028 // Does the number of data arguments exceed the number of
3029 // format conversions in the format string?
3030 if (!HasVAListArg) {
3031 // Find any arguments that weren't covered.
3032 CoveredArgs.flip();
3033 signed notCoveredArg = CoveredArgs.find_first();
3034 if (notCoveredArg >= 0) {
3035 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003036 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3037 SourceLocation Loc = E->getLocStart();
3038 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3039 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3040 Loc, /*IsStringLocation*/false,
3041 getFormatStringRange());
3042 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003043 }
Ted Kremenek02087932010-07-16 02:11:22 +00003044 }
3045 }
3046}
3047
Ted Kremenekce815422010-07-19 21:25:57 +00003048bool
3049CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3050 SourceLocation Loc,
3051 const char *startSpec,
3052 unsigned specifierLen,
3053 const char *csStart,
3054 unsigned csLen) {
3055
3056 bool keepGoing = true;
3057 if (argIndex < NumDataArgs) {
3058 // Consider the argument coverered, even though the specifier doesn't
3059 // make sense.
3060 CoveredArgs.set(argIndex);
3061 }
3062 else {
3063 // If argIndex exceeds the number of data arguments we
3064 // don't issue a warning because that is just a cascade of warnings (and
3065 // they may have intended '%%' anyway). We don't want to continue processing
3066 // the format string after this point, however, as we will like just get
3067 // gibberish when trying to match arguments.
3068 keepGoing = false;
3069 }
3070
Richard Trieu03cf7b72011-10-28 00:41:25 +00003071 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3072 << StringRef(csStart, csLen),
3073 Loc, /*IsStringLocation*/true,
3074 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003075
3076 return keepGoing;
3077}
3078
Richard Trieu03cf7b72011-10-28 00:41:25 +00003079void
3080CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3081 const char *startSpec,
3082 unsigned specifierLen) {
3083 EmitFormatDiagnostic(
3084 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3085 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3086}
3087
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003088bool
3089CheckFormatHandler::CheckNumArgs(
3090 const analyze_format_string::FormatSpecifier &FS,
3091 const analyze_format_string::ConversionSpecifier &CS,
3092 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3093
3094 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003095 PartialDiagnostic PDiag = FS.usesPositionalArg()
3096 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3097 << (argIndex+1) << NumDataArgs)
3098 : S.PDiag(diag::warn_printf_insufficient_data_args);
3099 EmitFormatDiagnostic(
3100 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3101 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003102 return false;
3103 }
3104 return true;
3105}
3106
Richard Trieu03cf7b72011-10-28 00:41:25 +00003107template<typename Range>
3108void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3109 SourceLocation Loc,
3110 bool IsStringLocation,
3111 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003112 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003113 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003114 Loc, IsStringLocation, StringRange, FixIt);
3115}
3116
3117/// \brief If the format string is not within the funcion call, emit a note
3118/// so that the function call and string are in diagnostic messages.
3119///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003120/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003121/// call and only one diagnostic message will be produced. Otherwise, an
3122/// extra note will be emitted pointing to location of the format string.
3123///
3124/// \param ArgumentExpr the expression that is passed as the format string
3125/// argument in the function call. Used for getting locations when two
3126/// diagnostics are emitted.
3127///
3128/// \param PDiag the callee should already have provided any strings for the
3129/// diagnostic message. This function only adds locations and fixits
3130/// to diagnostics.
3131///
3132/// \param Loc primary location for diagnostic. If two diagnostics are
3133/// required, one will be at Loc and a new SourceLocation will be created for
3134/// the other one.
3135///
3136/// \param IsStringLocation if true, Loc points to the format string should be
3137/// used for the note. Otherwise, Loc points to the argument list and will
3138/// be used with PDiag.
3139///
3140/// \param StringRange some or all of the string to highlight. This is
3141/// templated so it can accept either a CharSourceRange or a SourceRange.
3142///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003143/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003144template<typename Range>
3145void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3146 const Expr *ArgumentExpr,
3147 PartialDiagnostic PDiag,
3148 SourceLocation Loc,
3149 bool IsStringLocation,
3150 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003151 ArrayRef<FixItHint> FixIt) {
3152 if (InFunctionCall) {
3153 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3154 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003155 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003156 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003157 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3158 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003159
3160 const Sema::SemaDiagnosticBuilder &Note =
3161 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3162 diag::note_format_string_defined);
3163
3164 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003165 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003166 }
3167}
3168
Ted Kremenek02087932010-07-16 02:11:22 +00003169//===--- CHECK: Printf format string checking ------------------------------===//
3170
3171namespace {
3172class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003173 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003174public:
3175 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3176 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003177 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003178 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003179 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003180 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003181 Sema::VariadicCallType CallType,
3182 llvm::SmallBitVector &CheckedVarArgs)
3183 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3184 numDataArgs, beg, hasVAListArg, Args,
3185 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3186 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003187 {}
3188
Craig Toppere14c0f82014-03-12 04:55:44 +00003189
Ted Kremenek02087932010-07-16 02:11:22 +00003190 bool HandleInvalidPrintfConversionSpecifier(
3191 const analyze_printf::PrintfSpecifier &FS,
3192 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003193 unsigned specifierLen) override;
3194
Ted Kremenek02087932010-07-16 02:11:22 +00003195 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3196 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003197 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003198 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3199 const char *StartSpecifier,
3200 unsigned SpecifierLen,
3201 const Expr *E);
3202
Ted Kremenek02087932010-07-16 02:11:22 +00003203 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3204 const char *startSpecifier, unsigned specifierLen);
3205 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3206 const analyze_printf::OptionalAmount &Amt,
3207 unsigned type,
3208 const char *startSpecifier, unsigned specifierLen);
3209 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3210 const analyze_printf::OptionalFlag &flag,
3211 const char *startSpecifier, unsigned specifierLen);
3212 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3213 const analyze_printf::OptionalFlag &ignoredFlag,
3214 const analyze_printf::OptionalFlag &flag,
3215 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003216 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003217 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003218
Ted Kremenek02087932010-07-16 02:11:22 +00003219};
3220}
3221
3222bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3223 const analyze_printf::PrintfSpecifier &FS,
3224 const char *startSpecifier,
3225 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003226 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003227 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003228
Ted Kremenekce815422010-07-19 21:25:57 +00003229 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3230 getLocationOfByte(CS.getStart()),
3231 startSpecifier, specifierLen,
3232 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003233}
3234
Ted Kremenek02087932010-07-16 02:11:22 +00003235bool CheckPrintfHandler::HandleAmount(
3236 const analyze_format_string::OptionalAmount &Amt,
3237 unsigned k, const char *startSpecifier,
3238 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003239
3240 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003241 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003242 unsigned argIndex = Amt.getArgIndex();
3243 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003244 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3245 << k,
3246 getLocationOfByte(Amt.getStart()),
3247 /*IsStringLocation*/true,
3248 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003249 // Don't do any more checking. We will just emit
3250 // spurious errors.
3251 return false;
3252 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003253
Ted Kremenek5739de72010-01-29 01:06:55 +00003254 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003255 // Although not in conformance with C99, we also allow the argument to be
3256 // an 'unsigned int' as that is a reasonably safe case. GCC also
3257 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003258 CoveredArgs.set(argIndex);
3259 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003260 if (!Arg)
3261 return false;
3262
Ted Kremenek5739de72010-01-29 01:06:55 +00003263 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003264
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003265 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3266 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003267
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003268 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003269 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003270 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003271 << T << Arg->getSourceRange(),
3272 getLocationOfByte(Amt.getStart()),
3273 /*IsStringLocation*/true,
3274 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003275 // Don't do any more checking. We will just emit
3276 // spurious errors.
3277 return false;
3278 }
3279 }
3280 }
3281 return true;
3282}
Ted Kremenek5739de72010-01-29 01:06:55 +00003283
Tom Careb49ec692010-06-17 19:00:27 +00003284void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003285 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003286 const analyze_printf::OptionalAmount &Amt,
3287 unsigned type,
3288 const char *startSpecifier,
3289 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003290 const analyze_printf::PrintfConversionSpecifier &CS =
3291 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003292
Richard Trieu03cf7b72011-10-28 00:41:25 +00003293 FixItHint fixit =
3294 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3295 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3296 Amt.getConstantLength()))
3297 : FixItHint();
3298
3299 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3300 << type << CS.toString(),
3301 getLocationOfByte(Amt.getStart()),
3302 /*IsStringLocation*/true,
3303 getSpecifierRange(startSpecifier, specifierLen),
3304 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003305}
3306
Ted Kremenek02087932010-07-16 02:11:22 +00003307void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003308 const analyze_printf::OptionalFlag &flag,
3309 const char *startSpecifier,
3310 unsigned specifierLen) {
3311 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003312 const analyze_printf::PrintfConversionSpecifier &CS =
3313 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003314 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3315 << flag.toString() << CS.toString(),
3316 getLocationOfByte(flag.getPosition()),
3317 /*IsStringLocation*/true,
3318 getSpecifierRange(startSpecifier, specifierLen),
3319 FixItHint::CreateRemoval(
3320 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003321}
3322
3323void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003324 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003325 const analyze_printf::OptionalFlag &ignoredFlag,
3326 const analyze_printf::OptionalFlag &flag,
3327 const char *startSpecifier,
3328 unsigned specifierLen) {
3329 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003330 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3331 << ignoredFlag.toString() << flag.toString(),
3332 getLocationOfByte(ignoredFlag.getPosition()),
3333 /*IsStringLocation*/true,
3334 getSpecifierRange(startSpecifier, specifierLen),
3335 FixItHint::CreateRemoval(
3336 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003337}
3338
Richard Smith55ce3522012-06-25 20:30:08 +00003339// Determines if the specified is a C++ class or struct containing
3340// a member with the specified name and kind (e.g. a CXXMethodDecl named
3341// "c_str()").
3342template<typename MemberKind>
3343static llvm::SmallPtrSet<MemberKind*, 1>
3344CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3345 const RecordType *RT = Ty->getAs<RecordType>();
3346 llvm::SmallPtrSet<MemberKind*, 1> Results;
3347
3348 if (!RT)
3349 return Results;
3350 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003351 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003352 return Results;
3353
Alp Tokerb6cc5922014-05-03 03:45:55 +00003354 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003355 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003356 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003357
3358 // We just need to include all members of the right kind turned up by the
3359 // filter, at this point.
3360 if (S.LookupQualifiedName(R, RT->getDecl()))
3361 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3362 NamedDecl *decl = (*I)->getUnderlyingDecl();
3363 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3364 Results.insert(FK);
3365 }
3366 return Results;
3367}
3368
Richard Smith2868a732014-02-28 01:36:39 +00003369/// Check if we could call '.c_str()' on an object.
3370///
3371/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3372/// allow the call, or if it would be ambiguous).
3373bool Sema::hasCStrMethod(const Expr *E) {
3374 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3375 MethodSet Results =
3376 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3377 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3378 MI != ME; ++MI)
3379 if ((*MI)->getMinRequiredArguments() == 0)
3380 return true;
3381 return false;
3382}
3383
Richard Smith55ce3522012-06-25 20:30:08 +00003384// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003385// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003386// Returns true when a c_str() conversion method is found.
3387bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003388 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003389 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3390
3391 MethodSet Results =
3392 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3393
3394 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3395 MI != ME; ++MI) {
3396 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003397 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003398 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003399 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003400 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003401 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3402 << "c_str()"
3403 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3404 return true;
3405 }
3406 }
3407
3408 return false;
3409}
3410
Ted Kremenekab278de2010-01-28 23:39:18 +00003411bool
Ted Kremenek02087932010-07-16 02:11:22 +00003412CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003413 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003414 const char *startSpecifier,
3415 unsigned specifierLen) {
3416
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003417 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003418 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003419 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003420
Ted Kremenek6cd69422010-07-19 22:01:06 +00003421 if (FS.consumesDataArgument()) {
3422 if (atFirstArg) {
3423 atFirstArg = false;
3424 usesPositionalArgs = FS.usesPositionalArg();
3425 }
3426 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003427 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3428 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003429 return false;
3430 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003431 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003432
Ted Kremenekd1668192010-02-27 01:41:03 +00003433 // First check if the field width, precision, and conversion specifier
3434 // have matching data arguments.
3435 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3436 startSpecifier, specifierLen)) {
3437 return false;
3438 }
3439
3440 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3441 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003442 return false;
3443 }
3444
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003445 if (!CS.consumesDataArgument()) {
3446 // FIXME: Technically specifying a precision or field width here
3447 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003448 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003449 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003450
Ted Kremenek4a49d982010-02-26 19:18:41 +00003451 // Consume the argument.
3452 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003453 if (argIndex < NumDataArgs) {
3454 // The check to see if the argIndex is valid will come later.
3455 // We set the bit here because we may exit early from this
3456 // function if we encounter some other error.
3457 CoveredArgs.set(argIndex);
3458 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003459
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003460 // FreeBSD kernel extensions.
3461 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3462 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3463 // We need at least two arguments.
3464 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3465 return false;
3466
3467 // Claim the second argument.
3468 CoveredArgs.set(argIndex + 1);
3469
3470 // Type check the first argument (int for %b, pointer for %D)
3471 const Expr *Ex = getDataArg(argIndex);
3472 const analyze_printf::ArgType &AT =
3473 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3474 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3475 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3476 EmitFormatDiagnostic(
3477 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3478 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3479 << false << Ex->getSourceRange(),
3480 Ex->getLocStart(), /*IsStringLocation*/false,
3481 getSpecifierRange(startSpecifier, specifierLen));
3482
3483 // Type check the second argument (char * for both %b and %D)
3484 Ex = getDataArg(argIndex + 1);
3485 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3486 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3487 EmitFormatDiagnostic(
3488 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3489 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3490 << false << Ex->getSourceRange(),
3491 Ex->getLocStart(), /*IsStringLocation*/false,
3492 getSpecifierRange(startSpecifier, specifierLen));
3493
3494 return true;
3495 }
3496
Ted Kremenek4a49d982010-02-26 19:18:41 +00003497 // Check for using an Objective-C specific conversion specifier
3498 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003499 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003500 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3501 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003502 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003503
Tom Careb49ec692010-06-17 19:00:27 +00003504 // Check for invalid use of field width
3505 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003506 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003507 startSpecifier, specifierLen);
3508 }
3509
3510 // Check for invalid use of precision
3511 if (!FS.hasValidPrecision()) {
3512 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3513 startSpecifier, specifierLen);
3514 }
3515
3516 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003517 if (!FS.hasValidThousandsGroupingPrefix())
3518 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003519 if (!FS.hasValidLeadingZeros())
3520 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3521 if (!FS.hasValidPlusPrefix())
3522 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003523 if (!FS.hasValidSpacePrefix())
3524 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003525 if (!FS.hasValidAlternativeForm())
3526 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3527 if (!FS.hasValidLeftJustified())
3528 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3529
3530 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003531 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3532 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3533 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003534 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3535 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3536 startSpecifier, specifierLen);
3537
3538 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003539 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003540 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3541 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003542 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003543 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003544 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003545 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3546 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003547
Jordan Rose92303592012-09-08 04:00:03 +00003548 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3549 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3550
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003551 // The remaining checks depend on the data arguments.
3552 if (HasVAListArg)
3553 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003554
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003555 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003556 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003557
Jordan Rose58bbe422012-07-19 18:10:08 +00003558 const Expr *Arg = getDataArg(argIndex);
3559 if (!Arg)
3560 return true;
3561
3562 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003563}
3564
Jordan Roseaee34382012-09-05 22:56:26 +00003565static bool requiresParensToAddCast(const Expr *E) {
3566 // FIXME: We should have a general way to reason about operator
3567 // precedence and whether parens are actually needed here.
3568 // Take care of a few common cases where they aren't.
3569 const Expr *Inside = E->IgnoreImpCasts();
3570 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3571 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3572
3573 switch (Inside->getStmtClass()) {
3574 case Stmt::ArraySubscriptExprClass:
3575 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003576 case Stmt::CharacterLiteralClass:
3577 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003578 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003579 case Stmt::FloatingLiteralClass:
3580 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003581 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003582 case Stmt::ObjCArrayLiteralClass:
3583 case Stmt::ObjCBoolLiteralExprClass:
3584 case Stmt::ObjCBoxedExprClass:
3585 case Stmt::ObjCDictionaryLiteralClass:
3586 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003587 case Stmt::ObjCIvarRefExprClass:
3588 case Stmt::ObjCMessageExprClass:
3589 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003590 case Stmt::ObjCStringLiteralClass:
3591 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003592 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003593 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003594 case Stmt::UnaryOperatorClass:
3595 return false;
3596 default:
3597 return true;
3598 }
3599}
3600
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003601static std::pair<QualType, StringRef>
3602shouldNotPrintDirectly(const ASTContext &Context,
3603 QualType IntendedTy,
3604 const Expr *E) {
3605 // Use a 'while' to peel off layers of typedefs.
3606 QualType TyTy = IntendedTy;
3607 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3608 StringRef Name = UserTy->getDecl()->getName();
3609 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3610 .Case("NSInteger", Context.LongTy)
3611 .Case("NSUInteger", Context.UnsignedLongTy)
3612 .Case("SInt32", Context.IntTy)
3613 .Case("UInt32", Context.UnsignedIntTy)
3614 .Default(QualType());
3615
3616 if (!CastTy.isNull())
3617 return std::make_pair(CastTy, Name);
3618
3619 TyTy = UserTy->desugar();
3620 }
3621
3622 // Strip parens if necessary.
3623 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3624 return shouldNotPrintDirectly(Context,
3625 PE->getSubExpr()->getType(),
3626 PE->getSubExpr());
3627
3628 // If this is a conditional expression, then its result type is constructed
3629 // via usual arithmetic conversions and thus there might be no necessary
3630 // typedef sugar there. Recurse to operands to check for NSInteger &
3631 // Co. usage condition.
3632 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3633 QualType TrueTy, FalseTy;
3634 StringRef TrueName, FalseName;
3635
3636 std::tie(TrueTy, TrueName) =
3637 shouldNotPrintDirectly(Context,
3638 CO->getTrueExpr()->getType(),
3639 CO->getTrueExpr());
3640 std::tie(FalseTy, FalseName) =
3641 shouldNotPrintDirectly(Context,
3642 CO->getFalseExpr()->getType(),
3643 CO->getFalseExpr());
3644
3645 if (TrueTy == FalseTy)
3646 return std::make_pair(TrueTy, TrueName);
3647 else if (TrueTy.isNull())
3648 return std::make_pair(FalseTy, FalseName);
3649 else if (FalseTy.isNull())
3650 return std::make_pair(TrueTy, TrueName);
3651 }
3652
3653 return std::make_pair(QualType(), StringRef());
3654}
3655
Richard Smith55ce3522012-06-25 20:30:08 +00003656bool
3657CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3658 const char *StartSpecifier,
3659 unsigned SpecifierLen,
3660 const Expr *E) {
3661 using namespace analyze_format_string;
3662 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003663 // Now type check the data expression that matches the
3664 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003665 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3666 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003667 if (!AT.isValid())
3668 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003669
Jordan Rose598ec092012-12-05 18:44:40 +00003670 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003671 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3672 ExprTy = TET->getUnderlyingExpr()->getType();
3673 }
3674
Jordan Rose598ec092012-12-05 18:44:40 +00003675 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003676 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003677
Jordan Rose22b74712012-09-05 22:56:19 +00003678 // Look through argument promotions for our error message's reported type.
3679 // This includes the integral and floating promotions, but excludes array
3680 // and function pointer decay; seeing that an argument intended to be a
3681 // string has type 'char [6]' is probably more confusing than 'char *'.
3682 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3683 if (ICE->getCastKind() == CK_IntegralCast ||
3684 ICE->getCastKind() == CK_FloatingCast) {
3685 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003686 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003687
3688 // Check if we didn't match because of an implicit cast from a 'char'
3689 // or 'short' to an 'int'. This is done because printf is a varargs
3690 // function.
3691 if (ICE->getType() == S.Context.IntTy ||
3692 ICE->getType() == S.Context.UnsignedIntTy) {
3693 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003694 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003695 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003696 }
Jordan Rose98709982012-06-04 22:48:57 +00003697 }
Jordan Rose598ec092012-12-05 18:44:40 +00003698 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3699 // Special case for 'a', which has type 'int' in C.
3700 // Note, however, that we do /not/ want to treat multibyte constants like
3701 // 'MooV' as characters! This form is deprecated but still exists.
3702 if (ExprTy == S.Context.IntTy)
3703 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3704 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003705 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003706
Jordan Rosebc53ed12014-05-31 04:12:14 +00003707 // Look through enums to their underlying type.
3708 bool IsEnum = false;
3709 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3710 ExprTy = EnumTy->getDecl()->getIntegerType();
3711 IsEnum = true;
3712 }
3713
Jordan Rose0e5badd2012-12-05 18:44:49 +00003714 // %C in an Objective-C context prints a unichar, not a wchar_t.
3715 // If the argument is an integer of some kind, believe the %C and suggest
3716 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003717 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003718 if (ObjCContext &&
3719 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3720 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3721 !ExprTy->isCharType()) {
3722 // 'unichar' is defined as a typedef of unsigned short, but we should
3723 // prefer using the typedef if it is visible.
3724 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003725
3726 // While we are here, check if the value is an IntegerLiteral that happens
3727 // to be within the valid range.
3728 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3729 const llvm::APInt &V = IL->getValue();
3730 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3731 return true;
3732 }
3733
Jordan Rose0e5badd2012-12-05 18:44:49 +00003734 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3735 Sema::LookupOrdinaryName);
3736 if (S.LookupName(Result, S.getCurScope())) {
3737 NamedDecl *ND = Result.getFoundDecl();
3738 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3739 if (TD->getUnderlyingType() == IntendedTy)
3740 IntendedTy = S.Context.getTypedefType(TD);
3741 }
3742 }
3743 }
3744
3745 // Special-case some of Darwin's platform-independence types by suggesting
3746 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003747 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00003748 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003749 QualType CastTy;
3750 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3751 if (!CastTy.isNull()) {
3752 IntendedTy = CastTy;
3753 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00003754 }
3755 }
3756
Jordan Rose22b74712012-09-05 22:56:19 +00003757 // We may be able to offer a FixItHint if it is a supported type.
3758 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003759 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003760 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003761
Jordan Rose22b74712012-09-05 22:56:19 +00003762 if (success) {
3763 // Get the fix string from the fixed format specifier
3764 SmallString<16> buf;
3765 llvm::raw_svector_ostream os(buf);
3766 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003767
Jordan Roseaee34382012-09-05 22:56:26 +00003768 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3769
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003770 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Jordan Rose0e5badd2012-12-05 18:44:49 +00003771 // In this case, the specifier is wrong and should be changed to match
3772 // the argument.
3773 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003774 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3775 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003776 << E->getSourceRange(),
3777 E->getLocStart(),
3778 /*IsStringLocation*/false,
3779 SpecRange,
3780 FixItHint::CreateReplacement(SpecRange, os.str()));
3781
3782 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003783 // The canonical type for formatting this value is different from the
3784 // actual type of the expression. (This occurs, for example, with Darwin's
3785 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3786 // should be printed as 'long' for 64-bit compatibility.)
3787 // Rather than emitting a normal format/argument mismatch, we want to
3788 // add a cast to the recommended type (and correct the format string
3789 // if necessary).
3790 SmallString<16> CastBuf;
3791 llvm::raw_svector_ostream CastFix(CastBuf);
3792 CastFix << "(";
3793 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3794 CastFix << ")";
3795
3796 SmallVector<FixItHint,4> Hints;
3797 if (!AT.matchesType(S.Context, IntendedTy))
3798 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3799
3800 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3801 // If there's already a cast present, just replace it.
3802 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3803 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3804
3805 } else if (!requiresParensToAddCast(E)) {
3806 // If the expression has high enough precedence,
3807 // just write the C-style cast.
3808 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3809 CastFix.str()));
3810 } else {
3811 // Otherwise, add parens around the expression as well as the cast.
3812 CastFix << "(";
3813 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3814 CastFix.str()));
3815
Alp Tokerb6cc5922014-05-03 03:45:55 +00003816 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003817 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3818 }
3819
Jordan Rose0e5badd2012-12-05 18:44:49 +00003820 if (ShouldNotPrintDirectly) {
3821 // The expression has a type that should not be printed directly.
3822 // We extract the name from the typedef because we don't want to show
3823 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003824 StringRef Name;
3825 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3826 Name = TypedefTy->getDecl()->getName();
3827 else
3828 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003829 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003830 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003831 << E->getSourceRange(),
3832 E->getLocStart(), /*IsStringLocation=*/false,
3833 SpecRange, Hints);
3834 } else {
3835 // In this case, the expression could be printed using a different
3836 // specifier, but we've decided that the specifier is probably correct
3837 // and we should cast instead. Just use the normal warning message.
3838 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003839 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3840 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003841 << E->getSourceRange(),
3842 E->getLocStart(), /*IsStringLocation*/false,
3843 SpecRange, Hints);
3844 }
Jordan Roseaee34382012-09-05 22:56:26 +00003845 }
Jordan Rose22b74712012-09-05 22:56:19 +00003846 } else {
3847 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3848 SpecifierLen);
3849 // Since the warning for passing non-POD types to variadic functions
3850 // was deferred until now, we emit a warning for non-POD
3851 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003852 switch (S.isValidVarArgType(ExprTy)) {
3853 case Sema::VAK_Valid:
3854 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003855 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003856 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3857 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003858 << CSR
3859 << E->getSourceRange(),
3860 E->getLocStart(), /*IsStringLocation*/false, CSR);
3861 break;
3862
3863 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00003864 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00003865 EmitFormatDiagnostic(
3866 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003867 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003868 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003869 << CallType
3870 << AT.getRepresentativeTypeName(S.Context)
3871 << CSR
3872 << E->getSourceRange(),
3873 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003874 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003875 break;
3876
3877 case Sema::VAK_Invalid:
3878 if (ExprTy->isObjCObjectType())
3879 EmitFormatDiagnostic(
3880 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3881 << S.getLangOpts().CPlusPlus11
3882 << ExprTy
3883 << CallType
3884 << AT.getRepresentativeTypeName(S.Context)
3885 << CSR
3886 << E->getSourceRange(),
3887 E->getLocStart(), /*IsStringLocation*/false, CSR);
3888 else
3889 // FIXME: If this is an initializer list, suggest removing the braces
3890 // or inserting a cast to the target type.
3891 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3892 << isa<InitListExpr>(E) << ExprTy << CallType
3893 << AT.getRepresentativeTypeName(S.Context)
3894 << E->getSourceRange();
3895 break;
3896 }
3897
3898 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3899 "format string specifier index out of range");
3900 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003901 }
3902
Ted Kremenekab278de2010-01-28 23:39:18 +00003903 return true;
3904}
3905
Ted Kremenek02087932010-07-16 02:11:22 +00003906//===--- CHECK: Scanf format string checking ------------------------------===//
3907
3908namespace {
3909class CheckScanfHandler : public CheckFormatHandler {
3910public:
3911 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3912 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003913 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003914 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003915 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003916 Sema::VariadicCallType CallType,
3917 llvm::SmallBitVector &CheckedVarArgs)
3918 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3919 numDataArgs, beg, hasVAListArg,
3920 Args, formatIdx, inFunctionCall, CallType,
3921 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003922 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003923
3924 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3925 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003926 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003927
3928 bool HandleInvalidScanfConversionSpecifier(
3929 const analyze_scanf::ScanfSpecifier &FS,
3930 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003931 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003932
Craig Toppere14c0f82014-03-12 04:55:44 +00003933 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003934};
Ted Kremenek019d2242010-01-29 01:50:07 +00003935}
Ted Kremenekab278de2010-01-28 23:39:18 +00003936
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003937void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3938 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003939 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3940 getLocationOfByte(end), /*IsStringLocation*/true,
3941 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003942}
3943
Ted Kremenekce815422010-07-19 21:25:57 +00003944bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3945 const analyze_scanf::ScanfSpecifier &FS,
3946 const char *startSpecifier,
3947 unsigned specifierLen) {
3948
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003949 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003950 FS.getConversionSpecifier();
3951
3952 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3953 getLocationOfByte(CS.getStart()),
3954 startSpecifier, specifierLen,
3955 CS.getStart(), CS.getLength());
3956}
3957
Ted Kremenek02087932010-07-16 02:11:22 +00003958bool CheckScanfHandler::HandleScanfSpecifier(
3959 const analyze_scanf::ScanfSpecifier &FS,
3960 const char *startSpecifier,
3961 unsigned specifierLen) {
3962
3963 using namespace analyze_scanf;
3964 using namespace analyze_format_string;
3965
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003966 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003967
Ted Kremenek6cd69422010-07-19 22:01:06 +00003968 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3969 // be used to decide if we are using positional arguments consistently.
3970 if (FS.consumesDataArgument()) {
3971 if (atFirstArg) {
3972 atFirstArg = false;
3973 usesPositionalArgs = FS.usesPositionalArg();
3974 }
3975 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003976 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3977 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003978 return false;
3979 }
Ted Kremenek02087932010-07-16 02:11:22 +00003980 }
3981
3982 // Check if the field with is non-zero.
3983 const OptionalAmount &Amt = FS.getFieldWidth();
3984 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3985 if (Amt.getConstantAmount() == 0) {
3986 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3987 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003988 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3989 getLocationOfByte(Amt.getStart()),
3990 /*IsStringLocation*/true, R,
3991 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003992 }
3993 }
3994
3995 if (!FS.consumesDataArgument()) {
3996 // FIXME: Technically specifying a precision or field width here
3997 // makes no sense. Worth issuing a warning at some point.
3998 return true;
3999 }
4000
4001 // Consume the argument.
4002 unsigned argIndex = FS.getArgIndex();
4003 if (argIndex < NumDataArgs) {
4004 // The check to see if the argIndex is valid will come later.
4005 // We set the bit here because we may exit early from this
4006 // function if we encounter some other error.
4007 CoveredArgs.set(argIndex);
4008 }
4009
Ted Kremenek4407ea42010-07-20 20:04:47 +00004010 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004011 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004012 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4013 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004014 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004015 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004016 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004017 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4018 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004019
Jordan Rose92303592012-09-08 04:00:03 +00004020 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4021 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4022
Ted Kremenek02087932010-07-16 02:11:22 +00004023 // The remaining checks depend on the data arguments.
4024 if (HasVAListArg)
4025 return true;
4026
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004027 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004028 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00004029
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004030 // Check that the argument type matches the format specifier.
4031 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004032 if (!Ex)
4033 return true;
4034
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004035 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
4036 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004037 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00004038 bool success = fixedFS.fixType(Ex->getType(),
4039 Ex->IgnoreImpCasts()->getType(),
4040 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004041
4042 if (success) {
4043 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004044 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004045 llvm::raw_svector_ostream os(buf);
4046 fixedFS.toString(os);
4047
4048 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004049 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4050 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004051 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00004052 Ex->getLocStart(),
4053 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004054 getSpecifierRange(startSpecifier, specifierLen),
4055 FixItHint::CreateReplacement(
4056 getSpecifierRange(startSpecifier, specifierLen),
4057 os.str()));
4058 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00004059 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004060 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4061 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00004062 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00004063 Ex->getLocStart(),
4064 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00004065 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004066 }
4067 }
4068
Ted Kremenek02087932010-07-16 02:11:22 +00004069 return true;
4070}
4071
4072void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004073 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004074 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004075 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004076 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004077 bool inFunctionCall, VariadicCallType CallType,
4078 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004079
Ted Kremenekab278de2010-01-28 23:39:18 +00004080 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004081 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004082 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004083 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004084 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4085 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004086 return;
4087 }
Ted Kremenek02087932010-07-16 02:11:22 +00004088
Ted Kremenekab278de2010-01-28 23:39:18 +00004089 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004090 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004091 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004092 // Account for cases where the string literal is truncated in a declaration.
4093 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4094 assert(T && "String literal not of constant array type!");
4095 size_t TypeSize = T->getSize().getZExtValue();
4096 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004097 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004098
4099 // Emit a warning if the string literal is truncated and does not contain an
4100 // embedded null character.
4101 if (TypeSize <= StrRef.size() &&
4102 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4103 CheckFormatHandler::EmitFormatDiagnostic(
4104 *this, inFunctionCall, Args[format_idx],
4105 PDiag(diag::warn_printf_format_string_not_null_terminated),
4106 FExpr->getLocStart(),
4107 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4108 return;
4109 }
4110
Ted Kremenekab278de2010-01-28 23:39:18 +00004111 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004112 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004113 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004114 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004115 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4116 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004117 return;
4118 }
Ted Kremenek02087932010-07-16 02:11:22 +00004119
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004120 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004121 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004122 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004123 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004124 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004125 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004126
Hans Wennborg23926bd2011-12-15 10:25:47 +00004127 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004128 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004129 Context.getTargetInfo(),
4130 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004131 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004132 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004133 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004134 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004135 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004136
Hans Wennborg23926bd2011-12-15 10:25:47 +00004137 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004138 getLangOpts(),
4139 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004140 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004141 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004142}
4143
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004144bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4145 // Str - The format string. NOTE: this is NOT null-terminated!
4146 StringRef StrRef = FExpr->getString();
4147 const char *Str = StrRef.data();
4148 // Account for cases where the string literal is truncated in a declaration.
4149 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4150 assert(T && "String literal not of constant array type!");
4151 size_t TypeSize = T->getSize().getZExtValue();
4152 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4153 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4154 getLangOpts(),
4155 Context.getTargetInfo());
4156}
4157
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004158//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4159
4160// Returns the related absolute value function that is larger, of 0 if one
4161// does not exist.
4162static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4163 switch (AbsFunction) {
4164 default:
4165 return 0;
4166
4167 case Builtin::BI__builtin_abs:
4168 return Builtin::BI__builtin_labs;
4169 case Builtin::BI__builtin_labs:
4170 return Builtin::BI__builtin_llabs;
4171 case Builtin::BI__builtin_llabs:
4172 return 0;
4173
4174 case Builtin::BI__builtin_fabsf:
4175 return Builtin::BI__builtin_fabs;
4176 case Builtin::BI__builtin_fabs:
4177 return Builtin::BI__builtin_fabsl;
4178 case Builtin::BI__builtin_fabsl:
4179 return 0;
4180
4181 case Builtin::BI__builtin_cabsf:
4182 return Builtin::BI__builtin_cabs;
4183 case Builtin::BI__builtin_cabs:
4184 return Builtin::BI__builtin_cabsl;
4185 case Builtin::BI__builtin_cabsl:
4186 return 0;
4187
4188 case Builtin::BIabs:
4189 return Builtin::BIlabs;
4190 case Builtin::BIlabs:
4191 return Builtin::BIllabs;
4192 case Builtin::BIllabs:
4193 return 0;
4194
4195 case Builtin::BIfabsf:
4196 return Builtin::BIfabs;
4197 case Builtin::BIfabs:
4198 return Builtin::BIfabsl;
4199 case Builtin::BIfabsl:
4200 return 0;
4201
4202 case Builtin::BIcabsf:
4203 return Builtin::BIcabs;
4204 case Builtin::BIcabs:
4205 return Builtin::BIcabsl;
4206 case Builtin::BIcabsl:
4207 return 0;
4208 }
4209}
4210
4211// Returns the argument type of the absolute value function.
4212static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4213 unsigned AbsType) {
4214 if (AbsType == 0)
4215 return QualType();
4216
4217 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4218 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4219 if (Error != ASTContext::GE_None)
4220 return QualType();
4221
4222 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4223 if (!FT)
4224 return QualType();
4225
4226 if (FT->getNumParams() != 1)
4227 return QualType();
4228
4229 return FT->getParamType(0);
4230}
4231
4232// Returns the best absolute value function, or zero, based on type and
4233// current absolute value function.
4234static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4235 unsigned AbsFunctionKind) {
4236 unsigned BestKind = 0;
4237 uint64_t ArgSize = Context.getTypeSize(ArgType);
4238 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4239 Kind = getLargerAbsoluteValueFunction(Kind)) {
4240 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4241 if (Context.getTypeSize(ParamType) >= ArgSize) {
4242 if (BestKind == 0)
4243 BestKind = Kind;
4244 else if (Context.hasSameType(ParamType, ArgType)) {
4245 BestKind = Kind;
4246 break;
4247 }
4248 }
4249 }
4250 return BestKind;
4251}
4252
4253enum AbsoluteValueKind {
4254 AVK_Integer,
4255 AVK_Floating,
4256 AVK_Complex
4257};
4258
4259static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4260 if (T->isIntegralOrEnumerationType())
4261 return AVK_Integer;
4262 if (T->isRealFloatingType())
4263 return AVK_Floating;
4264 if (T->isAnyComplexType())
4265 return AVK_Complex;
4266
4267 llvm_unreachable("Type not integer, floating, or complex");
4268}
4269
4270// Changes the absolute value function to a different type. Preserves whether
4271// the function is a builtin.
4272static unsigned changeAbsFunction(unsigned AbsKind,
4273 AbsoluteValueKind ValueKind) {
4274 switch (ValueKind) {
4275 case AVK_Integer:
4276 switch (AbsKind) {
4277 default:
4278 return 0;
4279 case Builtin::BI__builtin_fabsf:
4280 case Builtin::BI__builtin_fabs:
4281 case Builtin::BI__builtin_fabsl:
4282 case Builtin::BI__builtin_cabsf:
4283 case Builtin::BI__builtin_cabs:
4284 case Builtin::BI__builtin_cabsl:
4285 return Builtin::BI__builtin_abs;
4286 case Builtin::BIfabsf:
4287 case Builtin::BIfabs:
4288 case Builtin::BIfabsl:
4289 case Builtin::BIcabsf:
4290 case Builtin::BIcabs:
4291 case Builtin::BIcabsl:
4292 return Builtin::BIabs;
4293 }
4294 case AVK_Floating:
4295 switch (AbsKind) {
4296 default:
4297 return 0;
4298 case Builtin::BI__builtin_abs:
4299 case Builtin::BI__builtin_labs:
4300 case Builtin::BI__builtin_llabs:
4301 case Builtin::BI__builtin_cabsf:
4302 case Builtin::BI__builtin_cabs:
4303 case Builtin::BI__builtin_cabsl:
4304 return Builtin::BI__builtin_fabsf;
4305 case Builtin::BIabs:
4306 case Builtin::BIlabs:
4307 case Builtin::BIllabs:
4308 case Builtin::BIcabsf:
4309 case Builtin::BIcabs:
4310 case Builtin::BIcabsl:
4311 return Builtin::BIfabsf;
4312 }
4313 case AVK_Complex:
4314 switch (AbsKind) {
4315 default:
4316 return 0;
4317 case Builtin::BI__builtin_abs:
4318 case Builtin::BI__builtin_labs:
4319 case Builtin::BI__builtin_llabs:
4320 case Builtin::BI__builtin_fabsf:
4321 case Builtin::BI__builtin_fabs:
4322 case Builtin::BI__builtin_fabsl:
4323 return Builtin::BI__builtin_cabsf;
4324 case Builtin::BIabs:
4325 case Builtin::BIlabs:
4326 case Builtin::BIllabs:
4327 case Builtin::BIfabsf:
4328 case Builtin::BIfabs:
4329 case Builtin::BIfabsl:
4330 return Builtin::BIcabsf;
4331 }
4332 }
4333 llvm_unreachable("Unable to convert function");
4334}
4335
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004336static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004337 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4338 if (!FnInfo)
4339 return 0;
4340
4341 switch (FDecl->getBuiltinID()) {
4342 default:
4343 return 0;
4344 case Builtin::BI__builtin_abs:
4345 case Builtin::BI__builtin_fabs:
4346 case Builtin::BI__builtin_fabsf:
4347 case Builtin::BI__builtin_fabsl:
4348 case Builtin::BI__builtin_labs:
4349 case Builtin::BI__builtin_llabs:
4350 case Builtin::BI__builtin_cabs:
4351 case Builtin::BI__builtin_cabsf:
4352 case Builtin::BI__builtin_cabsl:
4353 case Builtin::BIabs:
4354 case Builtin::BIlabs:
4355 case Builtin::BIllabs:
4356 case Builtin::BIfabs:
4357 case Builtin::BIfabsf:
4358 case Builtin::BIfabsl:
4359 case Builtin::BIcabs:
4360 case Builtin::BIcabsf:
4361 case Builtin::BIcabsl:
4362 return FDecl->getBuiltinID();
4363 }
4364 llvm_unreachable("Unknown Builtin type");
4365}
4366
4367// If the replacement is valid, emit a note with replacement function.
4368// Additionally, suggest including the proper header if not already included.
4369static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004370 unsigned AbsKind, QualType ArgType) {
4371 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004372 const char *HeaderName = nullptr;
4373 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004374 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4375 FunctionName = "std::abs";
4376 if (ArgType->isIntegralOrEnumerationType()) {
4377 HeaderName = "cstdlib";
4378 } else if (ArgType->isRealFloatingType()) {
4379 HeaderName = "cmath";
4380 } else {
4381 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004382 }
Richard Trieubeffb832014-04-15 23:47:53 +00004383
4384 // Lookup all std::abs
4385 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004386 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004387 R.suppressDiagnostics();
4388 S.LookupQualifiedName(R, Std);
4389
4390 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004391 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004392 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4393 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4394 } else {
4395 FDecl = dyn_cast<FunctionDecl>(I);
4396 }
4397 if (!FDecl)
4398 continue;
4399
4400 // Found std::abs(), check that they are the right ones.
4401 if (FDecl->getNumParams() != 1)
4402 continue;
4403
4404 // Check that the parameter type can handle the argument.
4405 QualType ParamType = FDecl->getParamDecl(0)->getType();
4406 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4407 S.Context.getTypeSize(ArgType) <=
4408 S.Context.getTypeSize(ParamType)) {
4409 // Found a function, don't need the header hint.
4410 EmitHeaderHint = false;
4411 break;
4412 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004413 }
Richard Trieubeffb832014-04-15 23:47:53 +00004414 }
4415 } else {
4416 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4417 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4418
4419 if (HeaderName) {
4420 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4421 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4422 R.suppressDiagnostics();
4423 S.LookupName(R, S.getCurScope());
4424
4425 if (R.isSingleResult()) {
4426 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4427 if (FD && FD->getBuiltinID() == AbsKind) {
4428 EmitHeaderHint = false;
4429 } else {
4430 return;
4431 }
4432 } else if (!R.empty()) {
4433 return;
4434 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004435 }
4436 }
4437
4438 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004439 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004440
Richard Trieubeffb832014-04-15 23:47:53 +00004441 if (!HeaderName)
4442 return;
4443
4444 if (!EmitHeaderHint)
4445 return;
4446
Alp Toker5d96e0a2014-07-11 20:53:51 +00004447 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4448 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004449}
4450
4451static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4452 if (!FDecl)
4453 return false;
4454
4455 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4456 return false;
4457
4458 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4459
4460 while (ND && ND->isInlineNamespace()) {
4461 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004462 }
Richard Trieubeffb832014-04-15 23:47:53 +00004463
4464 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4465 return false;
4466
4467 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4468 return false;
4469
4470 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004471}
4472
4473// Warn when using the wrong abs() function.
4474void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4475 const FunctionDecl *FDecl,
4476 IdentifierInfo *FnInfo) {
4477 if (Call->getNumArgs() != 1)
4478 return;
4479
4480 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004481 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4482 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004483 return;
4484
4485 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4486 QualType ParamType = Call->getArg(0)->getType();
4487
Alp Toker5d96e0a2014-07-11 20:53:51 +00004488 // Unsigned types cannot be negative. Suggest removing the absolute value
4489 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004490 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004491 const char *FunctionName =
4492 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004493 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4494 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004495 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004496 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4497 return;
4498 }
4499
Richard Trieubeffb832014-04-15 23:47:53 +00004500 // std::abs has overloads which prevent most of the absolute value problems
4501 // from occurring.
4502 if (IsStdAbs)
4503 return;
4504
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004505 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4506 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4507
4508 // The argument and parameter are the same kind. Check if they are the right
4509 // size.
4510 if (ArgValueKind == ParamValueKind) {
4511 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4512 return;
4513
4514 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4515 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4516 << FDecl << ArgType << ParamType;
4517
4518 if (NewAbsKind == 0)
4519 return;
4520
4521 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004522 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004523 return;
4524 }
4525
4526 // ArgValueKind != ParamValueKind
4527 // The wrong type of absolute value function was used. Attempt to find the
4528 // proper one.
4529 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4530 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4531 if (NewAbsKind == 0)
4532 return;
4533
4534 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4535 << FDecl << ParamValueKind << ArgValueKind;
4536
4537 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004538 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004539 return;
4540}
4541
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004542//===--- CHECK: Standard memory functions ---------------------------------===//
4543
Nico Weber0e6daef2013-12-26 23:38:39 +00004544/// \brief Takes the expression passed to the size_t parameter of functions
4545/// such as memcmp, strncat, etc and warns if it's a comparison.
4546///
4547/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4548static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4549 IdentifierInfo *FnName,
4550 SourceLocation FnLoc,
4551 SourceLocation RParenLoc) {
4552 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4553 if (!Size)
4554 return false;
4555
4556 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4557 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4558 return false;
4559
Nico Weber0e6daef2013-12-26 23:38:39 +00004560 SourceRange SizeRange = Size->getSourceRange();
4561 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4562 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004563 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004564 << FnName << FixItHint::CreateInsertion(
4565 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004566 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004567 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004568 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004569 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4570 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004571
4572 return true;
4573}
4574
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004575/// \brief Determine whether the given type is or contains a dynamic class type
4576/// (e.g., whether it has a vtable).
4577static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4578 bool &IsContained) {
4579 // Look through array types while ignoring qualifiers.
4580 const Type *Ty = T->getBaseElementTypeUnsafe();
4581 IsContained = false;
4582
4583 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4584 RD = RD ? RD->getDefinition() : nullptr;
4585 if (!RD)
4586 return nullptr;
4587
4588 if (RD->isDynamicClass())
4589 return RD;
4590
4591 // Check all the fields. If any bases were dynamic, the class is dynamic.
4592 // It's impossible for a class to transitively contain itself by value, so
4593 // infinite recursion is impossible.
4594 for (auto *FD : RD->fields()) {
4595 bool SubContained;
4596 if (const CXXRecordDecl *ContainedRD =
4597 getContainedDynamicClass(FD->getType(), SubContained)) {
4598 IsContained = true;
4599 return ContainedRD;
4600 }
4601 }
4602
4603 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004604}
4605
Chandler Carruth889ed862011-06-21 23:04:20 +00004606/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004607/// otherwise returns NULL.
4608static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004609 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004610 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4611 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4612 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004613
Craig Topperc3ec1492014-05-26 06:22:03 +00004614 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004615}
4616
Chandler Carruth889ed862011-06-21 23:04:20 +00004617/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004618static QualType getSizeOfArgType(const Expr* E) {
4619 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4620 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4621 if (SizeOf->getKind() == clang::UETT_SizeOf)
4622 return SizeOf->getTypeOfArgument();
4623
4624 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004625}
4626
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004627/// \brief Check for dangerous or invalid arguments to memset().
4628///
Chandler Carruthac687262011-06-03 06:23:57 +00004629/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004630/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4631/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004632///
4633/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004634void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004635 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004636 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004637 assert(BId != 0);
4638
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004639 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004640 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004641 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004642 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004643 return;
4644
Anna Zaks22122702012-01-17 00:37:07 +00004645 unsigned LastArg = (BId == Builtin::BImemset ||
4646 BId == Builtin::BIstrndup ? 1 : 2);
4647 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004648 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004649
Nico Weber0e6daef2013-12-26 23:38:39 +00004650 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4651 Call->getLocStart(), Call->getRParenLoc()))
4652 return;
4653
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004654 // We have special checking when the length is a sizeof expression.
4655 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4656 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4657 llvm::FoldingSetNodeID SizeOfArgID;
4658
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004659 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4660 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004661 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004662
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004663 QualType DestTy = Dest->getType();
4664 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4665 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004666
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004667 // Never warn about void type pointers. This can be used to suppress
4668 // false positives.
4669 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004670 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004671
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004672 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4673 // actually comparing the expressions for equality. Because computing the
4674 // expression IDs can be expensive, we only do this if the diagnostic is
4675 // enabled.
4676 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004677 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4678 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004679 // We only compute IDs for expressions if the warning is enabled, and
4680 // cache the sizeof arg's ID.
4681 if (SizeOfArgID == llvm::FoldingSetNodeID())
4682 SizeOfArg->Profile(SizeOfArgID, Context, true);
4683 llvm::FoldingSetNodeID DestID;
4684 Dest->Profile(DestID, Context, true);
4685 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004686 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4687 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004688 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004689 StringRef ReadableName = FnName->getName();
4690
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004691 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004692 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004693 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004694 if (!PointeeTy->isIncompleteType() &&
4695 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004696 ActionIdx = 2; // If the pointee's size is sizeof(char),
4697 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004698
4699 // If the function is defined as a builtin macro, do not show macro
4700 // expansion.
4701 SourceLocation SL = SizeOfArg->getExprLoc();
4702 SourceRange DSR = Dest->getSourceRange();
4703 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004704 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004705
4706 if (SM.isMacroArgExpansion(SL)) {
4707 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4708 SL = SM.getSpellingLoc(SL);
4709 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4710 SM.getSpellingLoc(DSR.getEnd()));
4711 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4712 SM.getSpellingLoc(SSR.getEnd()));
4713 }
4714
Anna Zaksd08d9152012-05-30 23:14:52 +00004715 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004716 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004717 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004718 << PointeeTy
4719 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004720 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004721 << SSR);
4722 DiagRuntimeBehavior(SL, SizeOfArg,
4723 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4724 << ActionIdx
4725 << SSR);
4726
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004727 break;
4728 }
4729 }
4730
4731 // Also check for cases where the sizeof argument is the exact same
4732 // type as the memory argument, and where it points to a user-defined
4733 // record type.
4734 if (SizeOfArgTy != QualType()) {
4735 if (PointeeTy->isRecordType() &&
4736 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4737 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4738 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4739 << FnName << SizeOfArgTy << ArgIdx
4740 << PointeeTy << Dest->getSourceRange()
4741 << LenExpr->getSourceRange());
4742 break;
4743 }
Nico Weberc5e73862011-06-14 16:14:58 +00004744 }
4745
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004746 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004747 bool IsContained;
4748 if (const CXXRecordDecl *ContainedRD =
4749 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004750
4751 unsigned OperationType = 0;
4752 // "overwritten" if we're warning about the destination for any call
4753 // but memcmp; otherwise a verb appropriate to the call.
4754 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4755 if (BId == Builtin::BImemcpy)
4756 OperationType = 1;
4757 else if(BId == Builtin::BImemmove)
4758 OperationType = 2;
4759 else if (BId == Builtin::BImemcmp)
4760 OperationType = 3;
4761 }
4762
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004763 DiagRuntimeBehavior(
4764 Dest->getExprLoc(), Dest,
4765 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004766 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004767 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004768 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004769 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4770 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004771 DiagRuntimeBehavior(
4772 Dest->getExprLoc(), Dest,
4773 PDiag(diag::warn_arc_object_memaccess)
4774 << ArgIdx << FnName << PointeeTy
4775 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004776 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004777 continue;
John McCall31168b02011-06-15 23:02:42 +00004778
4779 DiagRuntimeBehavior(
4780 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004781 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004782 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4783 break;
4784 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004785 }
4786}
4787
Ted Kremenek6865f772011-08-18 20:55:45 +00004788// A little helper routine: ignore addition and subtraction of integer literals.
4789// This intentionally does not ignore all integer constant expressions because
4790// we don't want to remove sizeof().
4791static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4792 Ex = Ex->IgnoreParenCasts();
4793
4794 for (;;) {
4795 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4796 if (!BO || !BO->isAdditiveOp())
4797 break;
4798
4799 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4800 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4801
4802 if (isa<IntegerLiteral>(RHS))
4803 Ex = LHS;
4804 else if (isa<IntegerLiteral>(LHS))
4805 Ex = RHS;
4806 else
4807 break;
4808 }
4809
4810 return Ex;
4811}
4812
Anna Zaks13b08572012-08-08 21:42:23 +00004813static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4814 ASTContext &Context) {
4815 // Only handle constant-sized or VLAs, but not flexible members.
4816 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4817 // Only issue the FIXIT for arrays of size > 1.
4818 if (CAT->getSize().getSExtValue() <= 1)
4819 return false;
4820 } else if (!Ty->isVariableArrayType()) {
4821 return false;
4822 }
4823 return true;
4824}
4825
Ted Kremenek6865f772011-08-18 20:55:45 +00004826// Warn if the user has made the 'size' argument to strlcpy or strlcat
4827// be the size of the source, instead of the destination.
4828void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4829 IdentifierInfo *FnName) {
4830
4831 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004832 unsigned NumArgs = Call->getNumArgs();
4833 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004834 return;
4835
4836 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4837 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004838 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004839
4840 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4841 Call->getLocStart(), Call->getRParenLoc()))
4842 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004843
4844 // Look for 'strlcpy(dst, x, sizeof(x))'
4845 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4846 CompareWithSrc = Ex;
4847 else {
4848 // Look for 'strlcpy(dst, x, strlen(x))'
4849 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004850 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4851 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004852 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4853 }
4854 }
4855
4856 if (!CompareWithSrc)
4857 return;
4858
4859 // Determine if the argument to sizeof/strlen is equal to the source
4860 // argument. In principle there's all kinds of things you could do
4861 // here, for instance creating an == expression and evaluating it with
4862 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4863 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4864 if (!SrcArgDRE)
4865 return;
4866
4867 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4868 if (!CompareWithSrcDRE ||
4869 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4870 return;
4871
4872 const Expr *OriginalSizeArg = Call->getArg(2);
4873 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4874 << OriginalSizeArg->getSourceRange() << FnName;
4875
4876 // Output a FIXIT hint if the destination is an array (rather than a
4877 // pointer to an array). This could be enhanced to handle some
4878 // pointers if we know the actual size, like if DstArg is 'array+2'
4879 // we could say 'sizeof(array)-2'.
4880 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004881 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004882 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004883
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004884 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004885 llvm::raw_svector_ostream OS(sizeString);
4886 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004887 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004888 OS << ")";
4889
4890 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4891 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4892 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004893}
4894
Anna Zaks314cd092012-02-01 19:08:57 +00004895/// Check if two expressions refer to the same declaration.
4896static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4897 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4898 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4899 return D1->getDecl() == D2->getDecl();
4900 return false;
4901}
4902
4903static const Expr *getStrlenExprArg(const Expr *E) {
4904 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4905 const FunctionDecl *FD = CE->getDirectCallee();
4906 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004907 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004908 return CE->getArg(0)->IgnoreParenCasts();
4909 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004910 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004911}
4912
4913// Warn on anti-patterns as the 'size' argument to strncat.
4914// The correct size argument should look like following:
4915// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4916void Sema::CheckStrncatArguments(const CallExpr *CE,
4917 IdentifierInfo *FnName) {
4918 // Don't crash if the user has the wrong number of arguments.
4919 if (CE->getNumArgs() < 3)
4920 return;
4921 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4922 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4923 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4924
Nico Weber0e6daef2013-12-26 23:38:39 +00004925 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4926 CE->getRParenLoc()))
4927 return;
4928
Anna Zaks314cd092012-02-01 19:08:57 +00004929 // Identify common expressions, which are wrongly used as the size argument
4930 // to strncat and may lead to buffer overflows.
4931 unsigned PatternType = 0;
4932 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4933 // - sizeof(dst)
4934 if (referToTheSameDecl(SizeOfArg, DstArg))
4935 PatternType = 1;
4936 // - sizeof(src)
4937 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4938 PatternType = 2;
4939 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4940 if (BE->getOpcode() == BO_Sub) {
4941 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4942 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4943 // - sizeof(dst) - strlen(dst)
4944 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4945 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4946 PatternType = 1;
4947 // - sizeof(src) - (anything)
4948 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4949 PatternType = 2;
4950 }
4951 }
4952
4953 if (PatternType == 0)
4954 return;
4955
Anna Zaks5069aa32012-02-03 01:27:37 +00004956 // Generate the diagnostic.
4957 SourceLocation SL = LenArg->getLocStart();
4958 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004959 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004960
4961 // If the function is defined as a builtin macro, do not show macro expansion.
4962 if (SM.isMacroArgExpansion(SL)) {
4963 SL = SM.getSpellingLoc(SL);
4964 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4965 SM.getSpellingLoc(SR.getEnd()));
4966 }
4967
Anna Zaks13b08572012-08-08 21:42:23 +00004968 // Check if the destination is an array (rather than a pointer to an array).
4969 QualType DstTy = DstArg->getType();
4970 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4971 Context);
4972 if (!isKnownSizeArray) {
4973 if (PatternType == 1)
4974 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4975 else
4976 Diag(SL, diag::warn_strncat_src_size) << SR;
4977 return;
4978 }
4979
Anna Zaks314cd092012-02-01 19:08:57 +00004980 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004981 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004982 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004983 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004984
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004985 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004986 llvm::raw_svector_ostream OS(sizeString);
4987 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004988 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004989 OS << ") - ";
4990 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004991 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004992 OS << ") - 1";
4993
Anna Zaks5069aa32012-02-03 01:27:37 +00004994 Diag(SL, diag::note_strncat_wrong_size)
4995 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004996}
4997
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004998//===--- CHECK: Return Address of Stack Variable --------------------------===//
4999
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005000static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5001 Decl *ParentDecl);
5002static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5003 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005004
5005/// CheckReturnStackAddr - Check if a return statement returns the address
5006/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005007static void
5008CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5009 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005010
Craig Topperc3ec1492014-05-26 06:22:03 +00005011 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005012 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005013
5014 // Perform checking for returned stack addresses, local blocks,
5015 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005016 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005017 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005018 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005019 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005020 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005021 }
5022
Craig Topperc3ec1492014-05-26 06:22:03 +00005023 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005024 return; // Nothing suspicious was found.
5025
5026 SourceLocation diagLoc;
5027 SourceRange diagRange;
5028 if (refVars.empty()) {
5029 diagLoc = stackE->getLocStart();
5030 diagRange = stackE->getSourceRange();
5031 } else {
5032 // We followed through a reference variable. 'stackE' contains the
5033 // problematic expression but we will warn at the return statement pointing
5034 // at the reference variable. We will later display the "trail" of
5035 // reference variables using notes.
5036 diagLoc = refVars[0]->getLocStart();
5037 diagRange = refVars[0]->getSourceRange();
5038 }
5039
5040 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005041 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005042 : diag::warn_ret_stack_addr)
5043 << DR->getDecl()->getDeclName() << diagRange;
5044 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005045 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005046 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005047 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005048 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005049 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5050 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005051 << diagRange;
5052 }
5053
5054 // Display the "trail" of reference variables that we followed until we
5055 // found the problematic expression using notes.
5056 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5057 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5058 // If this var binds to another reference var, show the range of the next
5059 // var, otherwise the var binds to the problematic expression, in which case
5060 // show the range of the expression.
5061 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5062 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005063 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5064 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005065 }
5066}
5067
5068/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5069/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005070/// to a location on the stack, a local block, an address of a label, or a
5071/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005072/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005073/// encounter a subexpression that (1) clearly does not lead to one of the
5074/// above problematic expressions (2) is something we cannot determine leads to
5075/// a problematic expression based on such local checking.
5076///
5077/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5078/// the expression that they point to. Such variables are added to the
5079/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005080///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005081/// EvalAddr processes expressions that are pointers that are used as
5082/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005083/// At the base case of the recursion is a check for the above problematic
5084/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005085///
5086/// This implementation handles:
5087///
5088/// * pointer-to-pointer casts
5089/// * implicit conversions from array references to pointers
5090/// * taking the address of fields
5091/// * arbitrary interplay between "&" and "*" operators
5092/// * pointer arithmetic from an address of a stack variable
5093/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005094static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5095 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005096 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005097 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005098
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005099 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005100 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005101 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005102 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005103 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005104
Peter Collingbourne91147592011-04-15 00:35:48 +00005105 E = E->IgnoreParens();
5106
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005107 // Our "symbolic interpreter" is just a dispatch off the currently
5108 // viewed AST node. We then recursively traverse the AST by calling
5109 // EvalAddr and EvalVal appropriately.
5110 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005111 case Stmt::DeclRefExprClass: {
5112 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5113
Richard Smith40f08eb2014-01-30 22:05:38 +00005114 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005115 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005116 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005117
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005118 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5119 // If this is a reference variable, follow through to the expression that
5120 // it points to.
5121 if (V->hasLocalStorage() &&
5122 V->getType()->isReferenceType() && V->hasInit()) {
5123 // Add the reference variable to the "trail".
5124 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005125 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005126 }
5127
Craig Topperc3ec1492014-05-26 06:22:03 +00005128 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005129 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005130
Chris Lattner934edb22007-12-28 05:31:15 +00005131 case Stmt::UnaryOperatorClass: {
5132 // The only unary operator that make sense to handle here
5133 // is AddrOf. All others don't make sense as pointers.
5134 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005135
John McCalle3027922010-08-25 11:45:40 +00005136 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005137 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005138 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005139 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005140 }
Mike Stump11289f42009-09-09 15:08:12 +00005141
Chris Lattner934edb22007-12-28 05:31:15 +00005142 case Stmt::BinaryOperatorClass: {
5143 // Handle pointer arithmetic. All other binary operators are not valid
5144 // in this context.
5145 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005146 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005147
John McCalle3027922010-08-25 11:45:40 +00005148 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005149 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005150
Chris Lattner934edb22007-12-28 05:31:15 +00005151 Expr *Base = B->getLHS();
5152
5153 // Determine which argument is the real pointer base. It could be
5154 // the RHS argument instead of the LHS.
5155 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005156
Chris Lattner934edb22007-12-28 05:31:15 +00005157 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005158 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005159 }
Steve Naroff2752a172008-09-10 19:17:48 +00005160
Chris Lattner934edb22007-12-28 05:31:15 +00005161 // For conditional operators we need to see if either the LHS or RHS are
5162 // valid DeclRefExpr*s. If one of them is valid, we return it.
5163 case Stmt::ConditionalOperatorClass: {
5164 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005165
Chris Lattner934edb22007-12-28 05:31:15 +00005166 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005167 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5168 if (Expr *LHSExpr = C->getLHS()) {
5169 // In C++, we can have a throw-expression, which has 'void' type.
5170 if (!LHSExpr->getType()->isVoidType())
5171 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005172 return LHS;
5173 }
Chris Lattner934edb22007-12-28 05:31:15 +00005174
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005175 // In C++, we can have a throw-expression, which has 'void' type.
5176 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005177 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005178
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005179 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005180 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005181
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005182 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005183 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005184 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005185 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005186
5187 case Stmt::AddrLabelExprClass:
5188 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005189
John McCall28fc7092011-11-10 05:35:25 +00005190 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005191 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5192 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005193
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005194 // For casts, we need to handle conversions from arrays to
5195 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005196 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005197 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005198 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005199 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005200 case Stmt::CXXStaticCastExprClass:
5201 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005202 case Stmt::CXXConstCastExprClass:
5203 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005204 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5205 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005206 case CK_LValueToRValue:
5207 case CK_NoOp:
5208 case CK_BaseToDerived:
5209 case CK_DerivedToBase:
5210 case CK_UncheckedDerivedToBase:
5211 case CK_Dynamic:
5212 case CK_CPointerToObjCPointerCast:
5213 case CK_BlockPointerToObjCPointerCast:
5214 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005215 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005216
5217 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005218 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005219
Richard Trieudadefde2014-07-02 04:39:38 +00005220 case CK_BitCast:
5221 if (SubExpr->getType()->isAnyPointerType() ||
5222 SubExpr->getType()->isBlockPointerType() ||
5223 SubExpr->getType()->isObjCQualifiedIdType())
5224 return EvalAddr(SubExpr, refVars, ParentDecl);
5225 else
5226 return nullptr;
5227
Eli Friedman8195ad72012-02-23 23:04:32 +00005228 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005229 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005230 }
Chris Lattner934edb22007-12-28 05:31:15 +00005231 }
Mike Stump11289f42009-09-09 15:08:12 +00005232
Douglas Gregorfe314812011-06-21 17:03:29 +00005233 case Stmt::MaterializeTemporaryExprClass:
5234 if (Expr *Result = EvalAddr(
5235 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005236 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005237 return Result;
5238
5239 return E;
5240
Chris Lattner934edb22007-12-28 05:31:15 +00005241 // Everything else: we simply don't reason about them.
5242 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005243 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005244 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005245}
Mike Stump11289f42009-09-09 15:08:12 +00005246
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005247
5248/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5249/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005250static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5251 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005252do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005253 // We should only be called for evaluating non-pointer expressions, or
5254 // expressions with a pointer type that are not used as references but instead
5255 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005256
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005257 // Our "symbolic interpreter" is just a dispatch off the currently
5258 // viewed AST node. We then recursively traverse the AST by calling
5259 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005260
5261 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005262 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005263 case Stmt::ImplicitCastExprClass: {
5264 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005265 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005266 E = IE->getSubExpr();
5267 continue;
5268 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005269 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005270 }
5271
John McCall28fc7092011-11-10 05:35:25 +00005272 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005273 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005274
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005275 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005276 // When we hit a DeclRefExpr we are looking at code that refers to a
5277 // variable's name. If it's not a reference variable we check if it has
5278 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005279 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005280
Richard Smith40f08eb2014-01-30 22:05:38 +00005281 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005282 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005283 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005284
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005285 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5286 // Check if it refers to itself, e.g. "int& i = i;".
5287 if (V == ParentDecl)
5288 return DR;
5289
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005290 if (V->hasLocalStorage()) {
5291 if (!V->getType()->isReferenceType())
5292 return DR;
5293
5294 // Reference variable, follow through to the expression that
5295 // it points to.
5296 if (V->hasInit()) {
5297 // Add the reference variable to the "trail".
5298 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005299 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005300 }
5301 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005302 }
Mike Stump11289f42009-09-09 15:08:12 +00005303
Craig Topperc3ec1492014-05-26 06:22:03 +00005304 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005305 }
Mike Stump11289f42009-09-09 15:08:12 +00005306
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005307 case Stmt::UnaryOperatorClass: {
5308 // The only unary operator that make sense to handle here
5309 // is Deref. All others don't resolve to a "name." This includes
5310 // handling all sorts of rvalues passed to a unary operator.
5311 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005312
John McCalle3027922010-08-25 11:45:40 +00005313 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005314 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +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::ArraySubscriptExprClass: {
5320 // Array subscripts are potential references to data on the stack. We
5321 // retrieve the DeclRefExpr* for the array variable if it indeed
5322 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005323 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005324 }
Mike Stump11289f42009-09-09 15:08:12 +00005325
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005326 case Stmt::ConditionalOperatorClass: {
5327 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005328 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005329 ConditionalOperator *C = cast<ConditionalOperator>(E);
5330
Anders Carlsson801c5c72007-11-30 19:04:31 +00005331 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005332 if (Expr *LHSExpr = C->getLHS()) {
5333 // In C++, we can have a throw-expression, which has 'void' type.
5334 if (!LHSExpr->getType()->isVoidType())
5335 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5336 return LHS;
5337 }
5338
5339 // In C++, we can have a throw-expression, which has 'void' type.
5340 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005341 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005342
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005343 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005344 }
Mike Stump11289f42009-09-09 15:08:12 +00005345
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005346 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005347 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005348 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005349
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005350 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005351 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005352 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005353
5354 // Check whether the member type is itself a reference, in which case
5355 // we're not going to refer to the member, but to what the member refers to.
5356 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005357 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005358
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005359 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005360 }
Mike Stump11289f42009-09-09 15:08:12 +00005361
Douglas Gregorfe314812011-06-21 17:03:29 +00005362 case Stmt::MaterializeTemporaryExprClass:
5363 if (Expr *Result = EvalVal(
5364 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005365 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005366 return Result;
5367
5368 return E;
5369
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005370 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005371 // Check that we don't return or take the address of a reference to a
5372 // temporary. This is only useful in C++.
5373 if (!E->isTypeDependent() && E->isRValue())
5374 return E;
5375
5376 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005377 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005378 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005379} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005380}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005381
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005382void
5383Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5384 SourceLocation ReturnLoc,
5385 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005386 const AttrVec *Attrs,
5387 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005388 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5389
5390 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005391 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5392 CheckNonNullExpr(*this, RetValExp))
5393 Diag(ReturnLoc, diag::warn_null_ret)
5394 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005395
5396 // C++11 [basic.stc.dynamic.allocation]p4:
5397 // If an allocation function declared with a non-throwing
5398 // exception-specification fails to allocate storage, it shall return
5399 // a null pointer. Any other allocation function that fails to allocate
5400 // storage shall indicate failure only by throwing an exception [...]
5401 if (FD) {
5402 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5403 if (Op == OO_New || Op == OO_Array_New) {
5404 const FunctionProtoType *Proto
5405 = FD->getType()->castAs<FunctionProtoType>();
5406 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5407 CheckNonNullExpr(*this, RetValExp))
5408 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5409 << FD << getLangOpts().CPlusPlus11;
5410 }
5411 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005412}
5413
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005414//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5415
5416/// Check for comparisons of floating point operands using != and ==.
5417/// Issue a warning if these are no self-comparisons, as they are not likely
5418/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005419void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005420 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5421 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005422
5423 // Special case: check for x == x (which is OK).
5424 // Do not emit warnings for such cases.
5425 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5426 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5427 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005428 return;
Mike Stump11289f42009-09-09 15:08:12 +00005429
5430
Ted Kremenekeda40e22007-11-29 00:59:04 +00005431 // Special case: check for comparisons against literals that can be exactly
5432 // represented by APFloat. In such cases, do not emit a warning. This
5433 // is a heuristic: often comparison against such literals are used to
5434 // detect if a value in a variable has not changed. This clearly can
5435 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005436 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5437 if (FLL->isExact())
5438 return;
5439 } else
5440 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5441 if (FLR->isExact())
5442 return;
Mike Stump11289f42009-09-09 15:08:12 +00005443
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005444 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005445 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005446 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005447 return;
Mike Stump11289f42009-09-09 15:08:12 +00005448
David Blaikie1f4ff152012-07-16 20:47:22 +00005449 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005450 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005451 return;
Mike Stump11289f42009-09-09 15:08:12 +00005452
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005453 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005454 Diag(Loc, diag::warn_floatingpoint_eq)
5455 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005456}
John McCallca01b222010-01-04 23:21:16 +00005457
John McCall70aa5392010-01-06 05:24:50 +00005458//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5459//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005460
John McCall70aa5392010-01-06 05:24:50 +00005461namespace {
John McCallca01b222010-01-04 23:21:16 +00005462
John McCall70aa5392010-01-06 05:24:50 +00005463/// Structure recording the 'active' range of an integer-valued
5464/// expression.
5465struct IntRange {
5466 /// The number of bits active in the int.
5467 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005468
John McCall70aa5392010-01-06 05:24:50 +00005469 /// True if the int is known not to have negative values.
5470 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005471
John McCall70aa5392010-01-06 05:24:50 +00005472 IntRange(unsigned Width, bool NonNegative)
5473 : Width(Width), NonNegative(NonNegative)
5474 {}
John McCallca01b222010-01-04 23:21:16 +00005475
John McCall817d4af2010-11-10 23:38:19 +00005476 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005477 static IntRange forBoolType() {
5478 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005479 }
5480
John McCall817d4af2010-11-10 23:38:19 +00005481 /// Returns the range of an opaque value of the given integral type.
5482 static IntRange forValueOfType(ASTContext &C, QualType T) {
5483 return forValueOfCanonicalType(C,
5484 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005485 }
5486
John McCall817d4af2010-11-10 23:38:19 +00005487 /// Returns the range of an opaque value of a canonical integral type.
5488 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005489 assert(T->isCanonicalUnqualified());
5490
5491 if (const VectorType *VT = dyn_cast<VectorType>(T))
5492 T = VT->getElementType().getTypePtr();
5493 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5494 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005495 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5496 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005497
David Majnemer6a426652013-06-07 22:07:20 +00005498 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005499 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005500 EnumDecl *Enum = ET->getDecl();
5501 if (!Enum->isCompleteDefinition())
5502 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005503
David Majnemer6a426652013-06-07 22:07:20 +00005504 unsigned NumPositive = Enum->getNumPositiveBits();
5505 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005506
David Majnemer6a426652013-06-07 22:07:20 +00005507 if (NumNegative == 0)
5508 return IntRange(NumPositive, true/*NonNegative*/);
5509 else
5510 return IntRange(std::max(NumPositive + 1, NumNegative),
5511 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005512 }
John McCall70aa5392010-01-06 05:24:50 +00005513
5514 const BuiltinType *BT = cast<BuiltinType>(T);
5515 assert(BT->isInteger());
5516
5517 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5518 }
5519
John McCall817d4af2010-11-10 23:38:19 +00005520 /// Returns the "target" range of a canonical integral type, i.e.
5521 /// the range of values expressible in the type.
5522 ///
5523 /// This matches forValueOfCanonicalType except that enums have the
5524 /// full range of their type, not the range of their enumerators.
5525 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5526 assert(T->isCanonicalUnqualified());
5527
5528 if (const VectorType *VT = dyn_cast<VectorType>(T))
5529 T = VT->getElementType().getTypePtr();
5530 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5531 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005532 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5533 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005534 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005535 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005536
5537 const BuiltinType *BT = cast<BuiltinType>(T);
5538 assert(BT->isInteger());
5539
5540 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5541 }
5542
5543 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005544 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005545 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005546 L.NonNegative && R.NonNegative);
5547 }
5548
John McCall817d4af2010-11-10 23:38:19 +00005549 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005550 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005551 return IntRange(std::min(L.Width, R.Width),
5552 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005553 }
5554};
5555
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005556static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5557 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005558 if (value.isSigned() && value.isNegative())
5559 return IntRange(value.getMinSignedBits(), false);
5560
5561 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005562 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005563
5564 // isNonNegative() just checks the sign bit without considering
5565 // signedness.
5566 return IntRange(value.getActiveBits(), true);
5567}
5568
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005569static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5570 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005571 if (result.isInt())
5572 return GetValueRange(C, result.getInt(), MaxWidth);
5573
5574 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005575 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5576 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5577 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5578 R = IntRange::join(R, El);
5579 }
John McCall70aa5392010-01-06 05:24:50 +00005580 return R;
5581 }
5582
5583 if (result.isComplexInt()) {
5584 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5585 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5586 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005587 }
5588
5589 // This can happen with lossless casts to intptr_t of "based" lvalues.
5590 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005591 // FIXME: The only reason we need to pass the type in here is to get
5592 // the sign right on this one case. It would be nice if APValue
5593 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005594 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005595 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005596}
John McCall70aa5392010-01-06 05:24:50 +00005597
Eli Friedmane6d33952013-07-08 20:20:06 +00005598static QualType GetExprType(Expr *E) {
5599 QualType Ty = E->getType();
5600 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5601 Ty = AtomicRHS->getValueType();
5602 return Ty;
5603}
5604
John McCall70aa5392010-01-06 05:24:50 +00005605/// Pseudo-evaluate the given integer expression, estimating the
5606/// range of values it might take.
5607///
5608/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005609static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005610 E = E->IgnoreParens();
5611
5612 // Try a full evaluation first.
5613 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005614 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005615 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005616
5617 // I think we only want to look through implicit casts here; if the
5618 // user has an explicit widening cast, we should treat the value as
5619 // being of the new, wider type.
5620 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005621 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005622 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5623
Eli Friedmane6d33952013-07-08 20:20:06 +00005624 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005625
John McCalle3027922010-08-25 11:45:40 +00005626 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005627
John McCall70aa5392010-01-06 05:24:50 +00005628 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005629 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005630 return OutputTypeRange;
5631
5632 IntRange SubRange
5633 = GetExprRange(C, CE->getSubExpr(),
5634 std::min(MaxWidth, OutputTypeRange.Width));
5635
5636 // Bail out if the subexpr's range is as wide as the cast type.
5637 if (SubRange.Width >= OutputTypeRange.Width)
5638 return OutputTypeRange;
5639
5640 // Otherwise, we take the smaller width, and we're non-negative if
5641 // either the output type or the subexpr is.
5642 return IntRange(SubRange.Width,
5643 SubRange.NonNegative || OutputTypeRange.NonNegative);
5644 }
5645
5646 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5647 // If we can fold the condition, just take that operand.
5648 bool CondResult;
5649 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5650 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5651 : CO->getFalseExpr(),
5652 MaxWidth);
5653
5654 // Otherwise, conservatively merge.
5655 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5656 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5657 return IntRange::join(L, R);
5658 }
5659
5660 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5661 switch (BO->getOpcode()) {
5662
5663 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005664 case BO_LAnd:
5665 case BO_LOr:
5666 case BO_LT:
5667 case BO_GT:
5668 case BO_LE:
5669 case BO_GE:
5670 case BO_EQ:
5671 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005672 return IntRange::forBoolType();
5673
John McCallc3688382011-07-13 06:35:24 +00005674 // The type of the assignments is the type of the LHS, so the RHS
5675 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005676 case BO_MulAssign:
5677 case BO_DivAssign:
5678 case BO_RemAssign:
5679 case BO_AddAssign:
5680 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005681 case BO_XorAssign:
5682 case BO_OrAssign:
5683 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005684 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005685
John McCallc3688382011-07-13 06:35:24 +00005686 // Simple assignments just pass through the RHS, which will have
5687 // been coerced to the LHS type.
5688 case BO_Assign:
5689 // TODO: bitfields?
5690 return GetExprRange(C, BO->getRHS(), MaxWidth);
5691
John McCall70aa5392010-01-06 05:24:50 +00005692 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005693 case BO_PtrMemD:
5694 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005695 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005696
John McCall2ce81ad2010-01-06 22:07:33 +00005697 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005698 case BO_And:
5699 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005700 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5701 GetExprRange(C, BO->getRHS(), MaxWidth));
5702
John McCall70aa5392010-01-06 05:24:50 +00005703 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005704 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005705 // ...except that we want to treat '1 << (blah)' as logically
5706 // positive. It's an important idiom.
5707 if (IntegerLiteral *I
5708 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5709 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005710 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005711 return IntRange(R.Width, /*NonNegative*/ true);
5712 }
5713 }
5714 // fallthrough
5715
John McCalle3027922010-08-25 11:45:40 +00005716 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005717 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005718
John McCall2ce81ad2010-01-06 22:07:33 +00005719 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005720 case BO_Shr:
5721 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005722 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5723
5724 // If the shift amount is a positive constant, drop the width by
5725 // that much.
5726 llvm::APSInt shift;
5727 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5728 shift.isNonNegative()) {
5729 unsigned zext = shift.getZExtValue();
5730 if (zext >= L.Width)
5731 L.Width = (L.NonNegative ? 0 : 1);
5732 else
5733 L.Width -= zext;
5734 }
5735
5736 return L;
5737 }
5738
5739 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005740 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005741 return GetExprRange(C, BO->getRHS(), MaxWidth);
5742
John McCall2ce81ad2010-01-06 22:07:33 +00005743 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005744 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005745 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005746 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005747 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005748
John McCall51431812011-07-14 22:39:48 +00005749 // The width of a division result is mostly determined by the size
5750 // of the LHS.
5751 case BO_Div: {
5752 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005753 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005754 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5755
5756 // If the divisor is constant, use that.
5757 llvm::APSInt divisor;
5758 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5759 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5760 if (log2 >= L.Width)
5761 L.Width = (L.NonNegative ? 0 : 1);
5762 else
5763 L.Width = std::min(L.Width - log2, MaxWidth);
5764 return L;
5765 }
5766
5767 // Otherwise, just use the LHS's width.
5768 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5769 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5770 }
5771
5772 // The result of a remainder can't be larger than the result of
5773 // either side.
5774 case BO_Rem: {
5775 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005776 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005777 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5778 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5779
5780 IntRange meet = IntRange::meet(L, R);
5781 meet.Width = std::min(meet.Width, MaxWidth);
5782 return meet;
5783 }
5784
5785 // The default behavior is okay for these.
5786 case BO_Mul:
5787 case BO_Add:
5788 case BO_Xor:
5789 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005790 break;
5791 }
5792
John McCall51431812011-07-14 22:39:48 +00005793 // The default case is to treat the operation as if it were closed
5794 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005795 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5796 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5797 return IntRange::join(L, R);
5798 }
5799
5800 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5801 switch (UO->getOpcode()) {
5802 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005803 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005804 return IntRange::forBoolType();
5805
5806 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005807 case UO_Deref:
5808 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005809 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005810
5811 default:
5812 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5813 }
5814 }
5815
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005816 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5817 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5818
John McCalld25db7e2013-05-06 21:39:12 +00005819 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005820 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005821 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005822
Eli Friedmane6d33952013-07-08 20:20:06 +00005823 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005824}
John McCall263a48b2010-01-04 23:31:57 +00005825
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005826static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005827 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005828}
5829
John McCall263a48b2010-01-04 23:31:57 +00005830/// Checks whether the given value, which currently has the given
5831/// source semantics, has the same value when coerced through the
5832/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005833static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5834 const llvm::fltSemantics &Src,
5835 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005836 llvm::APFloat truncated = value;
5837
5838 bool ignored;
5839 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5840 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5841
5842 return truncated.bitwiseIsEqual(value);
5843}
5844
5845/// Checks whether the given value, which currently has the given
5846/// source semantics, has the same value when coerced through the
5847/// target semantics.
5848///
5849/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005850static bool IsSameFloatAfterCast(const APValue &value,
5851 const llvm::fltSemantics &Src,
5852 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005853 if (value.isFloat())
5854 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5855
5856 if (value.isVector()) {
5857 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5858 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5859 return false;
5860 return true;
5861 }
5862
5863 assert(value.isComplexFloat());
5864 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5865 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5866}
5867
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005868static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005869
Ted Kremenek6274be42010-09-23 21:43:44 +00005870static bool IsZero(Sema &S, Expr *E) {
5871 // Suppress cases where we are comparing against an enum constant.
5872 if (const DeclRefExpr *DR =
5873 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5874 if (isa<EnumConstantDecl>(DR->getDecl()))
5875 return false;
5876
5877 // Suppress cases where the '0' value is expanded from a macro.
5878 if (E->getLocStart().isMacroID())
5879 return false;
5880
John McCallcc7e5bf2010-05-06 08:58:33 +00005881 llvm::APSInt Value;
5882 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5883}
5884
John McCall2551c1b2010-10-06 00:25:24 +00005885static bool HasEnumType(Expr *E) {
5886 // Strip off implicit integral promotions.
5887 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005888 if (ICE->getCastKind() != CK_IntegralCast &&
5889 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005890 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005891 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005892 }
5893
5894 return E->getType()->isEnumeralType();
5895}
5896
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005897static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005898 // Disable warning in template instantiations.
5899 if (!S.ActiveTemplateInstantiations.empty())
5900 return;
5901
John McCalle3027922010-08-25 11:45:40 +00005902 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005903 if (E->isValueDependent())
5904 return;
5905
John McCalle3027922010-08-25 11:45:40 +00005906 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005907 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005908 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005909 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005910 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005911 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005912 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005913 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005914 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005915 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005916 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005917 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005918 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005919 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005920 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005921 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5922 }
5923}
5924
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005925static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005926 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005927 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005928 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005929 // Disable warning in template instantiations.
5930 if (!S.ActiveTemplateInstantiations.empty())
5931 return;
5932
Richard Trieu0f097742014-04-04 04:13:47 +00005933 // TODO: Investigate using GetExprRange() to get tighter bounds
5934 // on the bit ranges.
5935 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005936 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5937 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005938 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5939 unsigned OtherWidth = OtherRange.Width;
5940
5941 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5942
Richard Trieu560910c2012-11-14 22:50:24 +00005943 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005944 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005945 return;
5946
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005947 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005948 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005949
Richard Trieu0f097742014-04-04 04:13:47 +00005950 // Used for diagnostic printout.
5951 enum {
5952 LiteralConstant = 0,
5953 CXXBoolLiteralTrue,
5954 CXXBoolLiteralFalse
5955 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005956
Richard Trieu0f097742014-04-04 04:13:47 +00005957 if (!OtherIsBooleanType) {
5958 QualType ConstantT = Constant->getType();
5959 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005960
Richard Trieu0f097742014-04-04 04:13:47 +00005961 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5962 return;
5963 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5964 "comparison with non-integer type");
5965
5966 bool ConstantSigned = ConstantT->isSignedIntegerType();
5967 bool CommonSigned = CommonT->isSignedIntegerType();
5968
5969 bool EqualityOnly = false;
5970
5971 if (CommonSigned) {
5972 // The common type is signed, therefore no signed to unsigned conversion.
5973 if (!OtherRange.NonNegative) {
5974 // Check that the constant is representable in type OtherT.
5975 if (ConstantSigned) {
5976 if (OtherWidth >= Value.getMinSignedBits())
5977 return;
5978 } else { // !ConstantSigned
5979 if (OtherWidth >= Value.getActiveBits() + 1)
5980 return;
5981 }
5982 } else { // !OtherSigned
5983 // Check that the constant is representable in type OtherT.
5984 // Negative values are out of range.
5985 if (ConstantSigned) {
5986 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5987 return;
5988 } else { // !ConstantSigned
5989 if (OtherWidth >= Value.getActiveBits())
5990 return;
5991 }
Richard Trieu560910c2012-11-14 22:50:24 +00005992 }
Richard Trieu0f097742014-04-04 04:13:47 +00005993 } else { // !CommonSigned
5994 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005995 if (OtherWidth >= Value.getActiveBits())
5996 return;
Craig Toppercf360162014-06-18 05:13:11 +00005997 } else { // OtherSigned
5998 assert(!ConstantSigned &&
5999 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006000 // Check to see if the constant is representable in OtherT.
6001 if (OtherWidth > Value.getActiveBits())
6002 return;
6003 // Check to see if the constant is equivalent to a negative value
6004 // cast to CommonT.
6005 if (S.Context.getIntWidth(ConstantT) ==
6006 S.Context.getIntWidth(CommonT) &&
6007 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6008 return;
6009 // The constant value rests between values that OtherT can represent
6010 // after conversion. Relational comparison still works, but equality
6011 // comparisons will be tautological.
6012 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006013 }
6014 }
Richard Trieu0f097742014-04-04 04:13:47 +00006015
6016 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6017
6018 if (op == BO_EQ || op == BO_NE) {
6019 IsTrue = op == BO_NE;
6020 } else if (EqualityOnly) {
6021 return;
6022 } else if (RhsConstant) {
6023 if (op == BO_GT || op == BO_GE)
6024 IsTrue = !PositiveConstant;
6025 else // op == BO_LT || op == BO_LE
6026 IsTrue = PositiveConstant;
6027 } else {
6028 if (op == BO_LT || op == BO_LE)
6029 IsTrue = !PositiveConstant;
6030 else // op == BO_GT || op == BO_GE
6031 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006032 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006033 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006034 // Other isKnownToHaveBooleanValue
6035 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6036 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6037 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6038
6039 static const struct LinkedConditions {
6040 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6041 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6042 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6043 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6044 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6045 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6046
6047 } TruthTable = {
6048 // Constant on LHS. | Constant on RHS. |
6049 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6050 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6051 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6052 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6053 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6054 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6055 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6056 };
6057
6058 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6059
6060 enum ConstantValue ConstVal = Zero;
6061 if (Value.isUnsigned() || Value.isNonNegative()) {
6062 if (Value == 0) {
6063 LiteralOrBoolConstant =
6064 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6065 ConstVal = Zero;
6066 } else if (Value == 1) {
6067 LiteralOrBoolConstant =
6068 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6069 ConstVal = One;
6070 } else {
6071 LiteralOrBoolConstant = LiteralConstant;
6072 ConstVal = GT_One;
6073 }
6074 } else {
6075 ConstVal = LT_Zero;
6076 }
6077
6078 CompareBoolWithConstantResult CmpRes;
6079
6080 switch (op) {
6081 case BO_LT:
6082 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6083 break;
6084 case BO_GT:
6085 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6086 break;
6087 case BO_LE:
6088 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6089 break;
6090 case BO_GE:
6091 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6092 break;
6093 case BO_EQ:
6094 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6095 break;
6096 case BO_NE:
6097 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6098 break;
6099 default:
6100 CmpRes = Unkwn;
6101 break;
6102 }
6103
6104 if (CmpRes == AFals) {
6105 IsTrue = false;
6106 } else if (CmpRes == ATrue) {
6107 IsTrue = true;
6108 } else {
6109 return;
6110 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006111 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006112
6113 // If this is a comparison to an enum constant, include that
6114 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006115 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006116 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6117 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6118
6119 SmallString<64> PrettySourceValue;
6120 llvm::raw_svector_ostream OS(PrettySourceValue);
6121 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006122 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006123 else
6124 OS << Value;
6125
Richard Trieu0f097742014-04-04 04:13:47 +00006126 S.DiagRuntimeBehavior(
6127 E->getOperatorLoc(), E,
6128 S.PDiag(diag::warn_out_of_range_compare)
6129 << OS.str() << LiteralOrBoolConstant
6130 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6131 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006132}
6133
John McCallcc7e5bf2010-05-06 08:58:33 +00006134/// Analyze the operands of the given comparison. Implements the
6135/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006136static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006137 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6138 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006139}
John McCall263a48b2010-01-04 23:31:57 +00006140
John McCallca01b222010-01-04 23:21:16 +00006141/// \brief Implements -Wsign-compare.
6142///
Richard Trieu82402a02011-09-15 21:56:47 +00006143/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006144static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006145 // The type the comparison is being performed in.
6146 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006147
6148 // Only analyze comparison operators where both sides have been converted to
6149 // the same type.
6150 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6151 return AnalyzeImpConvsInComparison(S, E);
6152
6153 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006154 if (E->isValueDependent())
6155 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006156
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006157 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6158 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006159
6160 bool IsComparisonConstant = false;
6161
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006162 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006163 // of 'true' or 'false'.
6164 if (T->isIntegralType(S.Context)) {
6165 llvm::APSInt RHSValue;
6166 bool IsRHSIntegralLiteral =
6167 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6168 llvm::APSInt LHSValue;
6169 bool IsLHSIntegralLiteral =
6170 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6171 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6172 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6173 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6174 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6175 else
6176 IsComparisonConstant =
6177 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006178 } else if (!T->hasUnsignedIntegerRepresentation())
6179 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006180
John McCallcc7e5bf2010-05-06 08:58:33 +00006181 // We don't do anything special if this isn't an unsigned integral
6182 // comparison: we're only interested in integral comparisons, and
6183 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006184 //
6185 // We also don't care about value-dependent expressions or expressions
6186 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006187 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006188 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006189
John McCallcc7e5bf2010-05-06 08:58:33 +00006190 // Check to see if one of the (unmodified) operands is of different
6191 // signedness.
6192 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006193 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6194 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006195 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006196 signedOperand = LHS;
6197 unsignedOperand = RHS;
6198 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6199 signedOperand = RHS;
6200 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006201 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006202 CheckTrivialUnsignedComparison(S, E);
6203 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006204 }
6205
John McCallcc7e5bf2010-05-06 08:58:33 +00006206 // Otherwise, calculate the effective range of the signed operand.
6207 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006208
John McCallcc7e5bf2010-05-06 08:58:33 +00006209 // Go ahead and analyze implicit conversions in the operands. Note
6210 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006211 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6212 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006213
John McCallcc7e5bf2010-05-06 08:58:33 +00006214 // If the signed range is non-negative, -Wsign-compare won't fire,
6215 // but we should still check for comparisons which are always true
6216 // or false.
6217 if (signedRange.NonNegative)
6218 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006219
6220 // For (in)equality comparisons, if the unsigned operand is a
6221 // constant which cannot collide with a overflowed signed operand,
6222 // then reinterpreting the signed operand as unsigned will not
6223 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006224 if (E->isEqualityOp()) {
6225 unsigned comparisonWidth = S.Context.getIntWidth(T);
6226 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006227
John McCallcc7e5bf2010-05-06 08:58:33 +00006228 // We should never be unable to prove that the unsigned operand is
6229 // non-negative.
6230 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6231
6232 if (unsignedRange.Width < comparisonWidth)
6233 return;
6234 }
6235
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006236 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6237 S.PDiag(diag::warn_mixed_sign_comparison)
6238 << LHS->getType() << RHS->getType()
6239 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006240}
6241
John McCall1f425642010-11-11 03:21:53 +00006242/// Analyzes an attempt to assign the given value to a bitfield.
6243///
6244/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006245static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6246 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006247 assert(Bitfield->isBitField());
6248 if (Bitfield->isInvalidDecl())
6249 return false;
6250
John McCalldeebbcf2010-11-11 05:33:51 +00006251 // White-list bool bitfields.
6252 if (Bitfield->getType()->isBooleanType())
6253 return false;
6254
Douglas Gregor789adec2011-02-04 13:09:01 +00006255 // Ignore value- or type-dependent expressions.
6256 if (Bitfield->getBitWidth()->isValueDependent() ||
6257 Bitfield->getBitWidth()->isTypeDependent() ||
6258 Init->isValueDependent() ||
6259 Init->isTypeDependent())
6260 return false;
6261
John McCall1f425642010-11-11 03:21:53 +00006262 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6263
Richard Smith5fab0c92011-12-28 19:48:30 +00006264 llvm::APSInt Value;
6265 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006266 return false;
6267
John McCall1f425642010-11-11 03:21:53 +00006268 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006269 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006270
6271 if (OriginalWidth <= FieldWidth)
6272 return false;
6273
Eli Friedmanc267a322012-01-26 23:11:39 +00006274 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006275 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006276 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006277
Eli Friedmanc267a322012-01-26 23:11:39 +00006278 // Check whether the stored value is equal to the original value.
6279 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006280 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006281 return false;
6282
Eli Friedmanc267a322012-01-26 23:11:39 +00006283 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006284 // therefore don't strictly fit into a signed bitfield of width 1.
6285 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006286 return false;
6287
John McCall1f425642010-11-11 03:21:53 +00006288 std::string PrettyValue = Value.toString(10);
6289 std::string PrettyTrunc = TruncatedValue.toString(10);
6290
6291 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6292 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6293 << Init->getSourceRange();
6294
6295 return true;
6296}
6297
John McCalld2a53122010-11-09 23:24:47 +00006298/// Analyze the given simple or compound assignment for warning-worthy
6299/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006300static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006301 // Just recurse on the LHS.
6302 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6303
6304 // We want to recurse on the RHS as normal unless we're assigning to
6305 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006306 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006307 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006308 E->getOperatorLoc())) {
6309 // Recurse, ignoring any implicit conversions on the RHS.
6310 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6311 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006312 }
6313 }
6314
6315 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6316}
6317
John McCall263a48b2010-01-04 23:31:57 +00006318/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006319static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006320 SourceLocation CContext, unsigned diag,
6321 bool pruneControlFlow = false) {
6322 if (pruneControlFlow) {
6323 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6324 S.PDiag(diag)
6325 << SourceType << T << E->getSourceRange()
6326 << SourceRange(CContext));
6327 return;
6328 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006329 S.Diag(E->getExprLoc(), diag)
6330 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6331}
6332
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006333/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006334static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006335 SourceLocation CContext, unsigned diag,
6336 bool pruneControlFlow = false) {
6337 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006338}
6339
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006340/// Diagnose an implicit cast from a literal expression. Does not warn when the
6341/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006342void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6343 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006344 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006345 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006346 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006347 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6348 T->hasUnsignedIntegerRepresentation());
6349 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006350 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006351 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006352 return;
6353
Eli Friedman07185912013-08-29 23:44:43 +00006354 // FIXME: Force the precision of the source value down so we don't print
6355 // digits which are usually useless (we don't really care here if we
6356 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6357 // would automatically print the shortest representation, but it's a bit
6358 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006359 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006360 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6361 precision = (precision * 59 + 195) / 196;
6362 Value.toString(PrettySourceValue, precision);
6363
David Blaikie9b88cc02012-05-15 17:18:27 +00006364 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006365 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6366 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6367 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006368 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006369
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006370 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006371 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6372 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006373}
6374
John McCall18a2c2c2010-11-09 22:22:12 +00006375std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6376 if (!Range.Width) return "0";
6377
6378 llvm::APSInt ValueInRange = Value;
6379 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006380 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006381 return ValueInRange.toString(10);
6382}
6383
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006384static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6385 if (!isa<ImplicitCastExpr>(Ex))
6386 return false;
6387
6388 Expr *InnerE = Ex->IgnoreParenImpCasts();
6389 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6390 const Type *Source =
6391 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6392 if (Target->isDependentType())
6393 return false;
6394
6395 const BuiltinType *FloatCandidateBT =
6396 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6397 const Type *BoolCandidateType = ToBool ? Target : Source;
6398
6399 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6400 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6401}
6402
6403void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6404 SourceLocation CC) {
6405 unsigned NumArgs = TheCall->getNumArgs();
6406 for (unsigned i = 0; i < NumArgs; ++i) {
6407 Expr *CurrA = TheCall->getArg(i);
6408 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6409 continue;
6410
6411 bool IsSwapped = ((i > 0) &&
6412 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6413 IsSwapped |= ((i < (NumArgs - 1)) &&
6414 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6415 if (IsSwapped) {
6416 // Warn on this floating-point to bool conversion.
6417 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6418 CurrA->getType(), CC,
6419 diag::warn_impcast_floating_point_to_bool);
6420 }
6421 }
6422}
6423
Richard Trieu5b993502014-10-15 03:42:06 +00006424static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6425 SourceLocation CC) {
6426 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6427 E->getExprLoc()))
6428 return;
6429
6430 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6431 const Expr::NullPointerConstantKind NullKind =
6432 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6433 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6434 return;
6435
6436 // Return if target type is a safe conversion.
6437 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6438 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6439 return;
6440
6441 SourceLocation Loc = E->getSourceRange().getBegin();
6442
6443 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6444 if (NullKind == Expr::NPCK_GNUNull) {
6445 if (Loc.isMacroID())
6446 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6447 }
6448
6449 // Only warn if the null and context location are in the same macro expansion.
6450 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6451 return;
6452
6453 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6454 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6455 << FixItHint::CreateReplacement(Loc,
6456 S.getFixItZeroLiteralForType(T, Loc));
6457}
6458
John McCallcc7e5bf2010-05-06 08:58:33 +00006459void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006460 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006461 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006462
John McCallcc7e5bf2010-05-06 08:58:33 +00006463 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6464 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6465 if (Source == Target) return;
6466 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006467
Chandler Carruthc22845a2011-07-26 05:40:03 +00006468 // If the conversion context location is invalid don't complain. We also
6469 // don't want to emit a warning if the issue occurs from the expansion of
6470 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6471 // delay this check as long as possible. Once we detect we are in that
6472 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006473 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006474 return;
6475
Richard Trieu021baa32011-09-23 20:10:00 +00006476 // Diagnose implicit casts to bool.
6477 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6478 if (isa<StringLiteral>(E))
6479 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006480 // and expressions, for instance, assert(0 && "error here"), are
6481 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006482 return DiagnoseImpCast(S, E, T, CC,
6483 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006484 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6485 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6486 // This covers the literal expressions that evaluate to Objective-C
6487 // objects.
6488 return DiagnoseImpCast(S, E, T, CC,
6489 diag::warn_impcast_objective_c_literal_to_bool);
6490 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006491 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6492 // Warn on pointer to bool conversion that is always true.
6493 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6494 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006495 }
Richard Trieu021baa32011-09-23 20:10:00 +00006496 }
John McCall263a48b2010-01-04 23:31:57 +00006497
6498 // Strip vector types.
6499 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006500 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006501 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006502 return;
John McCallacf0ee52010-10-08 02:01:28 +00006503 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006504 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006505
6506 // If the vector cast is cast between two vectors of the same size, it is
6507 // a bitcast, not a conversion.
6508 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6509 return;
John McCall263a48b2010-01-04 23:31:57 +00006510
6511 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6512 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6513 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006514 if (auto VecTy = dyn_cast<VectorType>(Target))
6515 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006516
6517 // Strip complex types.
6518 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006519 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006520 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006521 return;
6522
John McCallacf0ee52010-10-08 02:01:28 +00006523 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006524 }
John McCall263a48b2010-01-04 23:31:57 +00006525
6526 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6527 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6528 }
6529
6530 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6531 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6532
6533 // If the source is floating point...
6534 if (SourceBT && SourceBT->isFloatingPoint()) {
6535 // ...and the target is floating point...
6536 if (TargetBT && TargetBT->isFloatingPoint()) {
6537 // ...then warn if we're dropping FP rank.
6538
6539 // Builtin FP kinds are ordered by increasing FP rank.
6540 if (SourceBT->getKind() > TargetBT->getKind()) {
6541 // Don't warn about float constants that are precisely
6542 // representable in the target type.
6543 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006544 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006545 // Value might be a float, a float vector, or a float complex.
6546 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006547 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6548 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006549 return;
6550 }
6551
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006552 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006553 return;
6554
John McCallacf0ee52010-10-08 02:01:28 +00006555 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006556 }
6557 return;
6558 }
6559
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006560 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006561 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006562 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006563 return;
6564
Chandler Carruth22c7a792011-02-17 11:05:49 +00006565 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006566 // We also want to warn on, e.g., "int i = -1.234"
6567 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6568 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6569 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6570
Chandler Carruth016ef402011-04-10 08:36:24 +00006571 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6572 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006573 } else {
6574 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6575 }
6576 }
John McCall263a48b2010-01-04 23:31:57 +00006577
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006578 // If the target is bool, warn if expr is a function or method call.
6579 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6580 isa<CallExpr>(E)) {
6581 // Check last argument of function call to see if it is an
6582 // implicit cast from a type matching the type the result
6583 // is being cast to.
6584 CallExpr *CEx = cast<CallExpr>(E);
6585 unsigned NumArgs = CEx->getNumArgs();
6586 if (NumArgs > 0) {
6587 Expr *LastA = CEx->getArg(NumArgs - 1);
6588 Expr *InnerE = LastA->IgnoreParenImpCasts();
6589 const Type *InnerType =
6590 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6591 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6592 // Warn on this floating-point to bool conversion
6593 DiagnoseImpCast(S, E, T, CC,
6594 diag::warn_impcast_floating_point_to_bool);
6595 }
6596 }
6597 }
John McCall263a48b2010-01-04 23:31:57 +00006598 return;
6599 }
6600
Richard Trieu5b993502014-10-15 03:42:06 +00006601 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006602
David Blaikie9366d2b2012-06-19 21:19:06 +00006603 if (!Source->isIntegerType() || !Target->isIntegerType())
6604 return;
6605
David Blaikie7555b6a2012-05-15 16:56:36 +00006606 // TODO: remove this early return once the false positives for constant->bool
6607 // in templates, macros, etc, are reduced or removed.
6608 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6609 return;
6610
John McCallcc7e5bf2010-05-06 08:58:33 +00006611 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006612 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006613
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006614 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006615 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006616 // TODO: this should happen for bitfield stores, too.
6617 llvm::APSInt Value(32);
6618 if (E->isIntegerConstantExpr(Value, S.Context)) {
6619 if (S.SourceMgr.isInSystemMacro(CC))
6620 return;
6621
John McCall18a2c2c2010-11-09 22:22:12 +00006622 std::string PrettySourceValue = Value.toString(10);
6623 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006624
Ted Kremenek33ba9952011-10-22 02:37:33 +00006625 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6626 S.PDiag(diag::warn_impcast_integer_precision_constant)
6627 << PrettySourceValue << PrettyTargetValue
6628 << E->getType() << T << E->getSourceRange()
6629 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006630 return;
6631 }
6632
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006633 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6634 if (S.SourceMgr.isInSystemMacro(CC))
6635 return;
6636
David Blaikie9455da02012-04-12 22:40:54 +00006637 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006638 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6639 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006640 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006641 }
6642
6643 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6644 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6645 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006646
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006647 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006648 return;
6649
John McCallcc7e5bf2010-05-06 08:58:33 +00006650 unsigned DiagID = diag::warn_impcast_integer_sign;
6651
6652 // Traditionally, gcc has warned about this under -Wsign-compare.
6653 // We also want to warn about it in -Wconversion.
6654 // So if -Wconversion is off, use a completely identical diagnostic
6655 // in the sign-compare group.
6656 // The conditional-checking code will
6657 if (ICContext) {
6658 DiagID = diag::warn_impcast_integer_sign_conditional;
6659 *ICContext = true;
6660 }
6661
John McCallacf0ee52010-10-08 02:01:28 +00006662 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006663 }
6664
Douglas Gregora78f1932011-02-22 02:45:07 +00006665 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006666 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6667 // type, to give us better diagnostics.
6668 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006669 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006670 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6671 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6672 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6673 SourceType = S.Context.getTypeDeclType(Enum);
6674 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6675 }
6676 }
6677
Douglas Gregora78f1932011-02-22 02:45:07 +00006678 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6679 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006680 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6681 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006682 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006683 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006684 return;
6685
Douglas Gregor364f7db2011-03-12 00:14:31 +00006686 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006687 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006688 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006689
John McCall263a48b2010-01-04 23:31:57 +00006690 return;
6691}
6692
David Blaikie18e9ac72012-05-15 21:57:38 +00006693void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6694 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006695
6696void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006697 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006698 E = E->IgnoreParenImpCasts();
6699
6700 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006701 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006702
John McCallacf0ee52010-10-08 02:01:28 +00006703 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006704 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006705 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006706 return;
6707}
6708
David Blaikie18e9ac72012-05-15 21:57:38 +00006709void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6710 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006711 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006712
6713 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006714 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6715 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006716
6717 // If -Wconversion would have warned about either of the candidates
6718 // for a signedness conversion to the context type...
6719 if (!Suspicious) return;
6720
6721 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006722 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006723 return;
6724
John McCallcc7e5bf2010-05-06 08:58:33 +00006725 // ...then check whether it would have warned about either of the
6726 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006727 if (E->getType() == T) return;
6728
6729 Suspicious = false;
6730 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6731 E->getType(), CC, &Suspicious);
6732 if (!Suspicious)
6733 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006734 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006735}
6736
Richard Trieu65724892014-11-15 06:37:39 +00006737/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6738/// Input argument E is a logical expression.
6739static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6740 if (S.getLangOpts().Bool)
6741 return;
6742 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6743}
6744
John McCallcc7e5bf2010-05-06 08:58:33 +00006745/// AnalyzeImplicitConversions - Find and report any interesting
6746/// implicit conversions in the given expression. There are a couple
6747/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006748void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006749 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006750 Expr *E = OrigE->IgnoreParenImpCasts();
6751
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006752 if (E->isTypeDependent() || E->isValueDependent())
6753 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006754
John McCallcc7e5bf2010-05-06 08:58:33 +00006755 // For conditional operators, we analyze the arguments as if they
6756 // were being fed directly into the output.
6757 if (isa<ConditionalOperator>(E)) {
6758 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006759 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006760 return;
6761 }
6762
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006763 // Check implicit argument conversions for function calls.
6764 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6765 CheckImplicitArgumentConversions(S, Call, CC);
6766
John McCallcc7e5bf2010-05-06 08:58:33 +00006767 // Go ahead and check any implicit conversions we might have skipped.
6768 // The non-canonical typecheck is just an optimization;
6769 // CheckImplicitConversion will filter out dead implicit conversions.
6770 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006771 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006772
6773 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006774
6775 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006776 if (POE->getResultExpr())
6777 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006778 }
6779
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006780 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6781 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6782
John McCallcc7e5bf2010-05-06 08:58:33 +00006783 // Skip past explicit casts.
6784 if (isa<ExplicitCastExpr>(E)) {
6785 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006786 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006787 }
6788
John McCalld2a53122010-11-09 23:24:47 +00006789 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6790 // Do a somewhat different check with comparison operators.
6791 if (BO->isComparisonOp())
6792 return AnalyzeComparison(S, BO);
6793
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006794 // And with simple assignments.
6795 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006796 return AnalyzeAssignment(S, BO);
6797 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006798
6799 // These break the otherwise-useful invariant below. Fortunately,
6800 // we don't really need to recurse into them, because any internal
6801 // expressions should have been analyzed already when they were
6802 // built into statements.
6803 if (isa<StmtExpr>(E)) return;
6804
6805 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006806 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006807
6808 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006809 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006810 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006811 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006812 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006813 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006814 if (!ChildExpr)
6815 continue;
6816
Richard Trieu955231d2014-01-25 01:10:35 +00006817 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006818 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006819 // Ignore checking string literals that are in logical and operators.
6820 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006821 continue;
6822 AnalyzeImplicitConversions(S, ChildExpr, CC);
6823 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006824
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006825 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006826 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6827 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006828 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00006829
6830 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6831 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006832 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006833 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006834
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006835 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6836 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00006837 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006838}
6839
6840} // end anonymous namespace
6841
Richard Trieu3bb8b562014-02-26 02:36:06 +00006842enum {
6843 AddressOf,
6844 FunctionPointer,
6845 ArrayPointer
6846};
6847
Richard Trieuc1888e02014-06-28 23:25:37 +00006848// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6849// Returns true when emitting a warning about taking the address of a reference.
6850static bool CheckForReference(Sema &SemaRef, const Expr *E,
6851 PartialDiagnostic PD) {
6852 E = E->IgnoreParenImpCasts();
6853
6854 const FunctionDecl *FD = nullptr;
6855
6856 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6857 if (!DRE->getDecl()->getType()->isReferenceType())
6858 return false;
6859 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6860 if (!M->getMemberDecl()->getType()->isReferenceType())
6861 return false;
6862 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00006863 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00006864 return false;
6865 FD = Call->getDirectCallee();
6866 } else {
6867 return false;
6868 }
6869
6870 SemaRef.Diag(E->getExprLoc(), PD);
6871
6872 // If possible, point to location of function.
6873 if (FD) {
6874 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6875 }
6876
6877 return true;
6878}
6879
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006880// Returns true if the SourceLocation is expanded from any macro body.
6881// Returns false if the SourceLocation is invalid, is from not in a macro
6882// expansion, or is from expanded from a top-level macro argument.
6883static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6884 if (Loc.isInvalid())
6885 return false;
6886
6887 while (Loc.isMacroID()) {
6888 if (SM.isMacroBodyExpansion(Loc))
6889 return true;
6890 Loc = SM.getImmediateMacroCallerLoc(Loc);
6891 }
6892
6893 return false;
6894}
6895
Richard Trieu3bb8b562014-02-26 02:36:06 +00006896/// \brief Diagnose pointers that are always non-null.
6897/// \param E the expression containing the pointer
6898/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6899/// compared to a null pointer
6900/// \param IsEqual True when the comparison is equal to a null pointer
6901/// \param Range Extra SourceRange to highlight in the diagnostic
6902void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6903 Expr::NullPointerConstantKind NullKind,
6904 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006905 if (!E)
6906 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006907
6908 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006909 if (E->getExprLoc().isMacroID()) {
6910 const SourceManager &SM = getSourceManager();
6911 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6912 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006913 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006914 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006915 E = E->IgnoreImpCasts();
6916
6917 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6918
Richard Trieuf7432752014-06-06 21:39:26 +00006919 if (isa<CXXThisExpr>(E)) {
6920 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6921 : diag::warn_this_bool_conversion;
6922 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6923 return;
6924 }
6925
Richard Trieu3bb8b562014-02-26 02:36:06 +00006926 bool IsAddressOf = false;
6927
6928 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6929 if (UO->getOpcode() != UO_AddrOf)
6930 return;
6931 IsAddressOf = true;
6932 E = UO->getSubExpr();
6933 }
6934
Richard Trieuc1888e02014-06-28 23:25:37 +00006935 if (IsAddressOf) {
6936 unsigned DiagID = IsCompare
6937 ? diag::warn_address_of_reference_null_compare
6938 : diag::warn_address_of_reference_bool_conversion;
6939 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6940 << IsEqual;
6941 if (CheckForReference(*this, E, PD)) {
6942 return;
6943 }
6944 }
6945
Richard Trieu3bb8b562014-02-26 02:36:06 +00006946 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006947 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006948 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6949 D = R->getDecl();
6950 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6951 D = M->getMemberDecl();
6952 }
6953
6954 // Weak Decls can be null.
6955 if (!D || D->isWeak())
6956 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006957
6958 // Check for parameter decl with nonnull attribute
6959 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6960 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6961 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6962 unsigned NumArgs = FD->getNumParams();
6963 llvm::SmallBitVector AttrNonNull(NumArgs);
6964 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6965 if (!NonNull->args_size()) {
6966 AttrNonNull.set(0, NumArgs);
6967 break;
6968 }
6969 for (unsigned Val : NonNull->args()) {
6970 if (Val >= NumArgs)
6971 continue;
6972 AttrNonNull.set(Val);
6973 }
6974 }
6975 if (!AttrNonNull.empty())
6976 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00006977 if (FD->getParamDecl(i) == PV &&
6978 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006979 std::string Str;
6980 llvm::raw_string_ostream S(Str);
6981 E->printPretty(S, nullptr, getPrintingPolicy());
6982 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
6983 : diag::warn_cast_nonnull_to_bool;
6984 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
6985 << Range << IsEqual;
6986 return;
6987 }
6988 }
6989 }
6990
Richard Trieu3bb8b562014-02-26 02:36:06 +00006991 QualType T = D->getType();
6992 const bool IsArray = T->isArrayType();
6993 const bool IsFunction = T->isFunctionType();
6994
Richard Trieuc1888e02014-06-28 23:25:37 +00006995 // Address of function is used to silence the function warning.
6996 if (IsAddressOf && IsFunction) {
6997 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006998 }
6999
7000 // Found nothing.
7001 if (!IsAddressOf && !IsFunction && !IsArray)
7002 return;
7003
7004 // Pretty print the expression for the diagnostic.
7005 std::string Str;
7006 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007007 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007008
7009 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7010 : diag::warn_impcast_pointer_to_bool;
7011 unsigned DiagType;
7012 if (IsAddressOf)
7013 DiagType = AddressOf;
7014 else if (IsFunction)
7015 DiagType = FunctionPointer;
7016 else if (IsArray)
7017 DiagType = ArrayPointer;
7018 else
7019 llvm_unreachable("Could not determine diagnostic.");
7020 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7021 << Range << IsEqual;
7022
7023 if (!IsFunction)
7024 return;
7025
7026 // Suggest '&' to silence the function warning.
7027 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7028 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7029
7030 // Check to see if '()' fixit should be emitted.
7031 QualType ReturnType;
7032 UnresolvedSet<4> NonTemplateOverloads;
7033 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7034 if (ReturnType.isNull())
7035 return;
7036
7037 if (IsCompare) {
7038 // There are two cases here. If there is null constant, the only suggest
7039 // for a pointer return type. If the null is 0, then suggest if the return
7040 // type is a pointer or an integer type.
7041 if (!ReturnType->isPointerType()) {
7042 if (NullKind == Expr::NPCK_ZeroExpression ||
7043 NullKind == Expr::NPCK_ZeroLiteral) {
7044 if (!ReturnType->isIntegerType())
7045 return;
7046 } else {
7047 return;
7048 }
7049 }
7050 } else { // !IsCompare
7051 // For function to bool, only suggest if the function pointer has bool
7052 // return type.
7053 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7054 return;
7055 }
7056 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007057 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007058}
7059
7060
John McCallcc7e5bf2010-05-06 08:58:33 +00007061/// Diagnoses "dangerous" implicit conversions within the given
7062/// expression (which is a full expression). Implements -Wconversion
7063/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007064///
7065/// \param CC the "context" location of the implicit conversion, i.e.
7066/// the most location of the syntactic entity requiring the implicit
7067/// conversion
7068void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007069 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007070 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007071 return;
7072
7073 // Don't diagnose for value- or type-dependent expressions.
7074 if (E->isTypeDependent() || E->isValueDependent())
7075 return;
7076
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007077 // Check for array bounds violations in cases where the check isn't triggered
7078 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7079 // ArraySubscriptExpr is on the RHS of a variable initialization.
7080 CheckArrayAccess(E);
7081
John McCallacf0ee52010-10-08 02:01:28 +00007082 // This is not the right CC for (e.g.) a variable initialization.
7083 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007084}
7085
Richard Trieu65724892014-11-15 06:37:39 +00007086/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7087/// Input argument E is a logical expression.
7088void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7089 ::CheckBoolLikeConversion(*this, E, CC);
7090}
7091
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007092/// Diagnose when expression is an integer constant expression and its evaluation
7093/// results in integer overflow
7094void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007095 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7096 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007097}
7098
Richard Smithc406cb72013-01-17 01:17:56 +00007099namespace {
7100/// \brief Visitor for expressions which looks for unsequenced operations on the
7101/// same object.
7102class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007103 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7104
Richard Smithc406cb72013-01-17 01:17:56 +00007105 /// \brief A tree of sequenced regions within an expression. Two regions are
7106 /// unsequenced if one is an ancestor or a descendent of the other. When we
7107 /// finish processing an expression with sequencing, such as a comma
7108 /// expression, we fold its tree nodes into its parent, since they are
7109 /// unsequenced with respect to nodes we will visit later.
7110 class SequenceTree {
7111 struct Value {
7112 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7113 unsigned Parent : 31;
7114 bool Merged : 1;
7115 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007116 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007117
7118 public:
7119 /// \brief A region within an expression which may be sequenced with respect
7120 /// to some other region.
7121 class Seq {
7122 explicit Seq(unsigned N) : Index(N) {}
7123 unsigned Index;
7124 friend class SequenceTree;
7125 public:
7126 Seq() : Index(0) {}
7127 };
7128
7129 SequenceTree() { Values.push_back(Value(0)); }
7130 Seq root() const { return Seq(0); }
7131
7132 /// \brief Create a new sequence of operations, which is an unsequenced
7133 /// subset of \p Parent. This sequence of operations is sequenced with
7134 /// respect to other children of \p Parent.
7135 Seq allocate(Seq Parent) {
7136 Values.push_back(Value(Parent.Index));
7137 return Seq(Values.size() - 1);
7138 }
7139
7140 /// \brief Merge a sequence of operations into its parent.
7141 void merge(Seq S) {
7142 Values[S.Index].Merged = true;
7143 }
7144
7145 /// \brief Determine whether two operations are unsequenced. This operation
7146 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7147 /// should have been merged into its parent as appropriate.
7148 bool isUnsequenced(Seq Cur, Seq Old) {
7149 unsigned C = representative(Cur.Index);
7150 unsigned Target = representative(Old.Index);
7151 while (C >= Target) {
7152 if (C == Target)
7153 return true;
7154 C = Values[C].Parent;
7155 }
7156 return false;
7157 }
7158
7159 private:
7160 /// \brief Pick a representative for a sequence.
7161 unsigned representative(unsigned K) {
7162 if (Values[K].Merged)
7163 // Perform path compression as we go.
7164 return Values[K].Parent = representative(Values[K].Parent);
7165 return K;
7166 }
7167 };
7168
7169 /// An object for which we can track unsequenced uses.
7170 typedef NamedDecl *Object;
7171
7172 /// Different flavors of object usage which we track. We only track the
7173 /// least-sequenced usage of each kind.
7174 enum UsageKind {
7175 /// A read of an object. Multiple unsequenced reads are OK.
7176 UK_Use,
7177 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007178 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007179 UK_ModAsValue,
7180 /// A modification of an object which is not sequenced before the value
7181 /// computation of the expression, such as n++.
7182 UK_ModAsSideEffect,
7183
7184 UK_Count = UK_ModAsSideEffect + 1
7185 };
7186
7187 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007188 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007189 Expr *Use;
7190 SequenceTree::Seq Seq;
7191 };
7192
7193 struct UsageInfo {
7194 UsageInfo() : Diagnosed(false) {}
7195 Usage Uses[UK_Count];
7196 /// Have we issued a diagnostic for this variable already?
7197 bool Diagnosed;
7198 };
7199 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7200
7201 Sema &SemaRef;
7202 /// Sequenced regions within the expression.
7203 SequenceTree Tree;
7204 /// Declaration modifications and references which we have seen.
7205 UsageInfoMap UsageMap;
7206 /// The region we are currently within.
7207 SequenceTree::Seq Region;
7208 /// Filled in with declarations which were modified as a side-effect
7209 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007210 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007211 /// Expressions to check later. We defer checking these to reduce
7212 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007213 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007214
7215 /// RAII object wrapping the visitation of a sequenced subexpression of an
7216 /// expression. At the end of this process, the side-effects of the evaluation
7217 /// become sequenced with respect to the value computation of the result, so
7218 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7219 /// UK_ModAsValue.
7220 struct SequencedSubexpression {
7221 SequencedSubexpression(SequenceChecker &Self)
7222 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7223 Self.ModAsSideEffect = &ModAsSideEffect;
7224 }
7225 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007226 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7227 MI != ME; ++MI) {
7228 UsageInfo &U = Self.UsageMap[MI->first];
7229 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7230 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7231 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007232 }
7233 Self.ModAsSideEffect = OldModAsSideEffect;
7234 }
7235
7236 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007237 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7238 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007239 };
7240
Richard Smith40238f02013-06-20 22:21:56 +00007241 /// RAII object wrapping the visitation of a subexpression which we might
7242 /// choose to evaluate as a constant. If any subexpression is evaluated and
7243 /// found to be non-constant, this allows us to suppress the evaluation of
7244 /// the outer expression.
7245 class EvaluationTracker {
7246 public:
7247 EvaluationTracker(SequenceChecker &Self)
7248 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7249 Self.EvalTracker = this;
7250 }
7251 ~EvaluationTracker() {
7252 Self.EvalTracker = Prev;
7253 if (Prev)
7254 Prev->EvalOK &= EvalOK;
7255 }
7256
7257 bool evaluate(const Expr *E, bool &Result) {
7258 if (!EvalOK || E->isValueDependent())
7259 return false;
7260 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7261 return EvalOK;
7262 }
7263
7264 private:
7265 SequenceChecker &Self;
7266 EvaluationTracker *Prev;
7267 bool EvalOK;
7268 } *EvalTracker;
7269
Richard Smithc406cb72013-01-17 01:17:56 +00007270 /// \brief Find the object which is produced by the specified expression,
7271 /// if any.
7272 Object getObject(Expr *E, bool Mod) const {
7273 E = E->IgnoreParenCasts();
7274 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7275 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7276 return getObject(UO->getSubExpr(), Mod);
7277 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7278 if (BO->getOpcode() == BO_Comma)
7279 return getObject(BO->getRHS(), Mod);
7280 if (Mod && BO->isAssignmentOp())
7281 return getObject(BO->getLHS(), Mod);
7282 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7283 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7284 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7285 return ME->getMemberDecl();
7286 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7287 // FIXME: If this is a reference, map through to its value.
7288 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007289 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007290 }
7291
7292 /// \brief Note that an object was modified or used by an expression.
7293 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7294 Usage &U = UI.Uses[UK];
7295 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7296 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7297 ModAsSideEffect->push_back(std::make_pair(O, U));
7298 U.Use = Ref;
7299 U.Seq = Region;
7300 }
7301 }
7302 /// \brief Check whether a modification or use conflicts with a prior usage.
7303 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7304 bool IsModMod) {
7305 if (UI.Diagnosed)
7306 return;
7307
7308 const Usage &U = UI.Uses[OtherKind];
7309 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7310 return;
7311
7312 Expr *Mod = U.Use;
7313 Expr *ModOrUse = Ref;
7314 if (OtherKind == UK_Use)
7315 std::swap(Mod, ModOrUse);
7316
7317 SemaRef.Diag(Mod->getExprLoc(),
7318 IsModMod ? diag::warn_unsequenced_mod_mod
7319 : diag::warn_unsequenced_mod_use)
7320 << O << SourceRange(ModOrUse->getExprLoc());
7321 UI.Diagnosed = true;
7322 }
7323
7324 void notePreUse(Object O, Expr *Use) {
7325 UsageInfo &U = UsageMap[O];
7326 // Uses conflict with other modifications.
7327 checkUsage(O, U, Use, UK_ModAsValue, false);
7328 }
7329 void notePostUse(Object O, Expr *Use) {
7330 UsageInfo &U = UsageMap[O];
7331 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7332 addUsage(U, O, Use, UK_Use);
7333 }
7334
7335 void notePreMod(Object O, Expr *Mod) {
7336 UsageInfo &U = UsageMap[O];
7337 // Modifications conflict with other modifications and with uses.
7338 checkUsage(O, U, Mod, UK_ModAsValue, true);
7339 checkUsage(O, U, Mod, UK_Use, false);
7340 }
7341 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7342 UsageInfo &U = UsageMap[O];
7343 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7344 addUsage(U, O, Use, UK);
7345 }
7346
7347public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007348 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007349 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7350 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007351 Visit(E);
7352 }
7353
7354 void VisitStmt(Stmt *S) {
7355 // Skip all statements which aren't expressions for now.
7356 }
7357
7358 void VisitExpr(Expr *E) {
7359 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007360 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007361 }
7362
7363 void VisitCastExpr(CastExpr *E) {
7364 Object O = Object();
7365 if (E->getCastKind() == CK_LValueToRValue)
7366 O = getObject(E->getSubExpr(), false);
7367
7368 if (O)
7369 notePreUse(O, E);
7370 VisitExpr(E);
7371 if (O)
7372 notePostUse(O, E);
7373 }
7374
7375 void VisitBinComma(BinaryOperator *BO) {
7376 // C++11 [expr.comma]p1:
7377 // Every value computation and side effect associated with the left
7378 // expression is sequenced before every value computation and side
7379 // effect associated with the right expression.
7380 SequenceTree::Seq LHS = Tree.allocate(Region);
7381 SequenceTree::Seq RHS = Tree.allocate(Region);
7382 SequenceTree::Seq OldRegion = Region;
7383
7384 {
7385 SequencedSubexpression SeqLHS(*this);
7386 Region = LHS;
7387 Visit(BO->getLHS());
7388 }
7389
7390 Region = RHS;
7391 Visit(BO->getRHS());
7392
7393 Region = OldRegion;
7394
7395 // Forget that LHS and RHS are sequenced. They are both unsequenced
7396 // with respect to other stuff.
7397 Tree.merge(LHS);
7398 Tree.merge(RHS);
7399 }
7400
7401 void VisitBinAssign(BinaryOperator *BO) {
7402 // The modification is sequenced after the value computation of the LHS
7403 // and RHS, so check it before inspecting the operands and update the
7404 // map afterwards.
7405 Object O = getObject(BO->getLHS(), true);
7406 if (!O)
7407 return VisitExpr(BO);
7408
7409 notePreMod(O, BO);
7410
7411 // C++11 [expr.ass]p7:
7412 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7413 // only once.
7414 //
7415 // Therefore, for a compound assignment operator, O is considered used
7416 // everywhere except within the evaluation of E1 itself.
7417 if (isa<CompoundAssignOperator>(BO))
7418 notePreUse(O, BO);
7419
7420 Visit(BO->getLHS());
7421
7422 if (isa<CompoundAssignOperator>(BO))
7423 notePostUse(O, BO);
7424
7425 Visit(BO->getRHS());
7426
Richard Smith83e37bee2013-06-26 23:16:51 +00007427 // C++11 [expr.ass]p1:
7428 // the assignment is sequenced [...] before the value computation of the
7429 // assignment expression.
7430 // C11 6.5.16/3 has no such rule.
7431 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7432 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007433 }
7434 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7435 VisitBinAssign(CAO);
7436 }
7437
7438 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7439 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7440 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7441 Object O = getObject(UO->getSubExpr(), true);
7442 if (!O)
7443 return VisitExpr(UO);
7444
7445 notePreMod(O, UO);
7446 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007447 // C++11 [expr.pre.incr]p1:
7448 // the expression ++x is equivalent to x+=1
7449 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7450 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007451 }
7452
7453 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7454 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7455 void VisitUnaryPostIncDec(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());
7462 notePostMod(O, UO, UK_ModAsSideEffect);
7463 }
7464
7465 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7466 void VisitBinLOr(BinaryOperator *BO) {
7467 // The side-effects of the LHS of an '&&' are sequenced before the
7468 // value computation of the RHS, and hence before the value computation
7469 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7470 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007471 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007472 {
7473 SequencedSubexpression Sequenced(*this);
7474 Visit(BO->getLHS());
7475 }
7476
7477 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007478 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007479 if (!Result)
7480 Visit(BO->getRHS());
7481 } else {
7482 // Check for unsequenced operations in the RHS, treating it as an
7483 // entirely separate evaluation.
7484 //
7485 // FIXME: If there are operations in the RHS which are unsequenced
7486 // with respect to operations outside the RHS, and those operations
7487 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007488 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007489 }
Richard Smithc406cb72013-01-17 01:17:56 +00007490 }
7491 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007492 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007493 {
7494 SequencedSubexpression Sequenced(*this);
7495 Visit(BO->getLHS());
7496 }
7497
7498 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007499 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007500 if (Result)
7501 Visit(BO->getRHS());
7502 } else {
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
7507 // Only visit the condition, unless we can be sure which subexpression will
7508 // be chosen.
7509 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007510 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007511 {
7512 SequencedSubexpression Sequenced(*this);
7513 Visit(CO->getCond());
7514 }
Richard Smithc406cb72013-01-17 01:17:56 +00007515
7516 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007517 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007518 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007519 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007520 WorkList.push_back(CO->getTrueExpr());
7521 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007522 }
Richard Smithc406cb72013-01-17 01:17:56 +00007523 }
7524
Richard Smithe3dbfe02013-06-30 10:40:20 +00007525 void VisitCallExpr(CallExpr *CE) {
7526 // C++11 [intro.execution]p15:
7527 // When calling a function [...], every value computation and side effect
7528 // associated with any argument expression, or with the postfix expression
7529 // designating the called function, is sequenced before execution of every
7530 // expression or statement in the body of the function [and thus before
7531 // the value computation of its result].
7532 SequencedSubexpression Sequenced(*this);
7533 Base::VisitCallExpr(CE);
7534
7535 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7536 }
7537
Richard Smithc406cb72013-01-17 01:17:56 +00007538 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007539 // This is a call, so all subexpressions are sequenced before the result.
7540 SequencedSubexpression Sequenced(*this);
7541
Richard Smithc406cb72013-01-17 01:17:56 +00007542 if (!CCE->isListInitialization())
7543 return VisitExpr(CCE);
7544
7545 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007546 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007547 SequenceTree::Seq Parent = Region;
7548 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7549 E = CCE->arg_end();
7550 I != E; ++I) {
7551 Region = Tree.allocate(Parent);
7552 Elts.push_back(Region);
7553 Visit(*I);
7554 }
7555
7556 // Forget that the initializers are sequenced.
7557 Region = Parent;
7558 for (unsigned I = 0; I < Elts.size(); ++I)
7559 Tree.merge(Elts[I]);
7560 }
7561
7562 void VisitInitListExpr(InitListExpr *ILE) {
7563 if (!SemaRef.getLangOpts().CPlusPlus11)
7564 return VisitExpr(ILE);
7565
7566 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007567 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007568 SequenceTree::Seq Parent = Region;
7569 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7570 Expr *E = ILE->getInit(I);
7571 if (!E) continue;
7572 Region = Tree.allocate(Parent);
7573 Elts.push_back(Region);
7574 Visit(E);
7575 }
7576
7577 // Forget that the initializers are sequenced.
7578 Region = Parent;
7579 for (unsigned I = 0; I < Elts.size(); ++I)
7580 Tree.merge(Elts[I]);
7581 }
7582};
7583}
7584
7585void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007586 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007587 WorkList.push_back(E);
7588 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007589 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007590 SequenceChecker(*this, Item, WorkList);
7591 }
Richard Smithc406cb72013-01-17 01:17:56 +00007592}
7593
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007594void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7595 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007596 CheckImplicitConversions(E, CheckLoc);
7597 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007598 if (!IsConstexpr && !E->isValueDependent())
7599 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007600}
7601
John McCall1f425642010-11-11 03:21:53 +00007602void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7603 FieldDecl *BitField,
7604 Expr *Init) {
7605 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7606}
7607
Mike Stump0c2ec772010-01-21 03:59:47 +00007608/// CheckParmsForFunctionDef - Check that the parameters of the given
7609/// function are appropriate for the definition of a function. This
7610/// takes care of any checks that cannot be performed on the
7611/// declaration itself, e.g., that the types of each of the function
7612/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007613bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7614 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007615 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007616 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007617 for (; P != PEnd; ++P) {
7618 ParmVarDecl *Param = *P;
7619
Mike Stump0c2ec772010-01-21 03:59:47 +00007620 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7621 // function declarator that is part of a function definition of
7622 // that function shall not have incomplete type.
7623 //
7624 // This is also C++ [dcl.fct]p6.
7625 if (!Param->isInvalidDecl() &&
7626 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007627 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007628 Param->setInvalidDecl();
7629 HasInvalidParm = true;
7630 }
7631
7632 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7633 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007634 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007635 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007636 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007637 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007638 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007639
7640 // C99 6.7.5.3p12:
7641 // If the function declarator is not part of a definition of that
7642 // function, parameters may have incomplete type and may use the [*]
7643 // notation in their sequences of declarator specifiers to specify
7644 // variable length array types.
7645 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007646 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007647 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007648 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007649 // information is added for it.
7650 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007651 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007652 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007653 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007654 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007655
7656 // MSVC destroys objects passed by value in the callee. Therefore a
7657 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007658 // object's destructor. However, we don't perform any direct access check
7659 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007660 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7661 .getCXXABI()
7662 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007663 if (!Param->isInvalidDecl()) {
7664 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7665 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7666 if (!ClassDecl->isInvalidDecl() &&
7667 !ClassDecl->hasIrrelevantDestructor() &&
7668 !ClassDecl->isDependentContext()) {
7669 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7670 MarkFunctionReferenced(Param->getLocation(), Destructor);
7671 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7672 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007673 }
7674 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007675 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007676 }
7677
7678 return HasInvalidParm;
7679}
John McCall2b5c1b22010-08-12 21:44:57 +00007680
7681/// CheckCastAlign - Implements -Wcast-align, which warns when a
7682/// pointer cast increases the alignment requirements.
7683void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7684 // This is actually a lot of work to potentially be doing on every
7685 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007686 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007687 return;
7688
7689 // Ignore dependent types.
7690 if (T->isDependentType() || Op->getType()->isDependentType())
7691 return;
7692
7693 // Require that the destination be a pointer type.
7694 const PointerType *DestPtr = T->getAs<PointerType>();
7695 if (!DestPtr) return;
7696
7697 // If the destination has alignment 1, we're done.
7698 QualType DestPointee = DestPtr->getPointeeType();
7699 if (DestPointee->isIncompleteType()) return;
7700 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7701 if (DestAlign.isOne()) return;
7702
7703 // Require that the source be a pointer type.
7704 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7705 if (!SrcPtr) return;
7706 QualType SrcPointee = SrcPtr->getPointeeType();
7707
7708 // Whitelist casts from cv void*. We already implicitly
7709 // whitelisted casts to cv void*, since they have alignment 1.
7710 // Also whitelist casts involving incomplete types, which implicitly
7711 // includes 'void'.
7712 if (SrcPointee->isIncompleteType()) return;
7713
7714 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7715 if (SrcAlign >= DestAlign) return;
7716
7717 Diag(TRange.getBegin(), diag::warn_cast_align)
7718 << Op->getType() << T
7719 << static_cast<unsigned>(SrcAlign.getQuantity())
7720 << static_cast<unsigned>(DestAlign.getQuantity())
7721 << TRange << Op->getSourceRange();
7722}
7723
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007724static const Type* getElementType(const Expr *BaseExpr) {
7725 const Type* EltType = BaseExpr->getType().getTypePtr();
7726 if (EltType->isAnyPointerType())
7727 return EltType->getPointeeType().getTypePtr();
7728 else if (EltType->isArrayType())
7729 return EltType->getBaseElementTypeUnsafe();
7730 return EltType;
7731}
7732
Chandler Carruth28389f02011-08-05 09:10:50 +00007733/// \brief Check whether this array fits the idiom of a size-one tail padded
7734/// array member of a struct.
7735///
7736/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7737/// commonly used to emulate flexible arrays in C89 code.
7738static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7739 const NamedDecl *ND) {
7740 if (Size != 1 || !ND) return false;
7741
7742 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7743 if (!FD) return false;
7744
7745 // Don't consider sizes resulting from macro expansions or template argument
7746 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007747
7748 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007749 while (TInfo) {
7750 TypeLoc TL = TInfo->getTypeLoc();
7751 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007752 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7753 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007754 TInfo = TDL->getTypeSourceInfo();
7755 continue;
7756 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007757 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7758 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007759 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7760 return false;
7761 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007762 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007763 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007764
7765 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007766 if (!RD) return false;
7767 if (RD->isUnion()) return false;
7768 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7769 if (!CRD->isStandardLayout()) return false;
7770 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007771
Benjamin Kramer8c543672011-08-06 03:04:42 +00007772 // See if this is the last field decl in the record.
7773 const Decl *D = FD;
7774 while ((D = D->getNextDeclInContext()))
7775 if (isa<FieldDecl>(D))
7776 return false;
7777 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007778}
7779
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007780void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007781 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007782 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007783 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007784 if (IndexExpr->isValueDependent())
7785 return;
7786
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007787 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007788 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007789 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007790 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007791 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007792 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007793
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007794 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007795 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007796 return;
Richard Smith13f67182011-12-16 19:31:14 +00007797 if (IndexNegated)
7798 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007799
Craig Topperc3ec1492014-05-26 06:22:03 +00007800 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007801 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7802 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007803 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007804 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007805
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007806 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007807 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007808 if (!size.isStrictlyPositive())
7809 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007810
7811 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007812 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007813 // Make sure we're comparing apples to apples when comparing index to size
7814 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7815 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007816 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007817 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007818 if (ptrarith_typesize != array_typesize) {
7819 // There's a cast to a different size type involved
7820 uint64_t ratio = array_typesize / ptrarith_typesize;
7821 // TODO: Be smarter about handling cases where array_typesize is not a
7822 // multiple of ptrarith_typesize
7823 if (ptrarith_typesize * ratio == array_typesize)
7824 size *= llvm::APInt(size.getBitWidth(), ratio);
7825 }
7826 }
7827
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007828 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007829 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007830 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007831 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007832
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007833 // For array subscripting the index must be less than size, but for pointer
7834 // arithmetic also allow the index (offset) to be equal to size since
7835 // computing the next address after the end of the array is legal and
7836 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007837 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007838 return;
7839
7840 // Also don't warn for arrays of size 1 which are members of some
7841 // structure. These are often used to approximate flexible arrays in C89
7842 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007843 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007844 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007845
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007846 // Suppress the warning if the subscript expression (as identified by the
7847 // ']' location) and the index expression are both from macro expansions
7848 // within a system header.
7849 if (ASE) {
7850 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7851 ASE->getRBracketLoc());
7852 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7853 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7854 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007855 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007856 return;
7857 }
7858 }
7859
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007860 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007861 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007862 DiagID = diag::warn_array_index_exceeds_bounds;
7863
7864 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7865 PDiag(DiagID) << index.toString(10, true)
7866 << size.toString(10, true)
7867 << (unsigned)size.getLimitedValue(~0U)
7868 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007869 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007870 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007871 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007872 DiagID = diag::warn_ptr_arith_precedes_bounds;
7873 if (index.isNegative()) index = -index;
7874 }
7875
7876 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7877 PDiag(DiagID) << index.toString(10, true)
7878 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007879 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007880
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007881 if (!ND) {
7882 // Try harder to find a NamedDecl to point at in the note.
7883 while (const ArraySubscriptExpr *ASE =
7884 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7885 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7886 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7887 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7888 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7889 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7890 }
7891
Chandler Carruth1af88f12011-02-17 21:10:52 +00007892 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007893 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7894 PDiag(diag::note_array_index_out_of_bounds)
7895 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007896}
7897
Ted Kremenekdf26df72011-03-01 18:41:00 +00007898void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007899 int AllowOnePastEnd = 0;
7900 while (expr) {
7901 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007902 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007903 case Stmt::ArraySubscriptExprClass: {
7904 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007905 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007906 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007907 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007908 }
7909 case Stmt::UnaryOperatorClass: {
7910 // Only unwrap the * and & unary operators
7911 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7912 expr = UO->getSubExpr();
7913 switch (UO->getOpcode()) {
7914 case UO_AddrOf:
7915 AllowOnePastEnd++;
7916 break;
7917 case UO_Deref:
7918 AllowOnePastEnd--;
7919 break;
7920 default:
7921 return;
7922 }
7923 break;
7924 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007925 case Stmt::ConditionalOperatorClass: {
7926 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7927 if (const Expr *lhs = cond->getLHS())
7928 CheckArrayAccess(lhs);
7929 if (const Expr *rhs = cond->getRHS())
7930 CheckArrayAccess(rhs);
7931 return;
7932 }
7933 default:
7934 return;
7935 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007936 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007937}
John McCall31168b02011-06-15 23:02:42 +00007938
7939//===--- CHECK: Objective-C retain cycles ----------------------------------//
7940
7941namespace {
7942 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007943 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007944 VarDecl *Variable;
7945 SourceRange Range;
7946 SourceLocation Loc;
7947 bool Indirect;
7948
7949 void setLocsFrom(Expr *e) {
7950 Loc = e->getExprLoc();
7951 Range = e->getSourceRange();
7952 }
7953 };
7954}
7955
7956/// Consider whether capturing the given variable can possibly lead to
7957/// a retain cycle.
7958static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007959 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007960 // lifetime. In MRR, it's captured strongly if the variable is
7961 // __block and has an appropriate type.
7962 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7963 return false;
7964
7965 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007966 if (ref)
7967 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007968 return true;
7969}
7970
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007971static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007972 while (true) {
7973 e = e->IgnoreParens();
7974 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7975 switch (cast->getCastKind()) {
7976 case CK_BitCast:
7977 case CK_LValueBitCast:
7978 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007979 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007980 e = cast->getSubExpr();
7981 continue;
7982
John McCall31168b02011-06-15 23:02:42 +00007983 default:
7984 return false;
7985 }
7986 }
7987
7988 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7989 ObjCIvarDecl *ivar = ref->getDecl();
7990 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7991 return false;
7992
7993 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007994 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007995 return false;
7996
7997 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7998 owner.Indirect = true;
7999 return true;
8000 }
8001
8002 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8003 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8004 if (!var) return false;
8005 return considerVariable(var, ref, owner);
8006 }
8007
John McCall31168b02011-06-15 23:02:42 +00008008 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8009 if (member->isArrow()) return false;
8010
8011 // Don't count this as an indirect ownership.
8012 e = member->getBase();
8013 continue;
8014 }
8015
John McCallfe96e0b2011-11-06 09:01:30 +00008016 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8017 // Only pay attention to pseudo-objects on property references.
8018 ObjCPropertyRefExpr *pre
8019 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8020 ->IgnoreParens());
8021 if (!pre) return false;
8022 if (pre->isImplicitProperty()) return false;
8023 ObjCPropertyDecl *property = pre->getExplicitProperty();
8024 if (!property->isRetaining() &&
8025 !(property->getPropertyIvarDecl() &&
8026 property->getPropertyIvarDecl()->getType()
8027 .getObjCLifetime() == Qualifiers::OCL_Strong))
8028 return false;
8029
8030 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008031 if (pre->isSuperReceiver()) {
8032 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8033 if (!owner.Variable)
8034 return false;
8035 owner.Loc = pre->getLocation();
8036 owner.Range = pre->getSourceRange();
8037 return true;
8038 }
John McCallfe96e0b2011-11-06 09:01:30 +00008039 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8040 ->getSourceExpr());
8041 continue;
8042 }
8043
John McCall31168b02011-06-15 23:02:42 +00008044 // Array ivars?
8045
8046 return false;
8047 }
8048}
8049
8050namespace {
8051 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8052 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8053 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008054 Context(Context), Variable(variable), Capturer(nullptr),
8055 VarWillBeReased(false) {}
8056 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008057 VarDecl *Variable;
8058 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008059 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008060
8061 void VisitDeclRefExpr(DeclRefExpr *ref) {
8062 if (ref->getDecl() == Variable && !Capturer)
8063 Capturer = ref;
8064 }
8065
John McCall31168b02011-06-15 23:02:42 +00008066 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8067 if (Capturer) return;
8068 Visit(ref->getBase());
8069 if (Capturer && ref->isFreeIvar())
8070 Capturer = ref;
8071 }
8072
8073 void VisitBlockExpr(BlockExpr *block) {
8074 // Look inside nested blocks
8075 if (block->getBlockDecl()->capturesVariable(Variable))
8076 Visit(block->getBlockDecl()->getBody());
8077 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008078
8079 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8080 if (Capturer) return;
8081 if (OVE->getSourceExpr())
8082 Visit(OVE->getSourceExpr());
8083 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008084 void VisitBinaryOperator(BinaryOperator *BinOp) {
8085 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8086 return;
8087 Expr *LHS = BinOp->getLHS();
8088 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8089 if (DRE->getDecl() != Variable)
8090 return;
8091 if (Expr *RHS = BinOp->getRHS()) {
8092 RHS = RHS->IgnoreParenCasts();
8093 llvm::APSInt Value;
8094 VarWillBeReased =
8095 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8096 }
8097 }
8098 }
John McCall31168b02011-06-15 23:02:42 +00008099 };
8100}
8101
8102/// Check whether the given argument is a block which captures a
8103/// variable.
8104static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8105 assert(owner.Variable && owner.Loc.isValid());
8106
8107 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008108
8109 // Look through [^{...} copy] and Block_copy(^{...}).
8110 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8111 Selector Cmd = ME->getSelector();
8112 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8113 e = ME->getInstanceReceiver();
8114 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008115 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008116 e = e->IgnoreParenCasts();
8117 }
8118 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8119 if (CE->getNumArgs() == 1) {
8120 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008121 if (Fn) {
8122 const IdentifierInfo *FnI = Fn->getIdentifier();
8123 if (FnI && FnI->isStr("_Block_copy")) {
8124 e = CE->getArg(0)->IgnoreParenCasts();
8125 }
8126 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008127 }
8128 }
8129
John McCall31168b02011-06-15 23:02:42 +00008130 BlockExpr *block = dyn_cast<BlockExpr>(e);
8131 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008132 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008133
8134 FindCaptureVisitor visitor(S.Context, owner.Variable);
8135 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008136 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008137}
8138
8139static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8140 RetainCycleOwner &owner) {
8141 assert(capturer);
8142 assert(owner.Variable && owner.Loc.isValid());
8143
8144 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8145 << owner.Variable << capturer->getSourceRange();
8146 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8147 << owner.Indirect << owner.Range;
8148}
8149
8150/// Check for a keyword selector that starts with the word 'add' or
8151/// 'set'.
8152static bool isSetterLikeSelector(Selector sel) {
8153 if (sel.isUnarySelector()) return false;
8154
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008155 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008156 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008157 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008158 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008159 else if (str.startswith("add")) {
8160 // Specially whitelist 'addOperationWithBlock:'.
8161 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8162 return false;
8163 str = str.substr(3);
8164 }
John McCall31168b02011-06-15 23:02:42 +00008165 else
8166 return false;
8167
8168 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008169 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008170}
8171
8172/// Check a message send to see if it's likely to cause a retain cycle.
8173void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8174 // Only check instance methods whose selector looks like a setter.
8175 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8176 return;
8177
8178 // Try to find a variable that the receiver is strongly owned by.
8179 RetainCycleOwner owner;
8180 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008181 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008182 return;
8183 } else {
8184 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8185 owner.Variable = getCurMethodDecl()->getSelfDecl();
8186 owner.Loc = msg->getSuperLoc();
8187 owner.Range = msg->getSuperLoc();
8188 }
8189
8190 // Check whether the receiver is captured by any of the arguments.
8191 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8192 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8193 return diagnoseRetainCycle(*this, capturer, owner);
8194}
8195
8196/// Check a property assign to see if it's likely to cause a retain cycle.
8197void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8198 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008199 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008200 return;
8201
8202 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8203 diagnoseRetainCycle(*this, capturer, owner);
8204}
8205
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008206void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8207 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008208 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008209 return;
8210
8211 // Because we don't have an expression for the variable, we have to set the
8212 // location explicitly here.
8213 Owner.Loc = Var->getLocation();
8214 Owner.Range = Var->getSourceRange();
8215
8216 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8217 diagnoseRetainCycle(*this, Capturer, Owner);
8218}
8219
Ted Kremenek9304da92012-12-21 08:04:28 +00008220static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8221 Expr *RHS, bool isProperty) {
8222 // Check if RHS is an Objective-C object literal, which also can get
8223 // immediately zapped in a weak reference. Note that we explicitly
8224 // allow ObjCStringLiterals, since those are designed to never really die.
8225 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008226
Ted Kremenek64873352012-12-21 22:46:35 +00008227 // This enum needs to match with the 'select' in
8228 // warn_objc_arc_literal_assign (off-by-1).
8229 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8230 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8231 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008232
8233 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008234 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008235 << (isProperty ? 0 : 1)
8236 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008237
8238 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008239}
8240
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008241static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8242 Qualifiers::ObjCLifetime LT,
8243 Expr *RHS, bool isProperty) {
8244 // Strip off any implicit cast added to get to the one ARC-specific.
8245 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8246 if (cast->getCastKind() == CK_ARCConsumeObject) {
8247 S.Diag(Loc, diag::warn_arc_retained_assign)
8248 << (LT == Qualifiers::OCL_ExplicitNone)
8249 << (isProperty ? 0 : 1)
8250 << RHS->getSourceRange();
8251 return true;
8252 }
8253 RHS = cast->getSubExpr();
8254 }
8255
8256 if (LT == Qualifiers::OCL_Weak &&
8257 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8258 return true;
8259
8260 return false;
8261}
8262
Ted Kremenekb36234d2012-12-21 08:04:20 +00008263bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8264 QualType LHS, Expr *RHS) {
8265 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8266
8267 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8268 return false;
8269
8270 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8271 return true;
8272
8273 return false;
8274}
8275
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008276void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8277 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008278 QualType LHSType;
8279 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008280 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008281 ObjCPropertyRefExpr *PRE
8282 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8283 if (PRE && !PRE->isImplicitProperty()) {
8284 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8285 if (PD)
8286 LHSType = PD->getType();
8287 }
8288
8289 if (LHSType.isNull())
8290 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008291
8292 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8293
8294 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008295 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008296 getCurFunction()->markSafeWeakUse(LHS);
8297 }
8298
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008299 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8300 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008301
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008302 // FIXME. Check for other life times.
8303 if (LT != Qualifiers::OCL_None)
8304 return;
8305
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008306 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008307 if (PRE->isImplicitProperty())
8308 return;
8309 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8310 if (!PD)
8311 return;
8312
Bill Wendling44426052012-12-20 19:22:21 +00008313 unsigned Attributes = PD->getPropertyAttributes();
8314 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008315 // when 'assign' attribute was not explicitly specified
8316 // by user, ignore it and rely on property type itself
8317 // for lifetime info.
8318 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8319 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8320 LHSType->isObjCRetainableType())
8321 return;
8322
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008323 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008324 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008325 Diag(Loc, diag::warn_arc_retained_property_assign)
8326 << RHS->getSourceRange();
8327 return;
8328 }
8329 RHS = cast->getSubExpr();
8330 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008331 }
Bill Wendling44426052012-12-20 19:22:21 +00008332 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008333 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8334 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008335 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008336 }
8337}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008338
8339//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8340
8341namespace {
8342bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8343 SourceLocation StmtLoc,
8344 const NullStmt *Body) {
8345 // Do not warn if the body is a macro that expands to nothing, e.g:
8346 //
8347 // #define CALL(x)
8348 // if (condition)
8349 // CALL(0);
8350 //
8351 if (Body->hasLeadingEmptyMacro())
8352 return false;
8353
8354 // Get line numbers of statement and body.
8355 bool StmtLineInvalid;
8356 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8357 &StmtLineInvalid);
8358 if (StmtLineInvalid)
8359 return false;
8360
8361 bool BodyLineInvalid;
8362 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8363 &BodyLineInvalid);
8364 if (BodyLineInvalid)
8365 return false;
8366
8367 // Warn if null statement and body are on the same line.
8368 if (StmtLine != BodyLine)
8369 return false;
8370
8371 return true;
8372}
8373} // Unnamed namespace
8374
8375void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8376 const Stmt *Body,
8377 unsigned DiagID) {
8378 // Since this is a syntactic check, don't emit diagnostic for template
8379 // instantiations, this just adds noise.
8380 if (CurrentInstantiationScope)
8381 return;
8382
8383 // The body should be a null statement.
8384 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8385 if (!NBody)
8386 return;
8387
8388 // Do the usual checks.
8389 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8390 return;
8391
8392 Diag(NBody->getSemiLoc(), DiagID);
8393 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8394}
8395
8396void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8397 const Stmt *PossibleBody) {
8398 assert(!CurrentInstantiationScope); // Ensured by caller
8399
8400 SourceLocation StmtLoc;
8401 const Stmt *Body;
8402 unsigned DiagID;
8403 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8404 StmtLoc = FS->getRParenLoc();
8405 Body = FS->getBody();
8406 DiagID = diag::warn_empty_for_body;
8407 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8408 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8409 Body = WS->getBody();
8410 DiagID = diag::warn_empty_while_body;
8411 } else
8412 return; // Neither `for' nor `while'.
8413
8414 // The body should be a null statement.
8415 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8416 if (!NBody)
8417 return;
8418
8419 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008420 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008421 return;
8422
8423 // Do the usual checks.
8424 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8425 return;
8426
8427 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8428 // noise level low, emit diagnostics only if for/while is followed by a
8429 // CompoundStmt, e.g.:
8430 // for (int i = 0; i < n; i++);
8431 // {
8432 // a(i);
8433 // }
8434 // or if for/while is followed by a statement with more indentation
8435 // than for/while itself:
8436 // for (int i = 0; i < n; i++);
8437 // a(i);
8438 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8439 if (!ProbableTypo) {
8440 bool BodyColInvalid;
8441 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8442 PossibleBody->getLocStart(),
8443 &BodyColInvalid);
8444 if (BodyColInvalid)
8445 return;
8446
8447 bool StmtColInvalid;
8448 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8449 S->getLocStart(),
8450 &StmtColInvalid);
8451 if (StmtColInvalid)
8452 return;
8453
8454 if (BodyCol > StmtCol)
8455 ProbableTypo = true;
8456 }
8457
8458 if (ProbableTypo) {
8459 Diag(NBody->getSemiLoc(), DiagID);
8460 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8461 }
8462}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008463
Richard Trieu36d0b2b2015-01-13 02:32:02 +00008464//===--- CHECK: Warn on self move with std::move. -------------------------===//
8465
8466/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8467void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8468 SourceLocation OpLoc) {
8469
8470 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8471 return;
8472
8473 if (!ActiveTemplateInstantiations.empty())
8474 return;
8475
8476 // Strip parens and casts away.
8477 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8478 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8479
8480 // Check for a call expression
8481 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8482 if (!CE || CE->getNumArgs() != 1)
8483 return;
8484
8485 // Check for a call to std::move
8486 const FunctionDecl *FD = CE->getDirectCallee();
8487 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8488 !FD->getIdentifier()->isStr("move"))
8489 return;
8490
8491 // Get argument from std::move
8492 RHSExpr = CE->getArg(0);
8493
8494 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8495 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8496
8497 // Two DeclRefExpr's, check that the decls are the same.
8498 if (LHSDeclRef && RHSDeclRef) {
8499 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8500 return;
8501 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8502 RHSDeclRef->getDecl()->getCanonicalDecl())
8503 return;
8504
8505 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8506 << LHSExpr->getSourceRange()
8507 << RHSExpr->getSourceRange();
8508 return;
8509 }
8510
8511 // Member variables require a different approach to check for self moves.
8512 // MemberExpr's are the same if every nested MemberExpr refers to the same
8513 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8514 // the base Expr's are CXXThisExpr's.
8515 const Expr *LHSBase = LHSExpr;
8516 const Expr *RHSBase = RHSExpr;
8517 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8518 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8519 if (!LHSME || !RHSME)
8520 return;
8521
8522 while (LHSME && RHSME) {
8523 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8524 RHSME->getMemberDecl()->getCanonicalDecl())
8525 return;
8526
8527 LHSBase = LHSME->getBase();
8528 RHSBase = RHSME->getBase();
8529 LHSME = dyn_cast<MemberExpr>(LHSBase);
8530 RHSME = dyn_cast<MemberExpr>(RHSBase);
8531 }
8532
8533 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8534 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8535 if (LHSDeclRef && RHSDeclRef) {
8536 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8537 return;
8538 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8539 RHSDeclRef->getDecl()->getCanonicalDecl())
8540 return;
8541
8542 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8543 << LHSExpr->getSourceRange()
8544 << RHSExpr->getSourceRange();
8545 return;
8546 }
8547
8548 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8549 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8550 << LHSExpr->getSourceRange()
8551 << RHSExpr->getSourceRange();
8552}
8553
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008554//===--- Layout compatibility ----------------------------------------------//
8555
8556namespace {
8557
8558bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8559
8560/// \brief Check if two enumeration types are layout-compatible.
8561bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8562 // C++11 [dcl.enum] p8:
8563 // Two enumeration types are layout-compatible if they have the same
8564 // underlying type.
8565 return ED1->isComplete() && ED2->isComplete() &&
8566 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8567}
8568
8569/// \brief Check if two fields are layout-compatible.
8570bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8571 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8572 return false;
8573
8574 if (Field1->isBitField() != Field2->isBitField())
8575 return false;
8576
8577 if (Field1->isBitField()) {
8578 // Make sure that the bit-fields are the same length.
8579 unsigned Bits1 = Field1->getBitWidthValue(C);
8580 unsigned Bits2 = Field2->getBitWidthValue(C);
8581
8582 if (Bits1 != Bits2)
8583 return false;
8584 }
8585
8586 return true;
8587}
8588
8589/// \brief Check if two standard-layout structs are layout-compatible.
8590/// (C++11 [class.mem] p17)
8591bool isLayoutCompatibleStruct(ASTContext &C,
8592 RecordDecl *RD1,
8593 RecordDecl *RD2) {
8594 // If both records are C++ classes, check that base classes match.
8595 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8596 // If one of records is a CXXRecordDecl we are in C++ mode,
8597 // thus the other one is a CXXRecordDecl, too.
8598 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8599 // Check number of base classes.
8600 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8601 return false;
8602
8603 // Check the base classes.
8604 for (CXXRecordDecl::base_class_const_iterator
8605 Base1 = D1CXX->bases_begin(),
8606 BaseEnd1 = D1CXX->bases_end(),
8607 Base2 = D2CXX->bases_begin();
8608 Base1 != BaseEnd1;
8609 ++Base1, ++Base2) {
8610 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8611 return false;
8612 }
8613 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8614 // If only RD2 is a C++ class, it should have zero base classes.
8615 if (D2CXX->getNumBases() > 0)
8616 return false;
8617 }
8618
8619 // Check the fields.
8620 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8621 Field2End = RD2->field_end(),
8622 Field1 = RD1->field_begin(),
8623 Field1End = RD1->field_end();
8624 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8625 if (!isLayoutCompatible(C, *Field1, *Field2))
8626 return false;
8627 }
8628 if (Field1 != Field1End || Field2 != Field2End)
8629 return false;
8630
8631 return true;
8632}
8633
8634/// \brief Check if two standard-layout unions are layout-compatible.
8635/// (C++11 [class.mem] p18)
8636bool isLayoutCompatibleUnion(ASTContext &C,
8637 RecordDecl *RD1,
8638 RecordDecl *RD2) {
8639 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008640 for (auto *Field2 : RD2->fields())
8641 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008642
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008643 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008644 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8645 I = UnmatchedFields.begin(),
8646 E = UnmatchedFields.end();
8647
8648 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008649 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008650 bool Result = UnmatchedFields.erase(*I);
8651 (void) Result;
8652 assert(Result);
8653 break;
8654 }
8655 }
8656 if (I == E)
8657 return false;
8658 }
8659
8660 return UnmatchedFields.empty();
8661}
8662
8663bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8664 if (RD1->isUnion() != RD2->isUnion())
8665 return false;
8666
8667 if (RD1->isUnion())
8668 return isLayoutCompatibleUnion(C, RD1, RD2);
8669 else
8670 return isLayoutCompatibleStruct(C, RD1, RD2);
8671}
8672
8673/// \brief Check if two types are layout-compatible in C++11 sense.
8674bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8675 if (T1.isNull() || T2.isNull())
8676 return false;
8677
8678 // C++11 [basic.types] p11:
8679 // If two types T1 and T2 are the same type, then T1 and T2 are
8680 // layout-compatible types.
8681 if (C.hasSameType(T1, T2))
8682 return true;
8683
8684 T1 = T1.getCanonicalType().getUnqualifiedType();
8685 T2 = T2.getCanonicalType().getUnqualifiedType();
8686
8687 const Type::TypeClass TC1 = T1->getTypeClass();
8688 const Type::TypeClass TC2 = T2->getTypeClass();
8689
8690 if (TC1 != TC2)
8691 return false;
8692
8693 if (TC1 == Type::Enum) {
8694 return isLayoutCompatible(C,
8695 cast<EnumType>(T1)->getDecl(),
8696 cast<EnumType>(T2)->getDecl());
8697 } else if (TC1 == Type::Record) {
8698 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8699 return false;
8700
8701 return isLayoutCompatible(C,
8702 cast<RecordType>(T1)->getDecl(),
8703 cast<RecordType>(T2)->getDecl());
8704 }
8705
8706 return false;
8707}
8708}
8709
8710//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8711
8712namespace {
8713/// \brief Given a type tag expression find the type tag itself.
8714///
8715/// \param TypeExpr Type tag expression, as it appears in user's code.
8716///
8717/// \param VD Declaration of an identifier that appears in a type tag.
8718///
8719/// \param MagicValue Type tag magic value.
8720bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8721 const ValueDecl **VD, uint64_t *MagicValue) {
8722 while(true) {
8723 if (!TypeExpr)
8724 return false;
8725
8726 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8727
8728 switch (TypeExpr->getStmtClass()) {
8729 case Stmt::UnaryOperatorClass: {
8730 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8731 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8732 TypeExpr = UO->getSubExpr();
8733 continue;
8734 }
8735 return false;
8736 }
8737
8738 case Stmt::DeclRefExprClass: {
8739 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8740 *VD = DRE->getDecl();
8741 return true;
8742 }
8743
8744 case Stmt::IntegerLiteralClass: {
8745 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8746 llvm::APInt MagicValueAPInt = IL->getValue();
8747 if (MagicValueAPInt.getActiveBits() <= 64) {
8748 *MagicValue = MagicValueAPInt.getZExtValue();
8749 return true;
8750 } else
8751 return false;
8752 }
8753
8754 case Stmt::BinaryConditionalOperatorClass:
8755 case Stmt::ConditionalOperatorClass: {
8756 const AbstractConditionalOperator *ACO =
8757 cast<AbstractConditionalOperator>(TypeExpr);
8758 bool Result;
8759 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8760 if (Result)
8761 TypeExpr = ACO->getTrueExpr();
8762 else
8763 TypeExpr = ACO->getFalseExpr();
8764 continue;
8765 }
8766 return false;
8767 }
8768
8769 case Stmt::BinaryOperatorClass: {
8770 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8771 if (BO->getOpcode() == BO_Comma) {
8772 TypeExpr = BO->getRHS();
8773 continue;
8774 }
8775 return false;
8776 }
8777
8778 default:
8779 return false;
8780 }
8781 }
8782}
8783
8784/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8785///
8786/// \param TypeExpr Expression that specifies a type tag.
8787///
8788/// \param MagicValues Registered magic values.
8789///
8790/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8791/// kind.
8792///
8793/// \param TypeInfo Information about the corresponding C type.
8794///
8795/// \returns true if the corresponding C type was found.
8796bool GetMatchingCType(
8797 const IdentifierInfo *ArgumentKind,
8798 const Expr *TypeExpr, const ASTContext &Ctx,
8799 const llvm::DenseMap<Sema::TypeTagMagicValue,
8800 Sema::TypeTagData> *MagicValues,
8801 bool &FoundWrongKind,
8802 Sema::TypeTagData &TypeInfo) {
8803 FoundWrongKind = false;
8804
8805 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008806 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008807
8808 uint64_t MagicValue;
8809
8810 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8811 return false;
8812
8813 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008814 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008815 if (I->getArgumentKind() != ArgumentKind) {
8816 FoundWrongKind = true;
8817 return false;
8818 }
8819 TypeInfo.Type = I->getMatchingCType();
8820 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8821 TypeInfo.MustBeNull = I->getMustBeNull();
8822 return true;
8823 }
8824 return false;
8825 }
8826
8827 if (!MagicValues)
8828 return false;
8829
8830 llvm::DenseMap<Sema::TypeTagMagicValue,
8831 Sema::TypeTagData>::const_iterator I =
8832 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8833 if (I == MagicValues->end())
8834 return false;
8835
8836 TypeInfo = I->second;
8837 return true;
8838}
8839} // unnamed namespace
8840
8841void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8842 uint64_t MagicValue, QualType Type,
8843 bool LayoutCompatible,
8844 bool MustBeNull) {
8845 if (!TypeTagForDatatypeMagicValues)
8846 TypeTagForDatatypeMagicValues.reset(
8847 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8848
8849 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8850 (*TypeTagForDatatypeMagicValues)[Magic] =
8851 TypeTagData(Type, LayoutCompatible, MustBeNull);
8852}
8853
8854namespace {
8855bool IsSameCharType(QualType T1, QualType T2) {
8856 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8857 if (!BT1)
8858 return false;
8859
8860 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8861 if (!BT2)
8862 return false;
8863
8864 BuiltinType::Kind T1Kind = BT1->getKind();
8865 BuiltinType::Kind T2Kind = BT2->getKind();
8866
8867 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8868 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8869 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8870 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8871}
8872} // unnamed namespace
8873
8874void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8875 const Expr * const *ExprArgs) {
8876 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8877 bool IsPointerAttr = Attr->getIsPointer();
8878
8879 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8880 bool FoundWrongKind;
8881 TypeTagData TypeInfo;
8882 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8883 TypeTagForDatatypeMagicValues.get(),
8884 FoundWrongKind, TypeInfo)) {
8885 if (FoundWrongKind)
8886 Diag(TypeTagExpr->getExprLoc(),
8887 diag::warn_type_tag_for_datatype_wrong_kind)
8888 << TypeTagExpr->getSourceRange();
8889 return;
8890 }
8891
8892 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8893 if (IsPointerAttr) {
8894 // Skip implicit cast of pointer to `void *' (as a function argument).
8895 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008896 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008897 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008898 ArgumentExpr = ICE->getSubExpr();
8899 }
8900 QualType ArgumentType = ArgumentExpr->getType();
8901
8902 // Passing a `void*' pointer shouldn't trigger a warning.
8903 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8904 return;
8905
8906 if (TypeInfo.MustBeNull) {
8907 // Type tag with matching void type requires a null pointer.
8908 if (!ArgumentExpr->isNullPointerConstant(Context,
8909 Expr::NPC_ValueDependentIsNotNull)) {
8910 Diag(ArgumentExpr->getExprLoc(),
8911 diag::warn_type_safety_null_pointer_required)
8912 << ArgumentKind->getName()
8913 << ArgumentExpr->getSourceRange()
8914 << TypeTagExpr->getSourceRange();
8915 }
8916 return;
8917 }
8918
8919 QualType RequiredType = TypeInfo.Type;
8920 if (IsPointerAttr)
8921 RequiredType = Context.getPointerType(RequiredType);
8922
8923 bool mismatch = false;
8924 if (!TypeInfo.LayoutCompatible) {
8925 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8926
8927 // C++11 [basic.fundamental] p1:
8928 // Plain char, signed char, and unsigned char are three distinct types.
8929 //
8930 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8931 // char' depending on the current char signedness mode.
8932 if (mismatch)
8933 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8934 RequiredType->getPointeeType())) ||
8935 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8936 mismatch = false;
8937 } else
8938 if (IsPointerAttr)
8939 mismatch = !isLayoutCompatible(Context,
8940 ArgumentType->getPointeeType(),
8941 RequiredType->getPointeeType());
8942 else
8943 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8944
8945 if (mismatch)
8946 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008947 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008948 << TypeInfo.LayoutCompatible << RequiredType
8949 << ArgumentExpr->getSourceRange()
8950 << TypeTagExpr->getSourceRange();
8951}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008952