blob: 6b569b63756b7ef7d8ab14d7f46ceffca3fab8f2 [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;
Craig Topper16015252015-01-31 06:31:23 +0000889 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +0000890 case X86::BI__builtin_ia32_vpermil2pd:
891 case X86::BI__builtin_ia32_vpermil2pd256:
892 case X86::BI__builtin_ia32_vpermil2ps:
893 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +0000894 case X86::BI__builtin_ia32_cmpb128_mask:
895 case X86::BI__builtin_ia32_cmpw128_mask:
896 case X86::BI__builtin_ia32_cmpd128_mask:
897 case X86::BI__builtin_ia32_cmpq128_mask:
898 case X86::BI__builtin_ia32_cmpb256_mask:
899 case X86::BI__builtin_ia32_cmpw256_mask:
900 case X86::BI__builtin_ia32_cmpd256_mask:
901 case X86::BI__builtin_ia32_cmpq256_mask:
902 case X86::BI__builtin_ia32_cmpb512_mask:
903 case X86::BI__builtin_ia32_cmpw512_mask:
904 case X86::BI__builtin_ia32_cmpd512_mask:
905 case X86::BI__builtin_ia32_cmpq512_mask:
906 case X86::BI__builtin_ia32_ucmpb128_mask:
907 case X86::BI__builtin_ia32_ucmpw128_mask:
908 case X86::BI__builtin_ia32_ucmpd128_mask:
909 case X86::BI__builtin_ia32_ucmpq128_mask:
910 case X86::BI__builtin_ia32_ucmpb256_mask:
911 case X86::BI__builtin_ia32_ucmpw256_mask:
912 case X86::BI__builtin_ia32_ucmpd256_mask:
913 case X86::BI__builtin_ia32_ucmpq256_mask:
914 case X86::BI__builtin_ia32_ucmpb512_mask:
915 case X86::BI__builtin_ia32_ucmpw512_mask:
916 case X86::BI__builtin_ia32_ucmpd512_mask:
917 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +0000918 case X86::BI__builtin_ia32_roundps:
919 case X86::BI__builtin_ia32_roundpd:
920 case X86::BI__builtin_ia32_roundps256:
921 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
922 case X86::BI__builtin_ia32_roundss:
923 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
924 case X86::BI__builtin_ia32_cmpps:
925 case X86::BI__builtin_ia32_cmpss:
926 case X86::BI__builtin_ia32_cmppd:
927 case X86::BI__builtin_ia32_cmpsd:
928 case X86::BI__builtin_ia32_cmpps256:
929 case X86::BI__builtin_ia32_cmppd256:
930 case X86::BI__builtin_ia32_cmpps512_mask:
931 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +0000932 case X86::BI__builtin_ia32_vpcomub:
933 case X86::BI__builtin_ia32_vpcomuw:
934 case X86::BI__builtin_ia32_vpcomud:
935 case X86::BI__builtin_ia32_vpcomuq:
936 case X86::BI__builtin_ia32_vpcomb:
937 case X86::BI__builtin_ia32_vpcomw:
938 case X86::BI__builtin_ia32_vpcomd:
939 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000940 }
Craig Topperdd84ec52014-12-27 07:00:08 +0000941 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000942}
943
Richard Smith55ce3522012-06-25 20:30:08 +0000944/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
945/// parameter with the FormatAttr's correct format_idx and firstDataArg.
946/// Returns true when the format fits the function and the FormatStringInfo has
947/// been populated.
948bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
949 FormatStringInfo *FSI) {
950 FSI->HasVAListArg = Format->getFirstArg() == 0;
951 FSI->FormatIdx = Format->getFormatIdx() - 1;
952 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000953
Richard Smith55ce3522012-06-25 20:30:08 +0000954 // The way the format attribute works in GCC, the implicit this argument
955 // of member functions is counted. However, it doesn't appear in our own
956 // lists, so decrement format_idx in that case.
957 if (IsCXXMember) {
958 if(FSI->FormatIdx == 0)
959 return false;
960 --FSI->FormatIdx;
961 if (FSI->FirstDataArg != 0)
962 --FSI->FirstDataArg;
963 }
964 return true;
965}
Mike Stump11289f42009-09-09 15:08:12 +0000966
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000967/// Checks if a the given expression evaluates to null.
968///
969/// \brief Returns true if the value evaluates to null.
970static bool CheckNonNullExpr(Sema &S,
971 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000972 // As a special case, transparent unions initialized with zero are
973 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000974 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000975 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
976 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000977 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000978 if (const InitListExpr *ILE =
979 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000980 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000981 }
982
983 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000984 return (!Expr->isValueDependent() &&
985 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
986 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000987}
988
989static void CheckNonNullArgument(Sema &S,
990 const Expr *ArgExpr,
991 SourceLocation CallSiteLoc) {
992 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000993 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
994}
995
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000996bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
997 FormatStringInfo FSI;
998 if ((GetFormatStringType(Format) == FST_NSString) &&
999 getFormatStringInfo(Format, false, &FSI)) {
1000 Idx = FSI.FormatIdx;
1001 return true;
1002 }
1003 return false;
1004}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001005/// \brief Diagnose use of %s directive in an NSString which is being passed
1006/// as formatting string to formatting method.
1007static void
1008DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1009 const NamedDecl *FDecl,
1010 Expr **Args,
1011 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001012 unsigned Idx = 0;
1013 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001014 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1015 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001016 Idx = 2;
1017 Format = true;
1018 }
1019 else
1020 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1021 if (S.GetFormatNSStringIdx(I, Idx)) {
1022 Format = true;
1023 break;
1024 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001025 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001026 if (!Format || NumArgs <= Idx)
1027 return;
1028 const Expr *FormatExpr = Args[Idx];
1029 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1030 FormatExpr = CSCE->getSubExpr();
1031 const StringLiteral *FormatString;
1032 if (const ObjCStringLiteral *OSL =
1033 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1034 FormatString = OSL->getString();
1035 else
1036 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1037 if (!FormatString)
1038 return;
1039 if (S.FormatStringHasSArg(FormatString)) {
1040 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1041 << "%s" << 1 << 1;
1042 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1043 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001044 }
1045}
1046
Ted Kremenek2bc73332014-01-17 06:24:43 +00001047static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001048 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +00001049 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001050 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001051 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001052 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001053 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001054 if (!NonNull->args_size()) {
1055 // Easy case: all pointer arguments are nonnull.
1056 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +00001057 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +00001058 CheckNonNullArgument(S, Arg, CallSiteLoc);
1059 return;
1060 }
1061
1062 for (unsigned Val : NonNull->args()) {
1063 if (Val >= Args.size())
1064 continue;
1065 if (NonNullArgs.empty())
1066 NonNullArgs.resize(Args.size());
1067 NonNullArgs.set(Val);
1068 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001069 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001070
1071 // Check the attributes on the parameters.
1072 ArrayRef<ParmVarDecl*> parms;
1073 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1074 parms = FD->parameters();
1075 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1076 parms = MD->parameters();
1077
Richard Smith588bd9b2014-08-27 04:59:42 +00001078 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001079 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +00001080 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001081 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +00001082 if (PVD->hasAttr<NonNullAttr>() ||
1083 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1084 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +00001085 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001086
1087 // In case this is a variadic call, check any remaining arguments.
1088 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1089 if (NonNullArgs[ArgIndex])
1090 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +00001091}
1092
Richard Smith55ce3522012-06-25 20:30:08 +00001093/// Handles the checks for format strings, non-POD arguments to vararg
1094/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00001095void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1096 unsigned NumParams, bool IsMemberFunction,
1097 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001098 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001099 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001100 if (CurContext->isDependentContext())
1101 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001102
Ted Kremenekb8176da2010-09-09 04:33:05 +00001103 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001104 llvm::SmallBitVector CheckedVarArgs;
1105 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001106 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001107 // Only create vector if there are format attributes.
1108 CheckedVarArgs.resize(Args.size());
1109
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001110 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001111 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001112 }
Richard Smithd7293d72013-08-05 18:49:43 +00001113 }
Richard Smith55ce3522012-06-25 20:30:08 +00001114
1115 // Refuse POD arguments that weren't caught by the format string
1116 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001117 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001118 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001119 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001120 if (const Expr *Arg = Args[ArgIdx]) {
1121 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1122 checkVariadicArgument(Arg, CallType);
1123 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001124 }
Richard Smithd7293d72013-08-05 18:49:43 +00001125 }
Mike Stump11289f42009-09-09 15:08:12 +00001126
Richard Trieu41bc0992013-06-22 00:20:41 +00001127 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001128 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001129
Richard Trieu41bc0992013-06-22 00:20:41 +00001130 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001131 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1132 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001133 }
Richard Smith55ce3522012-06-25 20:30:08 +00001134}
1135
1136/// CheckConstructorCall - Check a constructor call for correctness and safety
1137/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001138void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1139 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001140 const FunctionProtoType *Proto,
1141 SourceLocation Loc) {
1142 VariadicCallType CallType =
1143 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +00001144 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +00001145 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1146}
1147
1148/// CheckFunctionCall - Check a direct function call for various correctness
1149/// and safety properties not strictly enforced by the C type system.
1150bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1151 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001152 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1153 isa<CXXMethodDecl>(FDecl);
1154 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1155 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001156 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1157 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001158 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +00001159 Expr** Args = TheCall->getArgs();
1160 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001161 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001162 // If this is a call to a member operator, hide the first argument
1163 // from checkCall.
1164 // FIXME: Our choice of AST representation here is less than ideal.
1165 ++Args;
1166 --NumArgs;
1167 }
Craig Topper8c2a2a02014-08-30 16:55:39 +00001168 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +00001169 IsMemberFunction, TheCall->getRParenLoc(),
1170 TheCall->getCallee()->getSourceRange(), CallType);
1171
1172 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1173 // None of the checks below are needed for functions that don't have
1174 // simple names (e.g., C++ conversion functions).
1175 if (!FnInfo)
1176 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001177
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001178 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001179 if (getLangOpts().ObjC1)
1180 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001181
Anna Zaks22122702012-01-17 00:37:07 +00001182 unsigned CMId = FDecl->getMemoryFunctionKind();
1183 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001184 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001185
Anna Zaks201d4892012-01-13 21:52:01 +00001186 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001187 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001188 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001189 else if (CMId == Builtin::BIstrncat)
1190 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001191 else
Anna Zaks22122702012-01-17 00:37:07 +00001192 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001193
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001194 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001195}
1196
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001197bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001198 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001199 VariadicCallType CallType =
1200 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001201
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001202 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001203 /*IsMemberFunction=*/false,
1204 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001205
1206 return false;
1207}
1208
Richard Trieu664c4c62013-06-20 21:03:13 +00001209bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1210 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001211 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1212 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001213 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001214
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001215 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +00001216 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001217 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001218
Richard Trieu664c4c62013-06-20 21:03:13 +00001219 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001220 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001221 CallType = VariadicDoesNotApply;
1222 } else if (Ty->isBlockPointerType()) {
1223 CallType = VariadicBlock;
1224 } else { // Ty->isFunctionPointerType()
1225 CallType = VariadicFunction;
1226 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001227 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001228
Craig Topper8c2a2a02014-08-30 16:55:39 +00001229 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1230 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001231 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001232 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001233
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001234 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001235}
1236
Richard Trieu41bc0992013-06-22 00:20:41 +00001237/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1238/// such as function pointers returned from functions.
1239bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001240 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001241 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001242 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001243
Craig Topperc3ec1492014-05-26 06:22:03 +00001244 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001245 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001246 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001247 TheCall->getCallee()->getSourceRange(), CallType);
1248
1249 return false;
1250}
1251
Tim Northovere94a34c2014-03-11 10:49:14 +00001252static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1253 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1254 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1255 return false;
1256
1257 switch (Op) {
1258 case AtomicExpr::AO__c11_atomic_init:
1259 llvm_unreachable("There is no ordering argument for an init");
1260
1261 case AtomicExpr::AO__c11_atomic_load:
1262 case AtomicExpr::AO__atomic_load_n:
1263 case AtomicExpr::AO__atomic_load:
1264 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1265 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1266
1267 case AtomicExpr::AO__c11_atomic_store:
1268 case AtomicExpr::AO__atomic_store:
1269 case AtomicExpr::AO__atomic_store_n:
1270 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1271 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1272 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1273
1274 default:
1275 return true;
1276 }
1277}
1278
Richard Smithfeea8832012-04-12 05:08:17 +00001279ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1280 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001281 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1282 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001283
Richard Smithfeea8832012-04-12 05:08:17 +00001284 // All these operations take one of the following forms:
1285 enum {
1286 // C __c11_atomic_init(A *, C)
1287 Init,
1288 // C __c11_atomic_load(A *, int)
1289 Load,
1290 // void __atomic_load(A *, CP, int)
1291 Copy,
1292 // C __c11_atomic_add(A *, M, int)
1293 Arithmetic,
1294 // C __atomic_exchange_n(A *, CP, int)
1295 Xchg,
1296 // void __atomic_exchange(A *, C *, CP, int)
1297 GNUXchg,
1298 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1299 C11CmpXchg,
1300 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1301 GNUCmpXchg
1302 } Form = Init;
1303 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1304 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1305 // where:
1306 // C is an appropriate type,
1307 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1308 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1309 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1310 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001311
Richard Smithfeea8832012-04-12 05:08:17 +00001312 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1313 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1314 && "need to update code for modified C11 atomics");
1315 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1316 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1317 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1318 Op == AtomicExpr::AO__atomic_store_n ||
1319 Op == AtomicExpr::AO__atomic_exchange_n ||
1320 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1321 bool IsAddSub = false;
1322
1323 switch (Op) {
1324 case AtomicExpr::AO__c11_atomic_init:
1325 Form = Init;
1326 break;
1327
1328 case AtomicExpr::AO__c11_atomic_load:
1329 case AtomicExpr::AO__atomic_load_n:
1330 Form = Load;
1331 break;
1332
1333 case AtomicExpr::AO__c11_atomic_store:
1334 case AtomicExpr::AO__atomic_load:
1335 case AtomicExpr::AO__atomic_store:
1336 case AtomicExpr::AO__atomic_store_n:
1337 Form = Copy;
1338 break;
1339
1340 case AtomicExpr::AO__c11_atomic_fetch_add:
1341 case AtomicExpr::AO__c11_atomic_fetch_sub:
1342 case AtomicExpr::AO__atomic_fetch_add:
1343 case AtomicExpr::AO__atomic_fetch_sub:
1344 case AtomicExpr::AO__atomic_add_fetch:
1345 case AtomicExpr::AO__atomic_sub_fetch:
1346 IsAddSub = true;
1347 // Fall through.
1348 case AtomicExpr::AO__c11_atomic_fetch_and:
1349 case AtomicExpr::AO__c11_atomic_fetch_or:
1350 case AtomicExpr::AO__c11_atomic_fetch_xor:
1351 case AtomicExpr::AO__atomic_fetch_and:
1352 case AtomicExpr::AO__atomic_fetch_or:
1353 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001354 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001355 case AtomicExpr::AO__atomic_and_fetch:
1356 case AtomicExpr::AO__atomic_or_fetch:
1357 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001358 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001359 Form = Arithmetic;
1360 break;
1361
1362 case AtomicExpr::AO__c11_atomic_exchange:
1363 case AtomicExpr::AO__atomic_exchange_n:
1364 Form = Xchg;
1365 break;
1366
1367 case AtomicExpr::AO__atomic_exchange:
1368 Form = GNUXchg;
1369 break;
1370
1371 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1372 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1373 Form = C11CmpXchg;
1374 break;
1375
1376 case AtomicExpr::AO__atomic_compare_exchange:
1377 case AtomicExpr::AO__atomic_compare_exchange_n:
1378 Form = GNUCmpXchg;
1379 break;
1380 }
1381
1382 // Check we have the right number of arguments.
1383 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001384 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001385 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001386 << TheCall->getCallee()->getSourceRange();
1387 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001388 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1389 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001390 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001391 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001392 << TheCall->getCallee()->getSourceRange();
1393 return ExprError();
1394 }
1395
Richard Smithfeea8832012-04-12 05:08:17 +00001396 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001397 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001398 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1399 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1400 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001401 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001402 << Ptr->getType() << Ptr->getSourceRange();
1403 return ExprError();
1404 }
1405
Richard Smithfeea8832012-04-12 05:08:17 +00001406 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1407 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1408 QualType ValType = AtomTy; // 'C'
1409 if (IsC11) {
1410 if (!AtomTy->isAtomicType()) {
1411 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1412 << Ptr->getType() << Ptr->getSourceRange();
1413 return ExprError();
1414 }
Richard Smithe00921a2012-09-15 06:09:58 +00001415 if (AtomTy.isConstQualified()) {
1416 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1417 << Ptr->getType() << Ptr->getSourceRange();
1418 return ExprError();
1419 }
Richard Smithfeea8832012-04-12 05:08:17 +00001420 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001421 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001422
Richard Smithfeea8832012-04-12 05:08:17 +00001423 // For an arithmetic operation, the implied arithmetic must be well-formed.
1424 if (Form == Arithmetic) {
1425 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1426 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1427 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1428 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1429 return ExprError();
1430 }
1431 if (!IsAddSub && !ValType->isIntegerType()) {
1432 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1433 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1434 return ExprError();
1435 }
David Majnemere85cff82015-01-28 05:48:06 +00001436 if (IsC11 && ValType->isPointerType() &&
1437 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1438 diag::err_incomplete_type)) {
1439 return ExprError();
1440 }
Richard Smithfeea8832012-04-12 05:08:17 +00001441 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1442 // For __atomic_*_n operations, the value type must be a scalar integral or
1443 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001444 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001445 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1446 return ExprError();
1447 }
1448
Eli Friedmanaa769812013-09-11 03:49:34 +00001449 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1450 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001451 // For GNU atomics, require a trivially-copyable type. This is not part of
1452 // the GNU atomics specification, but we enforce it for sanity.
1453 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001454 << Ptr->getType() << Ptr->getSourceRange();
1455 return ExprError();
1456 }
1457
Richard Smithfeea8832012-04-12 05:08:17 +00001458 // FIXME: For any builtin other than a load, the ValType must not be
1459 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001460
1461 switch (ValType.getObjCLifetime()) {
1462 case Qualifiers::OCL_None:
1463 case Qualifiers::OCL_ExplicitNone:
1464 // okay
1465 break;
1466
1467 case Qualifiers::OCL_Weak:
1468 case Qualifiers::OCL_Strong:
1469 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001470 // FIXME: Can this happen? By this point, ValType should be known
1471 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001472 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1473 << ValType << Ptr->getSourceRange();
1474 return ExprError();
1475 }
1476
1477 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001478 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001479 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001480 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001481 ResultType = Context.BoolTy;
1482
Richard Smithfeea8832012-04-12 05:08:17 +00001483 // The type of a parameter passed 'by value'. In the GNU atomics, such
1484 // arguments are actually passed as pointers.
1485 QualType ByValType = ValType; // 'CP'
1486 if (!IsC11 && !IsN)
1487 ByValType = Ptr->getType();
1488
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001489 // The first argument --- the pointer --- has a fixed type; we
1490 // deduce the types of the rest of the arguments accordingly. Walk
1491 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001492 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001493 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001494 if (i < NumVals[Form] + 1) {
1495 switch (i) {
1496 case 1:
1497 // The second argument is the non-atomic operand. For arithmetic, this
1498 // is always passed by value, and for a compare_exchange it is always
1499 // passed by address. For the rest, GNU uses by-address and C11 uses
1500 // by-value.
1501 assert(Form != Load);
1502 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1503 Ty = ValType;
1504 else if (Form == Copy || Form == Xchg)
1505 Ty = ByValType;
1506 else if (Form == Arithmetic)
1507 Ty = Context.getPointerDiffType();
1508 else
1509 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1510 break;
1511 case 2:
1512 // The third argument to compare_exchange / GNU exchange is a
1513 // (pointer to a) desired value.
1514 Ty = ByValType;
1515 break;
1516 case 3:
1517 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1518 Ty = Context.BoolTy;
1519 break;
1520 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001521 } else {
1522 // The order(s) are always converted to int.
1523 Ty = Context.IntTy;
1524 }
Richard Smithfeea8832012-04-12 05:08:17 +00001525
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001526 InitializedEntity Entity =
1527 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001528 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001529 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1530 if (Arg.isInvalid())
1531 return true;
1532 TheCall->setArg(i, Arg.get());
1533 }
1534
Richard Smithfeea8832012-04-12 05:08:17 +00001535 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001536 SmallVector<Expr*, 5> SubExprs;
1537 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001538 switch (Form) {
1539 case Init:
1540 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001541 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001542 break;
1543 case Load:
1544 SubExprs.push_back(TheCall->getArg(1)); // Order
1545 break;
1546 case Copy:
1547 case Arithmetic:
1548 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001549 SubExprs.push_back(TheCall->getArg(2)); // Order
1550 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001551 break;
1552 case GNUXchg:
1553 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1554 SubExprs.push_back(TheCall->getArg(3)); // Order
1555 SubExprs.push_back(TheCall->getArg(1)); // Val1
1556 SubExprs.push_back(TheCall->getArg(2)); // Val2
1557 break;
1558 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001559 SubExprs.push_back(TheCall->getArg(3)); // Order
1560 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001561 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001562 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001563 break;
1564 case GNUCmpXchg:
1565 SubExprs.push_back(TheCall->getArg(4)); // Order
1566 SubExprs.push_back(TheCall->getArg(1)); // Val1
1567 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1568 SubExprs.push_back(TheCall->getArg(2)); // Val2
1569 SubExprs.push_back(TheCall->getArg(3)); // Weak
1570 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001571 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001572
1573 if (SubExprs.size() >= 2 && Form != Init) {
1574 llvm::APSInt Result(32);
1575 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1576 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001577 Diag(SubExprs[1]->getLocStart(),
1578 diag::warn_atomic_op_has_invalid_memory_order)
1579 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001580 }
1581
Fariborz Jahanian615de762013-05-28 17:37:39 +00001582 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1583 SubExprs, ResultType, Op,
1584 TheCall->getRParenLoc());
1585
1586 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1587 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1588 Context.AtomicUsesUnsupportedLibcall(AE))
1589 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1590 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001591
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001592 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001593}
1594
1595
John McCall29ad95b2011-08-27 01:09:30 +00001596/// checkBuiltinArgument - Given a call to a builtin function, perform
1597/// normal type-checking on the given argument, updating the call in
1598/// place. This is useful when a builtin function requires custom
1599/// type-checking for some of its arguments but not necessarily all of
1600/// them.
1601///
1602/// Returns true on error.
1603static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1604 FunctionDecl *Fn = E->getDirectCallee();
1605 assert(Fn && "builtin call without direct callee!");
1606
1607 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1608 InitializedEntity Entity =
1609 InitializedEntity::InitializeParameter(S.Context, Param);
1610
1611 ExprResult Arg = E->getArg(0);
1612 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1613 if (Arg.isInvalid())
1614 return true;
1615
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001616 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001617 return false;
1618}
1619
Chris Lattnerdc046542009-05-08 06:58:22 +00001620/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1621/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1622/// type of its first argument. The main ActOnCallExpr routines have already
1623/// promoted the types of arguments because all of these calls are prototyped as
1624/// void(...).
1625///
1626/// This function goes through and does final semantic checking for these
1627/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001628ExprResult
1629Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001630 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001631 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1632 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1633
1634 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001635 if (TheCall->getNumArgs() < 1) {
1636 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1637 << 0 << 1 << TheCall->getNumArgs()
1638 << TheCall->getCallee()->getSourceRange();
1639 return ExprError();
1640 }
Mike Stump11289f42009-09-09 15:08:12 +00001641
Chris Lattnerdc046542009-05-08 06:58:22 +00001642 // Inspect the first argument of the atomic builtin. This should always be
1643 // a pointer type, whose element is an integral scalar or pointer type.
1644 // Because it is a pointer type, we don't have to worry about any implicit
1645 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001646 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001647 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001648 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1649 if (FirstArgResult.isInvalid())
1650 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001651 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001652 TheCall->setArg(0, FirstArg);
1653
John McCall31168b02011-06-15 23:02:42 +00001654 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1655 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001656 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1657 << FirstArg->getType() << FirstArg->getSourceRange();
1658 return ExprError();
1659 }
Mike Stump11289f42009-09-09 15:08:12 +00001660
John McCall31168b02011-06-15 23:02:42 +00001661 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001662 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001663 !ValType->isBlockPointerType()) {
1664 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1665 << FirstArg->getType() << FirstArg->getSourceRange();
1666 return ExprError();
1667 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001668
John McCall31168b02011-06-15 23:02:42 +00001669 switch (ValType.getObjCLifetime()) {
1670 case Qualifiers::OCL_None:
1671 case Qualifiers::OCL_ExplicitNone:
1672 // okay
1673 break;
1674
1675 case Qualifiers::OCL_Weak:
1676 case Qualifiers::OCL_Strong:
1677 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001678 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001679 << ValType << FirstArg->getSourceRange();
1680 return ExprError();
1681 }
1682
John McCallb50451a2011-10-05 07:41:44 +00001683 // Strip any qualifiers off ValType.
1684 ValType = ValType.getUnqualifiedType();
1685
Chandler Carruth3973af72010-07-18 20:54:12 +00001686 // The majority of builtins return a value, but a few have special return
1687 // types, so allow them to override appropriately below.
1688 QualType ResultType = ValType;
1689
Chris Lattnerdc046542009-05-08 06:58:22 +00001690 // We need to figure out which concrete builtin this maps onto. For example,
1691 // __sync_fetch_and_add with a 2 byte object turns into
1692 // __sync_fetch_and_add_2.
1693#define BUILTIN_ROW(x) \
1694 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1695 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001696
Chris Lattnerdc046542009-05-08 06:58:22 +00001697 static const unsigned BuiltinIndices[][5] = {
1698 BUILTIN_ROW(__sync_fetch_and_add),
1699 BUILTIN_ROW(__sync_fetch_and_sub),
1700 BUILTIN_ROW(__sync_fetch_and_or),
1701 BUILTIN_ROW(__sync_fetch_and_and),
1702 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001703 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001704
Chris Lattnerdc046542009-05-08 06:58:22 +00001705 BUILTIN_ROW(__sync_add_and_fetch),
1706 BUILTIN_ROW(__sync_sub_and_fetch),
1707 BUILTIN_ROW(__sync_and_and_fetch),
1708 BUILTIN_ROW(__sync_or_and_fetch),
1709 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001710 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001711
Chris Lattnerdc046542009-05-08 06:58:22 +00001712 BUILTIN_ROW(__sync_val_compare_and_swap),
1713 BUILTIN_ROW(__sync_bool_compare_and_swap),
1714 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001715 BUILTIN_ROW(__sync_lock_release),
1716 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001717 };
Mike Stump11289f42009-09-09 15:08:12 +00001718#undef BUILTIN_ROW
1719
Chris Lattnerdc046542009-05-08 06:58:22 +00001720 // Determine the index of the size.
1721 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001722 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001723 case 1: SizeIndex = 0; break;
1724 case 2: SizeIndex = 1; break;
1725 case 4: SizeIndex = 2; break;
1726 case 8: SizeIndex = 3; break;
1727 case 16: SizeIndex = 4; break;
1728 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001729 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1730 << FirstArg->getType() << FirstArg->getSourceRange();
1731 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001732 }
Mike Stump11289f42009-09-09 15:08:12 +00001733
Chris Lattnerdc046542009-05-08 06:58:22 +00001734 // Each of these builtins has one pointer argument, followed by some number of
1735 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1736 // that we ignore. Find out which row of BuiltinIndices to read from as well
1737 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001738 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001739 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001740 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001741 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001742 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001743 case Builtin::BI__sync_fetch_and_add:
1744 case Builtin::BI__sync_fetch_and_add_1:
1745 case Builtin::BI__sync_fetch_and_add_2:
1746 case Builtin::BI__sync_fetch_and_add_4:
1747 case Builtin::BI__sync_fetch_and_add_8:
1748 case Builtin::BI__sync_fetch_and_add_16:
1749 BuiltinIndex = 0;
1750 break;
1751
1752 case Builtin::BI__sync_fetch_and_sub:
1753 case Builtin::BI__sync_fetch_and_sub_1:
1754 case Builtin::BI__sync_fetch_and_sub_2:
1755 case Builtin::BI__sync_fetch_and_sub_4:
1756 case Builtin::BI__sync_fetch_and_sub_8:
1757 case Builtin::BI__sync_fetch_and_sub_16:
1758 BuiltinIndex = 1;
1759 break;
1760
1761 case Builtin::BI__sync_fetch_and_or:
1762 case Builtin::BI__sync_fetch_and_or_1:
1763 case Builtin::BI__sync_fetch_and_or_2:
1764 case Builtin::BI__sync_fetch_and_or_4:
1765 case Builtin::BI__sync_fetch_and_or_8:
1766 case Builtin::BI__sync_fetch_and_or_16:
1767 BuiltinIndex = 2;
1768 break;
1769
1770 case Builtin::BI__sync_fetch_and_and:
1771 case Builtin::BI__sync_fetch_and_and_1:
1772 case Builtin::BI__sync_fetch_and_and_2:
1773 case Builtin::BI__sync_fetch_and_and_4:
1774 case Builtin::BI__sync_fetch_and_and_8:
1775 case Builtin::BI__sync_fetch_and_and_16:
1776 BuiltinIndex = 3;
1777 break;
Mike Stump11289f42009-09-09 15:08:12 +00001778
Douglas Gregor73722482011-11-28 16:30:08 +00001779 case Builtin::BI__sync_fetch_and_xor:
1780 case Builtin::BI__sync_fetch_and_xor_1:
1781 case Builtin::BI__sync_fetch_and_xor_2:
1782 case Builtin::BI__sync_fetch_and_xor_4:
1783 case Builtin::BI__sync_fetch_and_xor_8:
1784 case Builtin::BI__sync_fetch_and_xor_16:
1785 BuiltinIndex = 4;
1786 break;
1787
Hal Finkeld2208b52014-10-02 20:53:50 +00001788 case Builtin::BI__sync_fetch_and_nand:
1789 case Builtin::BI__sync_fetch_and_nand_1:
1790 case Builtin::BI__sync_fetch_and_nand_2:
1791 case Builtin::BI__sync_fetch_and_nand_4:
1792 case Builtin::BI__sync_fetch_and_nand_8:
1793 case Builtin::BI__sync_fetch_and_nand_16:
1794 BuiltinIndex = 5;
1795 WarnAboutSemanticsChange = true;
1796 break;
1797
Douglas Gregor73722482011-11-28 16:30:08 +00001798 case Builtin::BI__sync_add_and_fetch:
1799 case Builtin::BI__sync_add_and_fetch_1:
1800 case Builtin::BI__sync_add_and_fetch_2:
1801 case Builtin::BI__sync_add_and_fetch_4:
1802 case Builtin::BI__sync_add_and_fetch_8:
1803 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001804 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00001805 break;
1806
1807 case Builtin::BI__sync_sub_and_fetch:
1808 case Builtin::BI__sync_sub_and_fetch_1:
1809 case Builtin::BI__sync_sub_and_fetch_2:
1810 case Builtin::BI__sync_sub_and_fetch_4:
1811 case Builtin::BI__sync_sub_and_fetch_8:
1812 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001813 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00001814 break;
1815
1816 case Builtin::BI__sync_and_and_fetch:
1817 case Builtin::BI__sync_and_and_fetch_1:
1818 case Builtin::BI__sync_and_and_fetch_2:
1819 case Builtin::BI__sync_and_and_fetch_4:
1820 case Builtin::BI__sync_and_and_fetch_8:
1821 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001822 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00001823 break;
1824
1825 case Builtin::BI__sync_or_and_fetch:
1826 case Builtin::BI__sync_or_and_fetch_1:
1827 case Builtin::BI__sync_or_and_fetch_2:
1828 case Builtin::BI__sync_or_and_fetch_4:
1829 case Builtin::BI__sync_or_and_fetch_8:
1830 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001831 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00001832 break;
1833
1834 case Builtin::BI__sync_xor_and_fetch:
1835 case Builtin::BI__sync_xor_and_fetch_1:
1836 case Builtin::BI__sync_xor_and_fetch_2:
1837 case Builtin::BI__sync_xor_and_fetch_4:
1838 case Builtin::BI__sync_xor_and_fetch_8:
1839 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001840 BuiltinIndex = 10;
1841 break;
1842
1843 case Builtin::BI__sync_nand_and_fetch:
1844 case Builtin::BI__sync_nand_and_fetch_1:
1845 case Builtin::BI__sync_nand_and_fetch_2:
1846 case Builtin::BI__sync_nand_and_fetch_4:
1847 case Builtin::BI__sync_nand_and_fetch_8:
1848 case Builtin::BI__sync_nand_and_fetch_16:
1849 BuiltinIndex = 11;
1850 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00001851 break;
Mike Stump11289f42009-09-09 15:08:12 +00001852
Chris Lattnerdc046542009-05-08 06:58:22 +00001853 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001854 case Builtin::BI__sync_val_compare_and_swap_1:
1855 case Builtin::BI__sync_val_compare_and_swap_2:
1856 case Builtin::BI__sync_val_compare_and_swap_4:
1857 case Builtin::BI__sync_val_compare_and_swap_8:
1858 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001859 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00001860 NumFixed = 2;
1861 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001862
Chris Lattnerdc046542009-05-08 06:58:22 +00001863 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001864 case Builtin::BI__sync_bool_compare_and_swap_1:
1865 case Builtin::BI__sync_bool_compare_and_swap_2:
1866 case Builtin::BI__sync_bool_compare_and_swap_4:
1867 case Builtin::BI__sync_bool_compare_and_swap_8:
1868 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001869 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001870 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001871 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001872 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001873
1874 case Builtin::BI__sync_lock_test_and_set:
1875 case Builtin::BI__sync_lock_test_and_set_1:
1876 case Builtin::BI__sync_lock_test_and_set_2:
1877 case Builtin::BI__sync_lock_test_and_set_4:
1878 case Builtin::BI__sync_lock_test_and_set_8:
1879 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001880 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00001881 break;
1882
Chris Lattnerdc046542009-05-08 06:58:22 +00001883 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001884 case Builtin::BI__sync_lock_release_1:
1885 case Builtin::BI__sync_lock_release_2:
1886 case Builtin::BI__sync_lock_release_4:
1887 case Builtin::BI__sync_lock_release_8:
1888 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001889 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00001890 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001891 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001892 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001893
1894 case Builtin::BI__sync_swap:
1895 case Builtin::BI__sync_swap_1:
1896 case Builtin::BI__sync_swap_2:
1897 case Builtin::BI__sync_swap_4:
1898 case Builtin::BI__sync_swap_8:
1899 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001900 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00001901 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001902 }
Mike Stump11289f42009-09-09 15:08:12 +00001903
Chris Lattnerdc046542009-05-08 06:58:22 +00001904 // Now that we know how many fixed arguments we expect, first check that we
1905 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001906 if (TheCall->getNumArgs() < 1+NumFixed) {
1907 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1908 << 0 << 1+NumFixed << TheCall->getNumArgs()
1909 << TheCall->getCallee()->getSourceRange();
1910 return ExprError();
1911 }
Mike Stump11289f42009-09-09 15:08:12 +00001912
Hal Finkeld2208b52014-10-02 20:53:50 +00001913 if (WarnAboutSemanticsChange) {
1914 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1915 << TheCall->getCallee()->getSourceRange();
1916 }
1917
Chris Lattner5b9241b2009-05-08 15:36:58 +00001918 // Get the decl for the concrete builtin from this, we can tell what the
1919 // concrete integer type we should convert to is.
1920 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1921 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001922 FunctionDecl *NewBuiltinDecl;
1923 if (NewBuiltinID == BuiltinID)
1924 NewBuiltinDecl = FDecl;
1925 else {
1926 // Perform builtin lookup to avoid redeclaring it.
1927 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1928 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1929 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1930 assert(Res.getFoundDecl());
1931 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001932 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001933 return ExprError();
1934 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001935
John McCallcf142162010-08-07 06:22:56 +00001936 // The first argument --- the pointer --- has a fixed type; we
1937 // deduce the types of the rest of the arguments accordingly. Walk
1938 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001939 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001940 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001941
Chris Lattnerdc046542009-05-08 06:58:22 +00001942 // GCC does an implicit conversion to the pointer or integer ValType. This
1943 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001944 // Initialize the argument.
1945 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1946 ValType, /*consume*/ false);
1947 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001948 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001949 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001950
Chris Lattnerdc046542009-05-08 06:58:22 +00001951 // Okay, we have something that *can* be converted to the right type. Check
1952 // to see if there is a potentially weird extension going on here. This can
1953 // happen when you do an atomic operation on something like an char* and
1954 // pass in 42. The 42 gets converted to char. This is even more strange
1955 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001956 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001957 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001958 }
Mike Stump11289f42009-09-09 15:08:12 +00001959
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001960 ASTContext& Context = this->getASTContext();
1961
1962 // Create a new DeclRefExpr to refer to the new decl.
1963 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1964 Context,
1965 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001966 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001967 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001968 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001969 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001970 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001971 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001972
Chris Lattnerdc046542009-05-08 06:58:22 +00001973 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001974 // FIXME: This loses syntactic information.
1975 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1976 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1977 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001978 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001979
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001980 // Change the result type of the call to match the original value type. This
1981 // is arbitrary, but the codegen for these builtins ins design to handle it
1982 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001983 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001984
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001985 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001986}
1987
Chris Lattner6436fb62009-02-18 06:01:06 +00001988/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001989/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001990/// Note: It might also make sense to do the UTF-16 conversion here (would
1991/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001992bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001993 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001994 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1995
Douglas Gregorfb65e592011-07-27 05:40:30 +00001996 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001997 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1998 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001999 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002000 }
Mike Stump11289f42009-09-09 15:08:12 +00002001
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002002 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002003 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002004 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002005 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002006 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002007 UTF16 *ToPtr = &ToBuf[0];
2008
2009 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2010 &ToPtr, ToPtr + NumBytes,
2011 strictConversion);
2012 // Check for conversion failure.
2013 if (Result != conversionOK)
2014 Diag(Arg->getLocStart(),
2015 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2016 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002017 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002018}
2019
Chris Lattnere202e6a2007-12-20 00:05:45 +00002020/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2021/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00002022bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2023 Expr *Fn = TheCall->getCallee();
2024 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002025 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002026 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002027 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2028 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002029 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002030 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002031 return true;
2032 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002033
2034 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002035 return Diag(TheCall->getLocEnd(),
2036 diag::err_typecheck_call_too_few_args_at_least)
2037 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002038 }
2039
John McCall29ad95b2011-08-27 01:09:30 +00002040 // Type-check the first argument normally.
2041 if (checkBuiltinArgument(*this, TheCall, 0))
2042 return true;
2043
Chris Lattnere202e6a2007-12-20 00:05:45 +00002044 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002045 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002046 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002047 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002048 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002049 else if (FunctionDecl *FD = getCurFunctionDecl())
2050 isVariadic = FD->isVariadic();
2051 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002052 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002053
Chris Lattnere202e6a2007-12-20 00:05:45 +00002054 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002055 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2056 return true;
2057 }
Mike Stump11289f42009-09-09 15:08:12 +00002058
Chris Lattner43be2e62007-12-19 23:59:04 +00002059 // Verify that the second argument to the builtin is the last argument of the
2060 // current function or method.
2061 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002062 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002063
Nico Weber9eea7642013-05-24 23:31:57 +00002064 // These are valid if SecondArgIsLastNamedArgument is false after the next
2065 // block.
2066 QualType Type;
2067 SourceLocation ParamLoc;
2068
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002069 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2070 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002071 // FIXME: This isn't correct for methods (results in bogus warning).
2072 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002073 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002074 if (CurBlock)
2075 LastArg = *(CurBlock->TheDecl->param_end()-1);
2076 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002077 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002078 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002079 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002080 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002081
2082 Type = PV->getType();
2083 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002084 }
2085 }
Mike Stump11289f42009-09-09 15:08:12 +00002086
Chris Lattner43be2e62007-12-19 23:59:04 +00002087 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002088 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002089 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002090 else if (Type->isReferenceType()) {
2091 Diag(Arg->getLocStart(),
2092 diag::warn_va_start_of_reference_type_is_undefined);
2093 Diag(ParamLoc, diag::note_parameter_type) << Type;
2094 }
2095
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002096 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002097 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002098}
Chris Lattner43be2e62007-12-19 23:59:04 +00002099
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002100bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2101 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2102 // const char *named_addr);
2103
2104 Expr *Func = Call->getCallee();
2105
2106 if (Call->getNumArgs() < 3)
2107 return Diag(Call->getLocEnd(),
2108 diag::err_typecheck_call_too_few_args_at_least)
2109 << 0 /*function call*/ << 3 << Call->getNumArgs();
2110
2111 // Determine whether the current function is variadic or not.
2112 bool IsVariadic;
2113 if (BlockScopeInfo *CurBlock = getCurBlock())
2114 IsVariadic = CurBlock->TheDecl->isVariadic();
2115 else if (FunctionDecl *FD = getCurFunctionDecl())
2116 IsVariadic = FD->isVariadic();
2117 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2118 IsVariadic = MD->isVariadic();
2119 else
2120 llvm_unreachable("unexpected statement type");
2121
2122 if (!IsVariadic) {
2123 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2124 return true;
2125 }
2126
2127 // Type-check the first argument normally.
2128 if (checkBuiltinArgument(*this, Call, 0))
2129 return true;
2130
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002131 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002132 unsigned ArgNo;
2133 QualType Type;
2134 } ArgumentTypes[] = {
2135 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2136 { 2, Context.getSizeType() },
2137 };
2138
2139 for (const auto &AT : ArgumentTypes) {
2140 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2141 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2142 continue;
2143 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2144 << Arg->getType() << AT.Type << 1 /* different class */
2145 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2146 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2147 }
2148
2149 return false;
2150}
2151
Chris Lattner2da14fb2007-12-20 00:26:33 +00002152/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2153/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002154bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2155 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002156 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002157 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002158 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002159 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002160 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002161 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002162 << SourceRange(TheCall->getArg(2)->getLocStart(),
2163 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002164
John Wiegley01296292011-04-08 18:41:53 +00002165 ExprResult OrigArg0 = TheCall->getArg(0);
2166 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002167
Chris Lattner2da14fb2007-12-20 00:26:33 +00002168 // Do standard promotions between the two arguments, returning their common
2169 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002170 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002171 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2172 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002173
2174 // Make sure any conversions are pushed back into the call; this is
2175 // type safe since unordered compare builtins are declared as "_Bool
2176 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002177 TheCall->setArg(0, OrigArg0.get());
2178 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002179
John Wiegley01296292011-04-08 18:41:53 +00002180 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002181 return false;
2182
Chris Lattner2da14fb2007-12-20 00:26:33 +00002183 // If the common type isn't a real floating type, then the arguments were
2184 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002185 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002186 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002187 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002188 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2189 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002190
Chris Lattner2da14fb2007-12-20 00:26:33 +00002191 return false;
2192}
2193
Benjamin Kramer634fc102010-02-15 22:42:31 +00002194/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2195/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002196/// to check everything. We expect the last argument to be a floating point
2197/// value.
2198bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2199 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002200 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002201 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002202 if (TheCall->getNumArgs() > NumArgs)
2203 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002204 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002205 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002206 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002207 (*(TheCall->arg_end()-1))->getLocEnd());
2208
Benjamin Kramer64aae502010-02-16 10:07:31 +00002209 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002210
Eli Friedman7e4faac2009-08-31 20:06:00 +00002211 if (OrigArg->isTypeDependent())
2212 return false;
2213
Chris Lattner68784ef2010-05-06 05:50:07 +00002214 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002215 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002216 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002217 diag::err_typecheck_call_invalid_unary_fp)
2218 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002219
Chris Lattner68784ef2010-05-06 05:50:07 +00002220 // If this is an implicit conversion from float -> double, remove it.
2221 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2222 Expr *CastArg = Cast->getSubExpr();
2223 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2224 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2225 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002226 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002227 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002228 }
2229 }
2230
Eli Friedman7e4faac2009-08-31 20:06:00 +00002231 return false;
2232}
2233
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002234/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2235// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002236ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002237 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002238 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002239 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002240 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2241 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002242
Nate Begemana0110022010-06-08 00:16:34 +00002243 // Determine which of the following types of shufflevector we're checking:
2244 // 1) unary, vector mask: (lhs, mask)
2245 // 2) binary, vector mask: (lhs, rhs, mask)
2246 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2247 QualType resType = TheCall->getArg(0)->getType();
2248 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002249
Douglas Gregorc25f7662009-05-19 22:10:17 +00002250 if (!TheCall->getArg(0)->isTypeDependent() &&
2251 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002252 QualType LHSType = TheCall->getArg(0)->getType();
2253 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002254
Craig Topperbaca3892013-07-29 06:47:04 +00002255 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2256 return ExprError(Diag(TheCall->getLocStart(),
2257 diag::err_shufflevector_non_vector)
2258 << SourceRange(TheCall->getArg(0)->getLocStart(),
2259 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002260
Nate Begemana0110022010-06-08 00:16:34 +00002261 numElements = LHSType->getAs<VectorType>()->getNumElements();
2262 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002263
Nate Begemana0110022010-06-08 00:16:34 +00002264 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2265 // with mask. If so, verify that RHS is an integer vector type with the
2266 // same number of elts as lhs.
2267 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002268 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002269 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002270 return ExprError(Diag(TheCall->getLocStart(),
2271 diag::err_shufflevector_incompatible_vector)
2272 << SourceRange(TheCall->getArg(1)->getLocStart(),
2273 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002274 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002275 return ExprError(Diag(TheCall->getLocStart(),
2276 diag::err_shufflevector_incompatible_vector)
2277 << SourceRange(TheCall->getArg(0)->getLocStart(),
2278 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002279 } else if (numElements != numResElements) {
2280 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002281 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002282 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002283 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002284 }
2285
2286 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002287 if (TheCall->getArg(i)->isTypeDependent() ||
2288 TheCall->getArg(i)->isValueDependent())
2289 continue;
2290
Nate Begemana0110022010-06-08 00:16:34 +00002291 llvm::APSInt Result(32);
2292 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2293 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002294 diag::err_shufflevector_nonconstant_argument)
2295 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002296
Craig Topper50ad5b72013-08-03 17:40:38 +00002297 // Allow -1 which will be translated to undef in the IR.
2298 if (Result.isSigned() && Result.isAllOnesValue())
2299 continue;
2300
Chris Lattner7ab824e2008-08-10 02:05:13 +00002301 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002302 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002303 diag::err_shufflevector_argument_too_large)
2304 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002305 }
2306
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002307 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002308
Chris Lattner7ab824e2008-08-10 02:05:13 +00002309 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002310 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002311 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002312 }
2313
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002314 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2315 TheCall->getCallee()->getLocStart(),
2316 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002317}
Chris Lattner43be2e62007-12-19 23:59:04 +00002318
Hal Finkelc4d7c822013-09-18 03:29:45 +00002319/// SemaConvertVectorExpr - Handle __builtin_convertvector
2320ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2321 SourceLocation BuiltinLoc,
2322 SourceLocation RParenLoc) {
2323 ExprValueKind VK = VK_RValue;
2324 ExprObjectKind OK = OK_Ordinary;
2325 QualType DstTy = TInfo->getType();
2326 QualType SrcTy = E->getType();
2327
2328 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2329 return ExprError(Diag(BuiltinLoc,
2330 diag::err_convertvector_non_vector)
2331 << E->getSourceRange());
2332 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2333 return ExprError(Diag(BuiltinLoc,
2334 diag::err_convertvector_non_vector_type));
2335
2336 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2337 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2338 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2339 if (SrcElts != DstElts)
2340 return ExprError(Diag(BuiltinLoc,
2341 diag::err_convertvector_incompatible_vector)
2342 << E->getSourceRange());
2343 }
2344
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002345 return new (Context)
2346 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002347}
2348
Daniel Dunbarb7257262008-07-21 22:59:13 +00002349/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2350// This is declared to take (const void*, ...) and can take two
2351// optional constant int args.
2352bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002353 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002354
Chris Lattner3b054132008-11-19 05:08:23 +00002355 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002356 return Diag(TheCall->getLocEnd(),
2357 diag::err_typecheck_call_too_many_args_at_most)
2358 << 0 /*function call*/ << 3 << NumArgs
2359 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002360
2361 // Argument 0 is checked for us and the remaining arguments must be
2362 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002363 for (unsigned i = 1; i != NumArgs; ++i)
2364 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002365 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002366
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002367 return false;
2368}
2369
Hal Finkelf0417332014-07-17 14:25:55 +00002370/// SemaBuiltinAssume - Handle __assume (MS Extension).
2371// __assume does not evaluate its arguments, and should warn if its argument
2372// has side effects.
2373bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2374 Expr *Arg = TheCall->getArg(0);
2375 if (Arg->isInstantiationDependent()) return false;
2376
2377 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002378 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002379 << Arg->getSourceRange()
2380 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2381
2382 return false;
2383}
2384
2385/// Handle __builtin_assume_aligned. This is declared
2386/// as (const void*, size_t, ...) and can take one optional constant int arg.
2387bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2388 unsigned NumArgs = TheCall->getNumArgs();
2389
2390 if (NumArgs > 3)
2391 return Diag(TheCall->getLocEnd(),
2392 diag::err_typecheck_call_too_many_args_at_most)
2393 << 0 /*function call*/ << 3 << NumArgs
2394 << TheCall->getSourceRange();
2395
2396 // The alignment must be a constant integer.
2397 Expr *Arg = TheCall->getArg(1);
2398
2399 // We can't check the value of a dependent argument.
2400 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2401 llvm::APSInt Result;
2402 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2403 return true;
2404
2405 if (!Result.isPowerOf2())
2406 return Diag(TheCall->getLocStart(),
2407 diag::err_alignment_not_power_of_two)
2408 << Arg->getSourceRange();
2409 }
2410
2411 if (NumArgs > 2) {
2412 ExprResult Arg(TheCall->getArg(2));
2413 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2414 Context.getSizeType(), false);
2415 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2416 if (Arg.isInvalid()) return true;
2417 TheCall->setArg(2, Arg.get());
2418 }
Hal Finkelf0417332014-07-17 14:25:55 +00002419
2420 return false;
2421}
2422
Eric Christopher8d0c6212010-04-17 02:26:23 +00002423/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2424/// TheCall is a constant expression.
2425bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2426 llvm::APSInt &Result) {
2427 Expr *Arg = TheCall->getArg(ArgNum);
2428 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2429 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2430
2431 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2432
2433 if (!Arg->isIntegerConstantExpr(Result, Context))
2434 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002435 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002436
Chris Lattnerd545ad12009-09-23 06:06:36 +00002437 return false;
2438}
2439
Richard Sandiford28940af2014-04-16 08:47:51 +00002440/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2441/// TheCall is a constant expression in the range [Low, High].
2442bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2443 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002444 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002445
2446 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002447 Expr *Arg = TheCall->getArg(ArgNum);
2448 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002449 return false;
2450
Eric Christopher8d0c6212010-04-17 02:26:23 +00002451 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002452 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002453 return true;
2454
Richard Sandiford28940af2014-04-16 08:47:51 +00002455 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002456 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002457 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002458
2459 return false;
2460}
2461
Eli Friedmanc97d0142009-05-03 06:04:26 +00002462/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002463/// This checks that val is a constant 1.
2464bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2465 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002466 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002467
Eric Christopher8d0c6212010-04-17 02:26:23 +00002468 // TODO: This is less than ideal. Overload this to take a value.
2469 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2470 return true;
2471
2472 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002473 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2474 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2475
2476 return false;
2477}
2478
Richard Smithd7293d72013-08-05 18:49:43 +00002479namespace {
2480enum StringLiteralCheckType {
2481 SLCT_NotALiteral,
2482 SLCT_UncheckedLiteral,
2483 SLCT_CheckedLiteral
2484};
2485}
2486
Richard Smith55ce3522012-06-25 20:30:08 +00002487// Determine if an expression is a string literal or constant string.
2488// If this function returns false on the arguments to a function expecting a
2489// format string, we will usually need to emit a warning.
2490// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002491static StringLiteralCheckType
2492checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2493 bool HasVAListArg, unsigned format_idx,
2494 unsigned firstDataArg, Sema::FormatStringType Type,
2495 Sema::VariadicCallType CallType, bool InFunctionCall,
2496 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002497 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002498 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002499 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002500
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002501 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002502
Richard Smithd7293d72013-08-05 18:49:43 +00002503 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002504 // Technically -Wformat-nonliteral does not warn about this case.
2505 // The behavior of printf and friends in this case is implementation
2506 // dependent. Ideally if the format string cannot be null then
2507 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002508 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002509
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002510 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002511 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002512 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002513 // The expression is a literal if both sub-expressions were, and it was
2514 // completely checked only if both sub-expressions were checked.
2515 const AbstractConditionalOperator *C =
2516 cast<AbstractConditionalOperator>(E);
2517 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002518 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002519 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002520 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002521 if (Left == SLCT_NotALiteral)
2522 return SLCT_NotALiteral;
2523 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002524 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002525 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002526 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002527 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002528 }
2529
2530 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002531 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2532 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002533 }
2534
John McCallc07a0c72011-02-17 10:25:35 +00002535 case Stmt::OpaqueValueExprClass:
2536 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2537 E = src;
2538 goto tryAgain;
2539 }
Richard Smith55ce3522012-06-25 20:30:08 +00002540 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002541
Ted Kremeneka8890832011-02-24 23:03:04 +00002542 case Stmt::PredefinedExprClass:
2543 // While __func__, etc., are technically not string literals, they
2544 // cannot contain format specifiers and thus are not a security
2545 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002546 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002547
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002548 case Stmt::DeclRefExprClass: {
2549 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002550
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002551 // As an exception, do not flag errors for variables binding to
2552 // const string literals.
2553 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2554 bool isConstant = false;
2555 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002556
Richard Smithd7293d72013-08-05 18:49:43 +00002557 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2558 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002559 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002560 isConstant = T.isConstant(S.Context) &&
2561 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002562 } else if (T->isObjCObjectPointerType()) {
2563 // In ObjC, there is usually no "const ObjectPointer" type,
2564 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002565 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002566 }
Mike Stump11289f42009-09-09 15:08:12 +00002567
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002568 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002569 if (const Expr *Init = VD->getAnyInitializer()) {
2570 // Look through initializers like const char c[] = { "foo" }
2571 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2572 if (InitList->isStringLiteralInit())
2573 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2574 }
Richard Smithd7293d72013-08-05 18:49:43 +00002575 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002576 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002577 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002578 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002579 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002580 }
Mike Stump11289f42009-09-09 15:08:12 +00002581
Anders Carlssonb012ca92009-06-28 19:55:58 +00002582 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2583 // special check to see if the format string is a function parameter
2584 // of the function calling the printf function. If the function
2585 // has an attribute indicating it is a printf-like function, then we
2586 // should suppress warnings concerning non-literals being used in a call
2587 // to a vprintf function. For example:
2588 //
2589 // void
2590 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2591 // va_list ap;
2592 // va_start(ap, fmt);
2593 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2594 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002595 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002596 if (HasVAListArg) {
2597 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2598 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2599 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002600 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002601 // adjust for implicit parameter
2602 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2603 if (MD->isInstance())
2604 ++PVIndex;
2605 // We also check if the formats are compatible.
2606 // We can't pass a 'scanf' string to a 'printf' function.
2607 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002608 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002609 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002610 }
2611 }
2612 }
2613 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002614 }
Mike Stump11289f42009-09-09 15:08:12 +00002615
Richard Smith55ce3522012-06-25 20:30:08 +00002616 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002617 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002618
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002619 case Stmt::CallExprClass:
2620 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002621 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002622 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2623 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2624 unsigned ArgIndex = FA->getFormatIdx();
2625 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2626 if (MD->isInstance())
2627 --ArgIndex;
2628 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002629
Richard Smithd7293d72013-08-05 18:49:43 +00002630 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002631 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002632 Type, CallType, InFunctionCall,
2633 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002634 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2635 unsigned BuiltinID = FD->getBuiltinID();
2636 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2637 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2638 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002639 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002640 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002641 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002642 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002643 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002644 }
2645 }
Mike Stump11289f42009-09-09 15:08:12 +00002646
Richard Smith55ce3522012-06-25 20:30:08 +00002647 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002648 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002649 case Stmt::ObjCStringLiteralClass:
2650 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002651 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002652
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002653 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002654 StrE = ObjCFExpr->getString();
2655 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002656 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002657
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002658 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002659 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2660 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002661 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002662 }
Mike Stump11289f42009-09-09 15:08:12 +00002663
Richard Smith55ce3522012-06-25 20:30:08 +00002664 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002665 }
Mike Stump11289f42009-09-09 15:08:12 +00002666
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002667 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002668 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002669 }
2670}
2671
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002672Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002673 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002674 .Case("scanf", FST_Scanf)
2675 .Cases("printf", "printf0", FST_Printf)
2676 .Cases("NSString", "CFString", FST_NSString)
2677 .Case("strftime", FST_Strftime)
2678 .Case("strfmon", FST_Strfmon)
2679 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00002680 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00002681 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002682 .Default(FST_Unknown);
2683}
2684
Jordan Rose3e0ec582012-07-19 18:10:23 +00002685/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002686/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002687/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002688bool Sema::CheckFormatArguments(const FormatAttr *Format,
2689 ArrayRef<const Expr *> Args,
2690 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002691 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002692 SourceLocation Loc, SourceRange Range,
2693 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002694 FormatStringInfo FSI;
2695 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002696 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002697 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002698 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002699 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002700}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002701
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002702bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002703 bool HasVAListArg, unsigned format_idx,
2704 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002705 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002706 SourceLocation Loc, SourceRange Range,
2707 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002708 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002709 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002710 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002711 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002712 }
Mike Stump11289f42009-09-09 15:08:12 +00002713
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002714 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002715
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002716 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002717 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002718 // Dynamically generated format strings are difficult to
2719 // automatically vet at compile time. Requiring that format strings
2720 // are string literals: (1) permits the checking of format strings by
2721 // the compiler and thereby (2) can practically remove the source of
2722 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002723
Mike Stump11289f42009-09-09 15:08:12 +00002724 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002725 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002726 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002727 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002728 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002729 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2730 format_idx, firstDataArg, Type, CallType,
2731 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002732 if (CT != SLCT_NotALiteral)
2733 // Literal format string found, check done!
2734 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002735
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002736 // Strftime is particular as it always uses a single 'time' argument,
2737 // so it is safe to pass a non-literal string.
2738 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002739 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002740
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002741 // Do not emit diag when the string param is a macro expansion and the
2742 // format is either NSString or CFString. This is a hack to prevent
2743 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2744 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002745 if (Type == FST_NSString &&
2746 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002747 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002748
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002749 // If there are no arguments specified, warn with -Wformat-security, otherwise
2750 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002751 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002752 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002753 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002754 << OrigFormatExpr->getSourceRange();
2755 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002756 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002757 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002758 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002759 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002760}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002761
Ted Kremenekab278de2010-01-28 23:39:18 +00002762namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002763class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2764protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002765 Sema &S;
2766 const StringLiteral *FExpr;
2767 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002768 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002769 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002770 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002771 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002772 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002773 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002774 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002775 bool usesPositionalArgs;
2776 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002777 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002778 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002779 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002780public:
Ted Kremenek02087932010-07-16 02:11:22 +00002781 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002782 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002783 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002784 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002785 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002786 Sema::VariadicCallType callType,
2787 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002788 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002789 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2790 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002791 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002792 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002793 inFunctionCall(inFunctionCall), CallType(callType),
2794 CheckedVarArgs(CheckedVarArgs) {
2795 CoveredArgs.resize(numDataArgs);
2796 CoveredArgs.reset();
2797 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002798
Ted Kremenek019d2242010-01-29 01:50:07 +00002799 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002800
Ted Kremenek02087932010-07-16 02:11:22 +00002801 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002802 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002803
Jordan Rose92303592012-09-08 04:00:03 +00002804 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002805 const analyze_format_string::FormatSpecifier &FS,
2806 const analyze_format_string::ConversionSpecifier &CS,
2807 const char *startSpecifier, unsigned specifierLen,
2808 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002809
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002810 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002811 const analyze_format_string::FormatSpecifier &FS,
2812 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002813
2814 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002815 const analyze_format_string::ConversionSpecifier &CS,
2816 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002817
Craig Toppere14c0f82014-03-12 04:55:44 +00002818 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002819
Craig Toppere14c0f82014-03-12 04:55:44 +00002820 void HandleInvalidPosition(const char *startSpecifier,
2821 unsigned specifierLen,
2822 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002823
Craig Toppere14c0f82014-03-12 04:55:44 +00002824 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002825
Craig Toppere14c0f82014-03-12 04:55:44 +00002826 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002827
Richard Trieu03cf7b72011-10-28 00:41:25 +00002828 template <typename Range>
2829 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2830 const Expr *ArgumentExpr,
2831 PartialDiagnostic PDiag,
2832 SourceLocation StringLoc,
2833 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002834 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002835
Ted Kremenek02087932010-07-16 02:11:22 +00002836protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002837 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2838 const char *startSpec,
2839 unsigned specifierLen,
2840 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002841
2842 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2843 const char *startSpec,
2844 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002845
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002846 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002847 CharSourceRange getSpecifierRange(const char *startSpecifier,
2848 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002849 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002850
Ted Kremenek5739de72010-01-29 01:06:55 +00002851 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002852
2853 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2854 const analyze_format_string::ConversionSpecifier &CS,
2855 const char *startSpecifier, unsigned specifierLen,
2856 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002857
2858 template <typename Range>
2859 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2860 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002861 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002862};
2863}
2864
Ted Kremenek02087932010-07-16 02:11:22 +00002865SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002866 return OrigFormatExpr->getSourceRange();
2867}
2868
Ted Kremenek02087932010-07-16 02:11:22 +00002869CharSourceRange CheckFormatHandler::
2870getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002871 SourceLocation Start = getLocationOfByte(startSpecifier);
2872 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2873
2874 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002875 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002876
2877 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002878}
2879
Ted Kremenek02087932010-07-16 02:11:22 +00002880SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002881 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002882}
2883
Ted Kremenek02087932010-07-16 02:11:22 +00002884void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2885 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002886 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2887 getLocationOfByte(startSpecifier),
2888 /*IsStringLocation*/true,
2889 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002890}
2891
Jordan Rose92303592012-09-08 04:00:03 +00002892void CheckFormatHandler::HandleInvalidLengthModifier(
2893 const analyze_format_string::FormatSpecifier &FS,
2894 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002895 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002896 using namespace analyze_format_string;
2897
2898 const LengthModifier &LM = FS.getLengthModifier();
2899 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2900
2901 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002902 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002903 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002904 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002905 getLocationOfByte(LM.getStart()),
2906 /*IsStringLocation*/true,
2907 getSpecifierRange(startSpecifier, specifierLen));
2908
2909 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2910 << FixedLM->toString()
2911 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2912
2913 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002914 FixItHint Hint;
2915 if (DiagID == diag::warn_format_nonsensical_length)
2916 Hint = FixItHint::CreateRemoval(LMRange);
2917
2918 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002919 getLocationOfByte(LM.getStart()),
2920 /*IsStringLocation*/true,
2921 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002922 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002923 }
2924}
2925
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002926void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002927 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002928 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002929 using namespace analyze_format_string;
2930
2931 const LengthModifier &LM = FS.getLengthModifier();
2932 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2933
2934 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002935 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002936 if (FixedLM) {
2937 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2938 << LM.toString() << 0,
2939 getLocationOfByte(LM.getStart()),
2940 /*IsStringLocation*/true,
2941 getSpecifierRange(startSpecifier, specifierLen));
2942
2943 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2944 << FixedLM->toString()
2945 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2946
2947 } else {
2948 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2949 << LM.toString() << 0,
2950 getLocationOfByte(LM.getStart()),
2951 /*IsStringLocation*/true,
2952 getSpecifierRange(startSpecifier, specifierLen));
2953 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002954}
2955
2956void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2957 const analyze_format_string::ConversionSpecifier &CS,
2958 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002959 using namespace analyze_format_string;
2960
2961 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002962 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002963 if (FixedCS) {
2964 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2965 << CS.toString() << /*conversion specifier*/1,
2966 getLocationOfByte(CS.getStart()),
2967 /*IsStringLocation*/true,
2968 getSpecifierRange(startSpecifier, specifierLen));
2969
2970 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2971 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2972 << FixedCS->toString()
2973 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2974 } else {
2975 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2976 << CS.toString() << /*conversion specifier*/1,
2977 getLocationOfByte(CS.getStart()),
2978 /*IsStringLocation*/true,
2979 getSpecifierRange(startSpecifier, specifierLen));
2980 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002981}
2982
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002983void CheckFormatHandler::HandlePosition(const char *startPos,
2984 unsigned posLen) {
2985 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2986 getLocationOfByte(startPos),
2987 /*IsStringLocation*/true,
2988 getSpecifierRange(startPos, posLen));
2989}
2990
Ted Kremenekd1668192010-02-27 01:41:03 +00002991void
Ted Kremenek02087932010-07-16 02:11:22 +00002992CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2993 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002994 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2995 << (unsigned) p,
2996 getLocationOfByte(startPos), /*IsStringLocation*/true,
2997 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002998}
2999
Ted Kremenek02087932010-07-16 02:11:22 +00003000void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003001 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003002 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3003 getLocationOfByte(startPos),
3004 /*IsStringLocation*/true,
3005 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003006}
3007
Ted Kremenek02087932010-07-16 02:11:22 +00003008void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003009 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003010 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003011 EmitFormatDiagnostic(
3012 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3013 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3014 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003015 }
Ted Kremenek02087932010-07-16 02:11:22 +00003016}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003017
Jordan Rose58bbe422012-07-19 18:10:08 +00003018// Note that this may return NULL if there was an error parsing or building
3019// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003020const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003021 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003022}
3023
3024void CheckFormatHandler::DoneProcessing() {
3025 // Does the number of data arguments exceed the number of
3026 // format conversions in the format string?
3027 if (!HasVAListArg) {
3028 // Find any arguments that weren't covered.
3029 CoveredArgs.flip();
3030 signed notCoveredArg = CoveredArgs.find_first();
3031 if (notCoveredArg >= 0) {
3032 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003033 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3034 SourceLocation Loc = E->getLocStart();
3035 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3036 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3037 Loc, /*IsStringLocation*/false,
3038 getFormatStringRange());
3039 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003040 }
Ted Kremenek02087932010-07-16 02:11:22 +00003041 }
3042 }
3043}
3044
Ted Kremenekce815422010-07-19 21:25:57 +00003045bool
3046CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3047 SourceLocation Loc,
3048 const char *startSpec,
3049 unsigned specifierLen,
3050 const char *csStart,
3051 unsigned csLen) {
3052
3053 bool keepGoing = true;
3054 if (argIndex < NumDataArgs) {
3055 // Consider the argument coverered, even though the specifier doesn't
3056 // make sense.
3057 CoveredArgs.set(argIndex);
3058 }
3059 else {
3060 // If argIndex exceeds the number of data arguments we
3061 // don't issue a warning because that is just a cascade of warnings (and
3062 // they may have intended '%%' anyway). We don't want to continue processing
3063 // the format string after this point, however, as we will like just get
3064 // gibberish when trying to match arguments.
3065 keepGoing = false;
3066 }
3067
Richard Trieu03cf7b72011-10-28 00:41:25 +00003068 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3069 << StringRef(csStart, csLen),
3070 Loc, /*IsStringLocation*/true,
3071 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003072
3073 return keepGoing;
3074}
3075
Richard Trieu03cf7b72011-10-28 00:41:25 +00003076void
3077CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3078 const char *startSpec,
3079 unsigned specifierLen) {
3080 EmitFormatDiagnostic(
3081 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3082 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3083}
3084
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003085bool
3086CheckFormatHandler::CheckNumArgs(
3087 const analyze_format_string::FormatSpecifier &FS,
3088 const analyze_format_string::ConversionSpecifier &CS,
3089 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3090
3091 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003092 PartialDiagnostic PDiag = FS.usesPositionalArg()
3093 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3094 << (argIndex+1) << NumDataArgs)
3095 : S.PDiag(diag::warn_printf_insufficient_data_args);
3096 EmitFormatDiagnostic(
3097 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3098 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003099 return false;
3100 }
3101 return true;
3102}
3103
Richard Trieu03cf7b72011-10-28 00:41:25 +00003104template<typename Range>
3105void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3106 SourceLocation Loc,
3107 bool IsStringLocation,
3108 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003109 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003110 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003111 Loc, IsStringLocation, StringRange, FixIt);
3112}
3113
3114/// \brief If the format string is not within the funcion call, emit a note
3115/// so that the function call and string are in diagnostic messages.
3116///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003117/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003118/// call and only one diagnostic message will be produced. Otherwise, an
3119/// extra note will be emitted pointing to location of the format string.
3120///
3121/// \param ArgumentExpr the expression that is passed as the format string
3122/// argument in the function call. Used for getting locations when two
3123/// diagnostics are emitted.
3124///
3125/// \param PDiag the callee should already have provided any strings for the
3126/// diagnostic message. This function only adds locations and fixits
3127/// to diagnostics.
3128///
3129/// \param Loc primary location for diagnostic. If two diagnostics are
3130/// required, one will be at Loc and a new SourceLocation will be created for
3131/// the other one.
3132///
3133/// \param IsStringLocation if true, Loc points to the format string should be
3134/// used for the note. Otherwise, Loc points to the argument list and will
3135/// be used with PDiag.
3136///
3137/// \param StringRange some or all of the string to highlight. This is
3138/// templated so it can accept either a CharSourceRange or a SourceRange.
3139///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003140/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003141template<typename Range>
3142void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3143 const Expr *ArgumentExpr,
3144 PartialDiagnostic PDiag,
3145 SourceLocation Loc,
3146 bool IsStringLocation,
3147 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003148 ArrayRef<FixItHint> FixIt) {
3149 if (InFunctionCall) {
3150 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3151 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003152 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003153 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003154 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3155 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003156
3157 const Sema::SemaDiagnosticBuilder &Note =
3158 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3159 diag::note_format_string_defined);
3160
3161 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003162 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003163 }
3164}
3165
Ted Kremenek02087932010-07-16 02:11:22 +00003166//===--- CHECK: Printf format string checking ------------------------------===//
3167
3168namespace {
3169class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003170 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003171public:
3172 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3173 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003174 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003175 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003176 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003177 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003178 Sema::VariadicCallType CallType,
3179 llvm::SmallBitVector &CheckedVarArgs)
3180 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3181 numDataArgs, beg, hasVAListArg, Args,
3182 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3183 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003184 {}
3185
Craig Toppere14c0f82014-03-12 04:55:44 +00003186
Ted Kremenek02087932010-07-16 02:11:22 +00003187 bool HandleInvalidPrintfConversionSpecifier(
3188 const analyze_printf::PrintfSpecifier &FS,
3189 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003190 unsigned specifierLen) override;
3191
Ted Kremenek02087932010-07-16 02:11:22 +00003192 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3193 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003194 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003195 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3196 const char *StartSpecifier,
3197 unsigned SpecifierLen,
3198 const Expr *E);
3199
Ted Kremenek02087932010-07-16 02:11:22 +00003200 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3201 const char *startSpecifier, unsigned specifierLen);
3202 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3203 const analyze_printf::OptionalAmount &Amt,
3204 unsigned type,
3205 const char *startSpecifier, unsigned specifierLen);
3206 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3207 const analyze_printf::OptionalFlag &flag,
3208 const char *startSpecifier, unsigned specifierLen);
3209 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3210 const analyze_printf::OptionalFlag &ignoredFlag,
3211 const analyze_printf::OptionalFlag &flag,
3212 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003213 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003214 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003215
Ted Kremenek02087932010-07-16 02:11:22 +00003216};
3217}
3218
3219bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3220 const analyze_printf::PrintfSpecifier &FS,
3221 const char *startSpecifier,
3222 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003223 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003224 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003225
Ted Kremenekce815422010-07-19 21:25:57 +00003226 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3227 getLocationOfByte(CS.getStart()),
3228 startSpecifier, specifierLen,
3229 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003230}
3231
Ted Kremenek02087932010-07-16 02:11:22 +00003232bool CheckPrintfHandler::HandleAmount(
3233 const analyze_format_string::OptionalAmount &Amt,
3234 unsigned k, const char *startSpecifier,
3235 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003236
3237 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003238 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003239 unsigned argIndex = Amt.getArgIndex();
3240 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003241 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3242 << k,
3243 getLocationOfByte(Amt.getStart()),
3244 /*IsStringLocation*/true,
3245 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003246 // Don't do any more checking. We will just emit
3247 // spurious errors.
3248 return false;
3249 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003250
Ted Kremenek5739de72010-01-29 01:06:55 +00003251 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003252 // Although not in conformance with C99, we also allow the argument to be
3253 // an 'unsigned int' as that is a reasonably safe case. GCC also
3254 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003255 CoveredArgs.set(argIndex);
3256 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003257 if (!Arg)
3258 return false;
3259
Ted Kremenek5739de72010-01-29 01:06:55 +00003260 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003261
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003262 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3263 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003264
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003265 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003266 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003267 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003268 << T << Arg->getSourceRange(),
3269 getLocationOfByte(Amt.getStart()),
3270 /*IsStringLocation*/true,
3271 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003272 // Don't do any more checking. We will just emit
3273 // spurious errors.
3274 return false;
3275 }
3276 }
3277 }
3278 return true;
3279}
Ted Kremenek5739de72010-01-29 01:06:55 +00003280
Tom Careb49ec692010-06-17 19:00:27 +00003281void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003282 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003283 const analyze_printf::OptionalAmount &Amt,
3284 unsigned type,
3285 const char *startSpecifier,
3286 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003287 const analyze_printf::PrintfConversionSpecifier &CS =
3288 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003289
Richard Trieu03cf7b72011-10-28 00:41:25 +00003290 FixItHint fixit =
3291 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3292 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3293 Amt.getConstantLength()))
3294 : FixItHint();
3295
3296 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3297 << type << CS.toString(),
3298 getLocationOfByte(Amt.getStart()),
3299 /*IsStringLocation*/true,
3300 getSpecifierRange(startSpecifier, specifierLen),
3301 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003302}
3303
Ted Kremenek02087932010-07-16 02:11:22 +00003304void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003305 const analyze_printf::OptionalFlag &flag,
3306 const char *startSpecifier,
3307 unsigned specifierLen) {
3308 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003309 const analyze_printf::PrintfConversionSpecifier &CS =
3310 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003311 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3312 << flag.toString() << CS.toString(),
3313 getLocationOfByte(flag.getPosition()),
3314 /*IsStringLocation*/true,
3315 getSpecifierRange(startSpecifier, specifierLen),
3316 FixItHint::CreateRemoval(
3317 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003318}
3319
3320void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003321 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003322 const analyze_printf::OptionalFlag &ignoredFlag,
3323 const analyze_printf::OptionalFlag &flag,
3324 const char *startSpecifier,
3325 unsigned specifierLen) {
3326 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003327 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3328 << ignoredFlag.toString() << flag.toString(),
3329 getLocationOfByte(ignoredFlag.getPosition()),
3330 /*IsStringLocation*/true,
3331 getSpecifierRange(startSpecifier, specifierLen),
3332 FixItHint::CreateRemoval(
3333 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003334}
3335
Richard Smith55ce3522012-06-25 20:30:08 +00003336// Determines if the specified is a C++ class or struct containing
3337// a member with the specified name and kind (e.g. a CXXMethodDecl named
3338// "c_str()").
3339template<typename MemberKind>
3340static llvm::SmallPtrSet<MemberKind*, 1>
3341CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3342 const RecordType *RT = Ty->getAs<RecordType>();
3343 llvm::SmallPtrSet<MemberKind*, 1> Results;
3344
3345 if (!RT)
3346 return Results;
3347 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003348 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003349 return Results;
3350
Alp Tokerb6cc5922014-05-03 03:45:55 +00003351 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003352 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003353 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003354
3355 // We just need to include all members of the right kind turned up by the
3356 // filter, at this point.
3357 if (S.LookupQualifiedName(R, RT->getDecl()))
3358 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3359 NamedDecl *decl = (*I)->getUnderlyingDecl();
3360 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3361 Results.insert(FK);
3362 }
3363 return Results;
3364}
3365
Richard Smith2868a732014-02-28 01:36:39 +00003366/// Check if we could call '.c_str()' on an object.
3367///
3368/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3369/// allow the call, or if it would be ambiguous).
3370bool Sema::hasCStrMethod(const Expr *E) {
3371 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3372 MethodSet Results =
3373 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3374 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3375 MI != ME; ++MI)
3376 if ((*MI)->getMinRequiredArguments() == 0)
3377 return true;
3378 return false;
3379}
3380
Richard Smith55ce3522012-06-25 20:30:08 +00003381// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003382// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003383// Returns true when a c_str() conversion method is found.
3384bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003385 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003386 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3387
3388 MethodSet Results =
3389 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3390
3391 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3392 MI != ME; ++MI) {
3393 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003394 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003395 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003396 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003397 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003398 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3399 << "c_str()"
3400 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3401 return true;
3402 }
3403 }
3404
3405 return false;
3406}
3407
Ted Kremenekab278de2010-01-28 23:39:18 +00003408bool
Ted Kremenek02087932010-07-16 02:11:22 +00003409CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003410 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003411 const char *startSpecifier,
3412 unsigned specifierLen) {
3413
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003414 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003415 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003416 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003417
Ted Kremenek6cd69422010-07-19 22:01:06 +00003418 if (FS.consumesDataArgument()) {
3419 if (atFirstArg) {
3420 atFirstArg = false;
3421 usesPositionalArgs = FS.usesPositionalArg();
3422 }
3423 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003424 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3425 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003426 return false;
3427 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003428 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003429
Ted Kremenekd1668192010-02-27 01:41:03 +00003430 // First check if the field width, precision, and conversion specifier
3431 // have matching data arguments.
3432 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3433 startSpecifier, specifierLen)) {
3434 return false;
3435 }
3436
3437 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3438 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003439 return false;
3440 }
3441
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003442 if (!CS.consumesDataArgument()) {
3443 // FIXME: Technically specifying a precision or field width here
3444 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003445 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003446 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003447
Ted Kremenek4a49d982010-02-26 19:18:41 +00003448 // Consume the argument.
3449 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003450 if (argIndex < NumDataArgs) {
3451 // The check to see if the argIndex is valid will come later.
3452 // We set the bit here because we may exit early from this
3453 // function if we encounter some other error.
3454 CoveredArgs.set(argIndex);
3455 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003456
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003457 // FreeBSD kernel extensions.
3458 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3459 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3460 // We need at least two arguments.
3461 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3462 return false;
3463
3464 // Claim the second argument.
3465 CoveredArgs.set(argIndex + 1);
3466
3467 // Type check the first argument (int for %b, pointer for %D)
3468 const Expr *Ex = getDataArg(argIndex);
3469 const analyze_printf::ArgType &AT =
3470 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3471 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3472 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3473 EmitFormatDiagnostic(
3474 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3475 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3476 << false << Ex->getSourceRange(),
3477 Ex->getLocStart(), /*IsStringLocation*/false,
3478 getSpecifierRange(startSpecifier, specifierLen));
3479
3480 // Type check the second argument (char * for both %b and %D)
3481 Ex = getDataArg(argIndex + 1);
3482 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3483 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3484 EmitFormatDiagnostic(
3485 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3486 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3487 << false << Ex->getSourceRange(),
3488 Ex->getLocStart(), /*IsStringLocation*/false,
3489 getSpecifierRange(startSpecifier, specifierLen));
3490
3491 return true;
3492 }
3493
Ted Kremenek4a49d982010-02-26 19:18:41 +00003494 // Check for using an Objective-C specific conversion specifier
3495 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003496 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003497 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3498 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003499 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003500
Tom Careb49ec692010-06-17 19:00:27 +00003501 // Check for invalid use of field width
3502 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003503 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003504 startSpecifier, specifierLen);
3505 }
3506
3507 // Check for invalid use of precision
3508 if (!FS.hasValidPrecision()) {
3509 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3510 startSpecifier, specifierLen);
3511 }
3512
3513 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003514 if (!FS.hasValidThousandsGroupingPrefix())
3515 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003516 if (!FS.hasValidLeadingZeros())
3517 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3518 if (!FS.hasValidPlusPrefix())
3519 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003520 if (!FS.hasValidSpacePrefix())
3521 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003522 if (!FS.hasValidAlternativeForm())
3523 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3524 if (!FS.hasValidLeftJustified())
3525 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3526
3527 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003528 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3529 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3530 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003531 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3532 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3533 startSpecifier, specifierLen);
3534
3535 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003536 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003537 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3538 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003539 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003540 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003541 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003542 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3543 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003544
Jordan Rose92303592012-09-08 04:00:03 +00003545 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3546 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3547
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003548 // The remaining checks depend on the data arguments.
3549 if (HasVAListArg)
3550 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003551
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003552 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003553 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003554
Jordan Rose58bbe422012-07-19 18:10:08 +00003555 const Expr *Arg = getDataArg(argIndex);
3556 if (!Arg)
3557 return true;
3558
3559 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003560}
3561
Jordan Roseaee34382012-09-05 22:56:26 +00003562static bool requiresParensToAddCast(const Expr *E) {
3563 // FIXME: We should have a general way to reason about operator
3564 // precedence and whether parens are actually needed here.
3565 // Take care of a few common cases where they aren't.
3566 const Expr *Inside = E->IgnoreImpCasts();
3567 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3568 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3569
3570 switch (Inside->getStmtClass()) {
3571 case Stmt::ArraySubscriptExprClass:
3572 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003573 case Stmt::CharacterLiteralClass:
3574 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003575 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003576 case Stmt::FloatingLiteralClass:
3577 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003578 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003579 case Stmt::ObjCArrayLiteralClass:
3580 case Stmt::ObjCBoolLiteralExprClass:
3581 case Stmt::ObjCBoxedExprClass:
3582 case Stmt::ObjCDictionaryLiteralClass:
3583 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003584 case Stmt::ObjCIvarRefExprClass:
3585 case Stmt::ObjCMessageExprClass:
3586 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003587 case Stmt::ObjCStringLiteralClass:
3588 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003589 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003590 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003591 case Stmt::UnaryOperatorClass:
3592 return false;
3593 default:
3594 return true;
3595 }
3596}
3597
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003598static std::pair<QualType, StringRef>
3599shouldNotPrintDirectly(const ASTContext &Context,
3600 QualType IntendedTy,
3601 const Expr *E) {
3602 // Use a 'while' to peel off layers of typedefs.
3603 QualType TyTy = IntendedTy;
3604 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3605 StringRef Name = UserTy->getDecl()->getName();
3606 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3607 .Case("NSInteger", Context.LongTy)
3608 .Case("NSUInteger", Context.UnsignedLongTy)
3609 .Case("SInt32", Context.IntTy)
3610 .Case("UInt32", Context.UnsignedIntTy)
3611 .Default(QualType());
3612
3613 if (!CastTy.isNull())
3614 return std::make_pair(CastTy, Name);
3615
3616 TyTy = UserTy->desugar();
3617 }
3618
3619 // Strip parens if necessary.
3620 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3621 return shouldNotPrintDirectly(Context,
3622 PE->getSubExpr()->getType(),
3623 PE->getSubExpr());
3624
3625 // If this is a conditional expression, then its result type is constructed
3626 // via usual arithmetic conversions and thus there might be no necessary
3627 // typedef sugar there. Recurse to operands to check for NSInteger &
3628 // Co. usage condition.
3629 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3630 QualType TrueTy, FalseTy;
3631 StringRef TrueName, FalseName;
3632
3633 std::tie(TrueTy, TrueName) =
3634 shouldNotPrintDirectly(Context,
3635 CO->getTrueExpr()->getType(),
3636 CO->getTrueExpr());
3637 std::tie(FalseTy, FalseName) =
3638 shouldNotPrintDirectly(Context,
3639 CO->getFalseExpr()->getType(),
3640 CO->getFalseExpr());
3641
3642 if (TrueTy == FalseTy)
3643 return std::make_pair(TrueTy, TrueName);
3644 else if (TrueTy.isNull())
3645 return std::make_pair(FalseTy, FalseName);
3646 else if (FalseTy.isNull())
3647 return std::make_pair(TrueTy, TrueName);
3648 }
3649
3650 return std::make_pair(QualType(), StringRef());
3651}
3652
Richard Smith55ce3522012-06-25 20:30:08 +00003653bool
3654CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3655 const char *StartSpecifier,
3656 unsigned SpecifierLen,
3657 const Expr *E) {
3658 using namespace analyze_format_string;
3659 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003660 // Now type check the data expression that matches the
3661 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003662 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3663 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003664 if (!AT.isValid())
3665 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003666
Jordan Rose598ec092012-12-05 18:44:40 +00003667 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003668 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3669 ExprTy = TET->getUnderlyingExpr()->getType();
3670 }
3671
Seth Cantrellb4802962015-03-04 03:12:10 +00003672 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
3673
3674 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00003675 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00003676 }
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:
Seth Cantrellb4802962015-03-04 03:12:10 +00003854 case Sema::VAK_ValidInCXX11: {
3855 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3856 if (match == analyze_printf::ArgType::NoMatchPedantic) {
3857 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3858 }
Richard Smithd7293d72013-08-05 18:49:43 +00003859
Seth Cantrellb4802962015-03-04 03:12:10 +00003860 EmitFormatDiagnostic(
3861 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
3862 << IsEnum << CSR << E->getSourceRange(),
3863 E->getLocStart(), /*IsStringLocation*/ false, CSR);
3864 break;
3865 }
Richard Smithd7293d72013-08-05 18:49:43 +00003866 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00003867 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00003868 EmitFormatDiagnostic(
3869 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003870 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003871 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003872 << CallType
3873 << AT.getRepresentativeTypeName(S.Context)
3874 << CSR
3875 << E->getSourceRange(),
3876 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003877 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003878 break;
3879
3880 case Sema::VAK_Invalid:
3881 if (ExprTy->isObjCObjectType())
3882 EmitFormatDiagnostic(
3883 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3884 << S.getLangOpts().CPlusPlus11
3885 << ExprTy
3886 << CallType
3887 << AT.getRepresentativeTypeName(S.Context)
3888 << CSR
3889 << E->getSourceRange(),
3890 E->getLocStart(), /*IsStringLocation*/false, CSR);
3891 else
3892 // FIXME: If this is an initializer list, suggest removing the braces
3893 // or inserting a cast to the target type.
3894 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3895 << isa<InitListExpr>(E) << ExprTy << CallType
3896 << AT.getRepresentativeTypeName(S.Context)
3897 << E->getSourceRange();
3898 break;
3899 }
3900
3901 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3902 "format string specifier index out of range");
3903 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003904 }
3905
Ted Kremenekab278de2010-01-28 23:39:18 +00003906 return true;
3907}
3908
Ted Kremenek02087932010-07-16 02:11:22 +00003909//===--- CHECK: Scanf format string checking ------------------------------===//
3910
3911namespace {
3912class CheckScanfHandler : public CheckFormatHandler {
3913public:
3914 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3915 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003916 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003917 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003918 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003919 Sema::VariadicCallType CallType,
3920 llvm::SmallBitVector &CheckedVarArgs)
3921 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3922 numDataArgs, beg, hasVAListArg,
3923 Args, formatIdx, inFunctionCall, CallType,
3924 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003925 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003926
3927 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3928 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003929 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003930
3931 bool HandleInvalidScanfConversionSpecifier(
3932 const analyze_scanf::ScanfSpecifier &FS,
3933 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003934 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003935
Craig Toppere14c0f82014-03-12 04:55:44 +00003936 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003937};
Ted Kremenek019d2242010-01-29 01:50:07 +00003938}
Ted Kremenekab278de2010-01-28 23:39:18 +00003939
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003940void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3941 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003942 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3943 getLocationOfByte(end), /*IsStringLocation*/true,
3944 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003945}
3946
Ted Kremenekce815422010-07-19 21:25:57 +00003947bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3948 const analyze_scanf::ScanfSpecifier &FS,
3949 const char *startSpecifier,
3950 unsigned specifierLen) {
3951
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003952 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003953 FS.getConversionSpecifier();
3954
3955 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3956 getLocationOfByte(CS.getStart()),
3957 startSpecifier, specifierLen,
3958 CS.getStart(), CS.getLength());
3959}
3960
Ted Kremenek02087932010-07-16 02:11:22 +00003961bool CheckScanfHandler::HandleScanfSpecifier(
3962 const analyze_scanf::ScanfSpecifier &FS,
3963 const char *startSpecifier,
3964 unsigned specifierLen) {
3965
3966 using namespace analyze_scanf;
3967 using namespace analyze_format_string;
3968
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003969 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003970
Ted Kremenek6cd69422010-07-19 22:01:06 +00003971 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3972 // be used to decide if we are using positional arguments consistently.
3973 if (FS.consumesDataArgument()) {
3974 if (atFirstArg) {
3975 atFirstArg = false;
3976 usesPositionalArgs = FS.usesPositionalArg();
3977 }
3978 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003979 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3980 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003981 return false;
3982 }
Ted Kremenek02087932010-07-16 02:11:22 +00003983 }
3984
3985 // Check if the field with is non-zero.
3986 const OptionalAmount &Amt = FS.getFieldWidth();
3987 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3988 if (Amt.getConstantAmount() == 0) {
3989 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3990 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003991 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3992 getLocationOfByte(Amt.getStart()),
3993 /*IsStringLocation*/true, R,
3994 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003995 }
3996 }
Seth Cantrellb4802962015-03-04 03:12:10 +00003997
Ted Kremenek02087932010-07-16 02:11:22 +00003998 if (!FS.consumesDataArgument()) {
3999 // FIXME: Technically specifying a precision or field width here
4000 // makes no sense. Worth issuing a warning at some point.
4001 return true;
4002 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004003
Ted Kremenek02087932010-07-16 02:11:22 +00004004 // Consume the argument.
4005 unsigned argIndex = FS.getArgIndex();
4006 if (argIndex < NumDataArgs) {
4007 // The check to see if the argIndex is valid will come later.
4008 // We set the bit here because we may exit early from this
4009 // function if we encounter some other error.
4010 CoveredArgs.set(argIndex);
4011 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004012
Ted Kremenek4407ea42010-07-20 20:04:47 +00004013 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004014 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004015 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4016 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004017 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004018 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004019 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004020 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4021 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004022
Jordan Rose92303592012-09-08 04:00:03 +00004023 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4024 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4025
Ted Kremenek02087932010-07-16 02:11:22 +00004026 // The remaining checks depend on the data arguments.
4027 if (HasVAListArg)
4028 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004029
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004030 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004031 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004032
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004033 // Check that the argument type matches the format specifier.
4034 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004035 if (!Ex)
4036 return true;
4037
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004038 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004039
4040 if (!AT.isValid()) {
4041 return true;
4042 }
4043
Seth Cantrellb4802962015-03-04 03:12:10 +00004044 analyze_format_string::ArgType::MatchKind match =
4045 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004046 if (match == analyze_format_string::ArgType::Match) {
4047 return true;
4048 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004049
Seth Cantrell79340072015-03-04 05:58:08 +00004050 ScanfSpecifier fixedFS = FS;
4051 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4052 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004053
Seth Cantrell79340072015-03-04 05:58:08 +00004054 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4055 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4056 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4057 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004058
Seth Cantrell79340072015-03-04 05:58:08 +00004059 if (success) {
4060 // Get the fix string from the fixed format specifier.
4061 SmallString<128> buf;
4062 llvm::raw_svector_ostream os(buf);
4063 fixedFS.toString(os);
4064
4065 EmitFormatDiagnostic(
4066 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4067 << Ex->getType() << false << Ex->getSourceRange(),
4068 Ex->getLocStart(),
4069 /*IsStringLocation*/ false,
4070 getSpecifierRange(startSpecifier, specifierLen),
4071 FixItHint::CreateReplacement(
4072 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4073 } else {
4074 EmitFormatDiagnostic(S.PDiag(diag)
4075 << AT.getRepresentativeTypeName(S.Context)
4076 << Ex->getType() << false << Ex->getSourceRange(),
4077 Ex->getLocStart(),
4078 /*IsStringLocation*/ false,
4079 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004080 }
4081
Ted Kremenek02087932010-07-16 02:11:22 +00004082 return true;
4083}
4084
4085void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004086 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004087 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004088 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004089 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004090 bool inFunctionCall, VariadicCallType CallType,
4091 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004092
Ted Kremenekab278de2010-01-28 23:39:18 +00004093 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004094 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004095 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004096 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004097 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4098 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004099 return;
4100 }
Ted Kremenek02087932010-07-16 02:11:22 +00004101
Ted Kremenekab278de2010-01-28 23:39:18 +00004102 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004103 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004104 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004105 // Account for cases where the string literal is truncated in a declaration.
4106 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4107 assert(T && "String literal not of constant array type!");
4108 size_t TypeSize = T->getSize().getZExtValue();
4109 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004110 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004111
4112 // Emit a warning if the string literal is truncated and does not contain an
4113 // embedded null character.
4114 if (TypeSize <= StrRef.size() &&
4115 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4116 CheckFormatHandler::EmitFormatDiagnostic(
4117 *this, inFunctionCall, Args[format_idx],
4118 PDiag(diag::warn_printf_format_string_not_null_terminated),
4119 FExpr->getLocStart(),
4120 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4121 return;
4122 }
4123
Ted Kremenekab278de2010-01-28 23:39:18 +00004124 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004125 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004126 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004127 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004128 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4129 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004130 return;
4131 }
Ted Kremenek02087932010-07-16 02:11:22 +00004132
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004133 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004134 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004135 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004136 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004137 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004138 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004139
Hans Wennborg23926bd2011-12-15 10:25:47 +00004140 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004141 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004142 Context.getTargetInfo(),
4143 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004144 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004145 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004146 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004147 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004148 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004149
Hans Wennborg23926bd2011-12-15 10:25:47 +00004150 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004151 getLangOpts(),
4152 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004153 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004154 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004155}
4156
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004157bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4158 // Str - The format string. NOTE: this is NOT null-terminated!
4159 StringRef StrRef = FExpr->getString();
4160 const char *Str = StrRef.data();
4161 // Account for cases where the string literal is truncated in a declaration.
4162 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4163 assert(T && "String literal not of constant array type!");
4164 size_t TypeSize = T->getSize().getZExtValue();
4165 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4166 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4167 getLangOpts(),
4168 Context.getTargetInfo());
4169}
4170
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004171//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4172
4173// Returns the related absolute value function that is larger, of 0 if one
4174// does not exist.
4175static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4176 switch (AbsFunction) {
4177 default:
4178 return 0;
4179
4180 case Builtin::BI__builtin_abs:
4181 return Builtin::BI__builtin_labs;
4182 case Builtin::BI__builtin_labs:
4183 return Builtin::BI__builtin_llabs;
4184 case Builtin::BI__builtin_llabs:
4185 return 0;
4186
4187 case Builtin::BI__builtin_fabsf:
4188 return Builtin::BI__builtin_fabs;
4189 case Builtin::BI__builtin_fabs:
4190 return Builtin::BI__builtin_fabsl;
4191 case Builtin::BI__builtin_fabsl:
4192 return 0;
4193
4194 case Builtin::BI__builtin_cabsf:
4195 return Builtin::BI__builtin_cabs;
4196 case Builtin::BI__builtin_cabs:
4197 return Builtin::BI__builtin_cabsl;
4198 case Builtin::BI__builtin_cabsl:
4199 return 0;
4200
4201 case Builtin::BIabs:
4202 return Builtin::BIlabs;
4203 case Builtin::BIlabs:
4204 return Builtin::BIllabs;
4205 case Builtin::BIllabs:
4206 return 0;
4207
4208 case Builtin::BIfabsf:
4209 return Builtin::BIfabs;
4210 case Builtin::BIfabs:
4211 return Builtin::BIfabsl;
4212 case Builtin::BIfabsl:
4213 return 0;
4214
4215 case Builtin::BIcabsf:
4216 return Builtin::BIcabs;
4217 case Builtin::BIcabs:
4218 return Builtin::BIcabsl;
4219 case Builtin::BIcabsl:
4220 return 0;
4221 }
4222}
4223
4224// Returns the argument type of the absolute value function.
4225static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4226 unsigned AbsType) {
4227 if (AbsType == 0)
4228 return QualType();
4229
4230 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4231 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4232 if (Error != ASTContext::GE_None)
4233 return QualType();
4234
4235 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4236 if (!FT)
4237 return QualType();
4238
4239 if (FT->getNumParams() != 1)
4240 return QualType();
4241
4242 return FT->getParamType(0);
4243}
4244
4245// Returns the best absolute value function, or zero, based on type and
4246// current absolute value function.
4247static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4248 unsigned AbsFunctionKind) {
4249 unsigned BestKind = 0;
4250 uint64_t ArgSize = Context.getTypeSize(ArgType);
4251 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4252 Kind = getLargerAbsoluteValueFunction(Kind)) {
4253 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4254 if (Context.getTypeSize(ParamType) >= ArgSize) {
4255 if (BestKind == 0)
4256 BestKind = Kind;
4257 else if (Context.hasSameType(ParamType, ArgType)) {
4258 BestKind = Kind;
4259 break;
4260 }
4261 }
4262 }
4263 return BestKind;
4264}
4265
4266enum AbsoluteValueKind {
4267 AVK_Integer,
4268 AVK_Floating,
4269 AVK_Complex
4270};
4271
4272static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4273 if (T->isIntegralOrEnumerationType())
4274 return AVK_Integer;
4275 if (T->isRealFloatingType())
4276 return AVK_Floating;
4277 if (T->isAnyComplexType())
4278 return AVK_Complex;
4279
4280 llvm_unreachable("Type not integer, floating, or complex");
4281}
4282
4283// Changes the absolute value function to a different type. Preserves whether
4284// the function is a builtin.
4285static unsigned changeAbsFunction(unsigned AbsKind,
4286 AbsoluteValueKind ValueKind) {
4287 switch (ValueKind) {
4288 case AVK_Integer:
4289 switch (AbsKind) {
4290 default:
4291 return 0;
4292 case Builtin::BI__builtin_fabsf:
4293 case Builtin::BI__builtin_fabs:
4294 case Builtin::BI__builtin_fabsl:
4295 case Builtin::BI__builtin_cabsf:
4296 case Builtin::BI__builtin_cabs:
4297 case Builtin::BI__builtin_cabsl:
4298 return Builtin::BI__builtin_abs;
4299 case Builtin::BIfabsf:
4300 case Builtin::BIfabs:
4301 case Builtin::BIfabsl:
4302 case Builtin::BIcabsf:
4303 case Builtin::BIcabs:
4304 case Builtin::BIcabsl:
4305 return Builtin::BIabs;
4306 }
4307 case AVK_Floating:
4308 switch (AbsKind) {
4309 default:
4310 return 0;
4311 case Builtin::BI__builtin_abs:
4312 case Builtin::BI__builtin_labs:
4313 case Builtin::BI__builtin_llabs:
4314 case Builtin::BI__builtin_cabsf:
4315 case Builtin::BI__builtin_cabs:
4316 case Builtin::BI__builtin_cabsl:
4317 return Builtin::BI__builtin_fabsf;
4318 case Builtin::BIabs:
4319 case Builtin::BIlabs:
4320 case Builtin::BIllabs:
4321 case Builtin::BIcabsf:
4322 case Builtin::BIcabs:
4323 case Builtin::BIcabsl:
4324 return Builtin::BIfabsf;
4325 }
4326 case AVK_Complex:
4327 switch (AbsKind) {
4328 default:
4329 return 0;
4330 case Builtin::BI__builtin_abs:
4331 case Builtin::BI__builtin_labs:
4332 case Builtin::BI__builtin_llabs:
4333 case Builtin::BI__builtin_fabsf:
4334 case Builtin::BI__builtin_fabs:
4335 case Builtin::BI__builtin_fabsl:
4336 return Builtin::BI__builtin_cabsf;
4337 case Builtin::BIabs:
4338 case Builtin::BIlabs:
4339 case Builtin::BIllabs:
4340 case Builtin::BIfabsf:
4341 case Builtin::BIfabs:
4342 case Builtin::BIfabsl:
4343 return Builtin::BIcabsf;
4344 }
4345 }
4346 llvm_unreachable("Unable to convert function");
4347}
4348
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004349static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004350 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4351 if (!FnInfo)
4352 return 0;
4353
4354 switch (FDecl->getBuiltinID()) {
4355 default:
4356 return 0;
4357 case Builtin::BI__builtin_abs:
4358 case Builtin::BI__builtin_fabs:
4359 case Builtin::BI__builtin_fabsf:
4360 case Builtin::BI__builtin_fabsl:
4361 case Builtin::BI__builtin_labs:
4362 case Builtin::BI__builtin_llabs:
4363 case Builtin::BI__builtin_cabs:
4364 case Builtin::BI__builtin_cabsf:
4365 case Builtin::BI__builtin_cabsl:
4366 case Builtin::BIabs:
4367 case Builtin::BIlabs:
4368 case Builtin::BIllabs:
4369 case Builtin::BIfabs:
4370 case Builtin::BIfabsf:
4371 case Builtin::BIfabsl:
4372 case Builtin::BIcabs:
4373 case Builtin::BIcabsf:
4374 case Builtin::BIcabsl:
4375 return FDecl->getBuiltinID();
4376 }
4377 llvm_unreachable("Unknown Builtin type");
4378}
4379
4380// If the replacement is valid, emit a note with replacement function.
4381// Additionally, suggest including the proper header if not already included.
4382static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004383 unsigned AbsKind, QualType ArgType) {
4384 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004385 const char *HeaderName = nullptr;
4386 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004387 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4388 FunctionName = "std::abs";
4389 if (ArgType->isIntegralOrEnumerationType()) {
4390 HeaderName = "cstdlib";
4391 } else if (ArgType->isRealFloatingType()) {
4392 HeaderName = "cmath";
4393 } else {
4394 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004395 }
Richard Trieubeffb832014-04-15 23:47:53 +00004396
4397 // Lookup all std::abs
4398 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004399 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004400 R.suppressDiagnostics();
4401 S.LookupQualifiedName(R, Std);
4402
4403 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004404 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004405 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4406 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4407 } else {
4408 FDecl = dyn_cast<FunctionDecl>(I);
4409 }
4410 if (!FDecl)
4411 continue;
4412
4413 // Found std::abs(), check that they are the right ones.
4414 if (FDecl->getNumParams() != 1)
4415 continue;
4416
4417 // Check that the parameter type can handle the argument.
4418 QualType ParamType = FDecl->getParamDecl(0)->getType();
4419 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4420 S.Context.getTypeSize(ArgType) <=
4421 S.Context.getTypeSize(ParamType)) {
4422 // Found a function, don't need the header hint.
4423 EmitHeaderHint = false;
4424 break;
4425 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004426 }
Richard Trieubeffb832014-04-15 23:47:53 +00004427 }
4428 } else {
4429 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4430 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4431
4432 if (HeaderName) {
4433 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4434 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4435 R.suppressDiagnostics();
4436 S.LookupName(R, S.getCurScope());
4437
4438 if (R.isSingleResult()) {
4439 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4440 if (FD && FD->getBuiltinID() == AbsKind) {
4441 EmitHeaderHint = false;
4442 } else {
4443 return;
4444 }
4445 } else if (!R.empty()) {
4446 return;
4447 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004448 }
4449 }
4450
4451 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004452 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004453
Richard Trieubeffb832014-04-15 23:47:53 +00004454 if (!HeaderName)
4455 return;
4456
4457 if (!EmitHeaderHint)
4458 return;
4459
Alp Toker5d96e0a2014-07-11 20:53:51 +00004460 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4461 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004462}
4463
4464static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4465 if (!FDecl)
4466 return false;
4467
4468 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4469 return false;
4470
4471 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4472
4473 while (ND && ND->isInlineNamespace()) {
4474 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004475 }
Richard Trieubeffb832014-04-15 23:47:53 +00004476
4477 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4478 return false;
4479
4480 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4481 return false;
4482
4483 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004484}
4485
4486// Warn when using the wrong abs() function.
4487void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4488 const FunctionDecl *FDecl,
4489 IdentifierInfo *FnInfo) {
4490 if (Call->getNumArgs() != 1)
4491 return;
4492
4493 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004494 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4495 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004496 return;
4497
4498 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4499 QualType ParamType = Call->getArg(0)->getType();
4500
Alp Toker5d96e0a2014-07-11 20:53:51 +00004501 // Unsigned types cannot be negative. Suggest removing the absolute value
4502 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004503 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004504 const char *FunctionName =
4505 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004506 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4507 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004508 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004509 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4510 return;
4511 }
4512
Richard Trieubeffb832014-04-15 23:47:53 +00004513 // std::abs has overloads which prevent most of the absolute value problems
4514 // from occurring.
4515 if (IsStdAbs)
4516 return;
4517
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004518 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4519 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4520
4521 // The argument and parameter are the same kind. Check if they are the right
4522 // size.
4523 if (ArgValueKind == ParamValueKind) {
4524 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4525 return;
4526
4527 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4528 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4529 << FDecl << ArgType << ParamType;
4530
4531 if (NewAbsKind == 0)
4532 return;
4533
4534 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004535 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004536 return;
4537 }
4538
4539 // ArgValueKind != ParamValueKind
4540 // The wrong type of absolute value function was used. Attempt to find the
4541 // proper one.
4542 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4543 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4544 if (NewAbsKind == 0)
4545 return;
4546
4547 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4548 << FDecl << ParamValueKind << ArgValueKind;
4549
4550 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004551 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004552 return;
4553}
4554
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004555//===--- CHECK: Standard memory functions ---------------------------------===//
4556
Nico Weber0e6daef2013-12-26 23:38:39 +00004557/// \brief Takes the expression passed to the size_t parameter of functions
4558/// such as memcmp, strncat, etc and warns if it's a comparison.
4559///
4560/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4561static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4562 IdentifierInfo *FnName,
4563 SourceLocation FnLoc,
4564 SourceLocation RParenLoc) {
4565 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4566 if (!Size)
4567 return false;
4568
4569 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4570 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4571 return false;
4572
Nico Weber0e6daef2013-12-26 23:38:39 +00004573 SourceRange SizeRange = Size->getSourceRange();
4574 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4575 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004576 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004577 << FnName << FixItHint::CreateInsertion(
4578 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004579 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004580 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004581 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004582 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4583 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004584
4585 return true;
4586}
4587
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004588/// \brief Determine whether the given type is or contains a dynamic class type
4589/// (e.g., whether it has a vtable).
4590static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4591 bool &IsContained) {
4592 // Look through array types while ignoring qualifiers.
4593 const Type *Ty = T->getBaseElementTypeUnsafe();
4594 IsContained = false;
4595
4596 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4597 RD = RD ? RD->getDefinition() : nullptr;
4598 if (!RD)
4599 return nullptr;
4600
4601 if (RD->isDynamicClass())
4602 return RD;
4603
4604 // Check all the fields. If any bases were dynamic, the class is dynamic.
4605 // It's impossible for a class to transitively contain itself by value, so
4606 // infinite recursion is impossible.
4607 for (auto *FD : RD->fields()) {
4608 bool SubContained;
4609 if (const CXXRecordDecl *ContainedRD =
4610 getContainedDynamicClass(FD->getType(), SubContained)) {
4611 IsContained = true;
4612 return ContainedRD;
4613 }
4614 }
4615
4616 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004617}
4618
Chandler Carruth889ed862011-06-21 23:04:20 +00004619/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004620/// otherwise returns NULL.
4621static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004622 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004623 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4624 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4625 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004626
Craig Topperc3ec1492014-05-26 06:22:03 +00004627 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004628}
4629
Chandler Carruth889ed862011-06-21 23:04:20 +00004630/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004631static QualType getSizeOfArgType(const Expr* E) {
4632 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4633 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4634 if (SizeOf->getKind() == clang::UETT_SizeOf)
4635 return SizeOf->getTypeOfArgument();
4636
4637 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004638}
4639
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004640/// \brief Check for dangerous or invalid arguments to memset().
4641///
Chandler Carruthac687262011-06-03 06:23:57 +00004642/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004643/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4644/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004645///
4646/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004647void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004648 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004649 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004650 assert(BId != 0);
4651
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004652 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004653 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004654 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004655 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004656 return;
4657
Anna Zaks22122702012-01-17 00:37:07 +00004658 unsigned LastArg = (BId == Builtin::BImemset ||
4659 BId == Builtin::BIstrndup ? 1 : 2);
4660 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004661 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004662
Nico Weber0e6daef2013-12-26 23:38:39 +00004663 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4664 Call->getLocStart(), Call->getRParenLoc()))
4665 return;
4666
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004667 // We have special checking when the length is a sizeof expression.
4668 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4669 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4670 llvm::FoldingSetNodeID SizeOfArgID;
4671
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004672 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4673 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004674 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004675
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004676 QualType DestTy = Dest->getType();
4677 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4678 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004679
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004680 // Never warn about void type pointers. This can be used to suppress
4681 // false positives.
4682 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004683 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004684
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004685 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4686 // actually comparing the expressions for equality. Because computing the
4687 // expression IDs can be expensive, we only do this if the diagnostic is
4688 // enabled.
4689 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004690 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4691 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004692 // We only compute IDs for expressions if the warning is enabled, and
4693 // cache the sizeof arg's ID.
4694 if (SizeOfArgID == llvm::FoldingSetNodeID())
4695 SizeOfArg->Profile(SizeOfArgID, Context, true);
4696 llvm::FoldingSetNodeID DestID;
4697 Dest->Profile(DestID, Context, true);
4698 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004699 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4700 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004701 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004702 StringRef ReadableName = FnName->getName();
4703
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004704 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004705 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004706 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004707 if (!PointeeTy->isIncompleteType() &&
4708 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004709 ActionIdx = 2; // If the pointee's size is sizeof(char),
4710 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004711
4712 // If the function is defined as a builtin macro, do not show macro
4713 // expansion.
4714 SourceLocation SL = SizeOfArg->getExprLoc();
4715 SourceRange DSR = Dest->getSourceRange();
4716 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004717 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004718
4719 if (SM.isMacroArgExpansion(SL)) {
4720 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4721 SL = SM.getSpellingLoc(SL);
4722 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4723 SM.getSpellingLoc(DSR.getEnd()));
4724 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4725 SM.getSpellingLoc(SSR.getEnd()));
4726 }
4727
Anna Zaksd08d9152012-05-30 23:14:52 +00004728 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004729 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004730 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004731 << PointeeTy
4732 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004733 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004734 << SSR);
4735 DiagRuntimeBehavior(SL, SizeOfArg,
4736 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4737 << ActionIdx
4738 << SSR);
4739
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004740 break;
4741 }
4742 }
4743
4744 // Also check for cases where the sizeof argument is the exact same
4745 // type as the memory argument, and where it points to a user-defined
4746 // record type.
4747 if (SizeOfArgTy != QualType()) {
4748 if (PointeeTy->isRecordType() &&
4749 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4750 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4751 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4752 << FnName << SizeOfArgTy << ArgIdx
4753 << PointeeTy << Dest->getSourceRange()
4754 << LenExpr->getSourceRange());
4755 break;
4756 }
Nico Weberc5e73862011-06-14 16:14:58 +00004757 }
4758
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004759 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004760 bool IsContained;
4761 if (const CXXRecordDecl *ContainedRD =
4762 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004763
4764 unsigned OperationType = 0;
4765 // "overwritten" if we're warning about the destination for any call
4766 // but memcmp; otherwise a verb appropriate to the call.
4767 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4768 if (BId == Builtin::BImemcpy)
4769 OperationType = 1;
4770 else if(BId == Builtin::BImemmove)
4771 OperationType = 2;
4772 else if (BId == Builtin::BImemcmp)
4773 OperationType = 3;
4774 }
4775
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004776 DiagRuntimeBehavior(
4777 Dest->getExprLoc(), Dest,
4778 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004779 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004780 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004781 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004782 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4783 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004784 DiagRuntimeBehavior(
4785 Dest->getExprLoc(), Dest,
4786 PDiag(diag::warn_arc_object_memaccess)
4787 << ArgIdx << FnName << PointeeTy
4788 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004789 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004790 continue;
John McCall31168b02011-06-15 23:02:42 +00004791
4792 DiagRuntimeBehavior(
4793 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004794 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004795 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4796 break;
4797 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004798 }
4799}
4800
Ted Kremenek6865f772011-08-18 20:55:45 +00004801// A little helper routine: ignore addition and subtraction of integer literals.
4802// This intentionally does not ignore all integer constant expressions because
4803// we don't want to remove sizeof().
4804static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4805 Ex = Ex->IgnoreParenCasts();
4806
4807 for (;;) {
4808 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4809 if (!BO || !BO->isAdditiveOp())
4810 break;
4811
4812 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4813 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4814
4815 if (isa<IntegerLiteral>(RHS))
4816 Ex = LHS;
4817 else if (isa<IntegerLiteral>(LHS))
4818 Ex = RHS;
4819 else
4820 break;
4821 }
4822
4823 return Ex;
4824}
4825
Anna Zaks13b08572012-08-08 21:42:23 +00004826static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4827 ASTContext &Context) {
4828 // Only handle constant-sized or VLAs, but not flexible members.
4829 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4830 // Only issue the FIXIT for arrays of size > 1.
4831 if (CAT->getSize().getSExtValue() <= 1)
4832 return false;
4833 } else if (!Ty->isVariableArrayType()) {
4834 return false;
4835 }
4836 return true;
4837}
4838
Ted Kremenek6865f772011-08-18 20:55:45 +00004839// Warn if the user has made the 'size' argument to strlcpy or strlcat
4840// be the size of the source, instead of the destination.
4841void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4842 IdentifierInfo *FnName) {
4843
4844 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004845 unsigned NumArgs = Call->getNumArgs();
4846 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004847 return;
4848
4849 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4850 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004851 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004852
4853 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4854 Call->getLocStart(), Call->getRParenLoc()))
4855 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004856
4857 // Look for 'strlcpy(dst, x, sizeof(x))'
4858 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4859 CompareWithSrc = Ex;
4860 else {
4861 // Look for 'strlcpy(dst, x, strlen(x))'
4862 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004863 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4864 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004865 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4866 }
4867 }
4868
4869 if (!CompareWithSrc)
4870 return;
4871
4872 // Determine if the argument to sizeof/strlen is equal to the source
4873 // argument. In principle there's all kinds of things you could do
4874 // here, for instance creating an == expression and evaluating it with
4875 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4876 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4877 if (!SrcArgDRE)
4878 return;
4879
4880 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4881 if (!CompareWithSrcDRE ||
4882 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4883 return;
4884
4885 const Expr *OriginalSizeArg = Call->getArg(2);
4886 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4887 << OriginalSizeArg->getSourceRange() << FnName;
4888
4889 // Output a FIXIT hint if the destination is an array (rather than a
4890 // pointer to an array). This could be enhanced to handle some
4891 // pointers if we know the actual size, like if DstArg is 'array+2'
4892 // we could say 'sizeof(array)-2'.
4893 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004894 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004895 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004896
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004897 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004898 llvm::raw_svector_ostream OS(sizeString);
4899 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004900 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004901 OS << ")";
4902
4903 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4904 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4905 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004906}
4907
Anna Zaks314cd092012-02-01 19:08:57 +00004908/// Check if two expressions refer to the same declaration.
4909static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4910 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4911 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4912 return D1->getDecl() == D2->getDecl();
4913 return false;
4914}
4915
4916static const Expr *getStrlenExprArg(const Expr *E) {
4917 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4918 const FunctionDecl *FD = CE->getDirectCallee();
4919 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004920 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004921 return CE->getArg(0)->IgnoreParenCasts();
4922 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004923 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004924}
4925
4926// Warn on anti-patterns as the 'size' argument to strncat.
4927// The correct size argument should look like following:
4928// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4929void Sema::CheckStrncatArguments(const CallExpr *CE,
4930 IdentifierInfo *FnName) {
4931 // Don't crash if the user has the wrong number of arguments.
4932 if (CE->getNumArgs() < 3)
4933 return;
4934 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4935 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4936 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4937
Nico Weber0e6daef2013-12-26 23:38:39 +00004938 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4939 CE->getRParenLoc()))
4940 return;
4941
Anna Zaks314cd092012-02-01 19:08:57 +00004942 // Identify common expressions, which are wrongly used as the size argument
4943 // to strncat and may lead to buffer overflows.
4944 unsigned PatternType = 0;
4945 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4946 // - sizeof(dst)
4947 if (referToTheSameDecl(SizeOfArg, DstArg))
4948 PatternType = 1;
4949 // - sizeof(src)
4950 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4951 PatternType = 2;
4952 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4953 if (BE->getOpcode() == BO_Sub) {
4954 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4955 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4956 // - sizeof(dst) - strlen(dst)
4957 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4958 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4959 PatternType = 1;
4960 // - sizeof(src) - (anything)
4961 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4962 PatternType = 2;
4963 }
4964 }
4965
4966 if (PatternType == 0)
4967 return;
4968
Anna Zaks5069aa32012-02-03 01:27:37 +00004969 // Generate the diagnostic.
4970 SourceLocation SL = LenArg->getLocStart();
4971 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004972 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004973
4974 // If the function is defined as a builtin macro, do not show macro expansion.
4975 if (SM.isMacroArgExpansion(SL)) {
4976 SL = SM.getSpellingLoc(SL);
4977 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4978 SM.getSpellingLoc(SR.getEnd()));
4979 }
4980
Anna Zaks13b08572012-08-08 21:42:23 +00004981 // Check if the destination is an array (rather than a pointer to an array).
4982 QualType DstTy = DstArg->getType();
4983 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4984 Context);
4985 if (!isKnownSizeArray) {
4986 if (PatternType == 1)
4987 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4988 else
4989 Diag(SL, diag::warn_strncat_src_size) << SR;
4990 return;
4991 }
4992
Anna Zaks314cd092012-02-01 19:08:57 +00004993 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004994 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004995 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004996 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004997
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004998 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004999 llvm::raw_svector_ostream OS(sizeString);
5000 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005001 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005002 OS << ") - ";
5003 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005004 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005005 OS << ") - 1";
5006
Anna Zaks5069aa32012-02-03 01:27:37 +00005007 Diag(SL, diag::note_strncat_wrong_size)
5008 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005009}
5010
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005011//===--- CHECK: Return Address of Stack Variable --------------------------===//
5012
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005013static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5014 Decl *ParentDecl);
5015static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5016 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005017
5018/// CheckReturnStackAddr - Check if a return statement returns the address
5019/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005020static void
5021CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5022 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005023
Craig Topperc3ec1492014-05-26 06:22:03 +00005024 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005025 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005026
5027 // Perform checking for returned stack addresses, local blocks,
5028 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005029 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005030 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005031 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005032 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005033 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005034 }
5035
Craig Topperc3ec1492014-05-26 06:22:03 +00005036 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005037 return; // Nothing suspicious was found.
5038
5039 SourceLocation diagLoc;
5040 SourceRange diagRange;
5041 if (refVars.empty()) {
5042 diagLoc = stackE->getLocStart();
5043 diagRange = stackE->getSourceRange();
5044 } else {
5045 // We followed through a reference variable. 'stackE' contains the
5046 // problematic expression but we will warn at the return statement pointing
5047 // at the reference variable. We will later display the "trail" of
5048 // reference variables using notes.
5049 diagLoc = refVars[0]->getLocStart();
5050 diagRange = refVars[0]->getSourceRange();
5051 }
5052
5053 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005054 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005055 : diag::warn_ret_stack_addr)
5056 << DR->getDecl()->getDeclName() << diagRange;
5057 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005058 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005059 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005060 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005061 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005062 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5063 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005064 << diagRange;
5065 }
5066
5067 // Display the "trail" of reference variables that we followed until we
5068 // found the problematic expression using notes.
5069 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5070 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5071 // If this var binds to another reference var, show the range of the next
5072 // var, otherwise the var binds to the problematic expression, in which case
5073 // show the range of the expression.
5074 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5075 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005076 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5077 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005078 }
5079}
5080
5081/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5082/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005083/// to a location on the stack, a local block, an address of a label, or a
5084/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005085/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005086/// encounter a subexpression that (1) clearly does not lead to one of the
5087/// above problematic expressions (2) is something we cannot determine leads to
5088/// a problematic expression based on such local checking.
5089///
5090/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5091/// the expression that they point to. Such variables are added to the
5092/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005093///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005094/// EvalAddr processes expressions that are pointers that are used as
5095/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005096/// At the base case of the recursion is a check for the above problematic
5097/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005098///
5099/// This implementation handles:
5100///
5101/// * pointer-to-pointer casts
5102/// * implicit conversions from array references to pointers
5103/// * taking the address of fields
5104/// * arbitrary interplay between "&" and "*" operators
5105/// * pointer arithmetic from an address of a stack variable
5106/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005107static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5108 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005109 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005110 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005111
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005112 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005113 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005114 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005115 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005116 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005117
Peter Collingbourne91147592011-04-15 00:35:48 +00005118 E = E->IgnoreParens();
5119
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005120 // Our "symbolic interpreter" is just a dispatch off the currently
5121 // viewed AST node. We then recursively traverse the AST by calling
5122 // EvalAddr and EvalVal appropriately.
5123 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005124 case Stmt::DeclRefExprClass: {
5125 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5126
Richard Smith40f08eb2014-01-30 22:05:38 +00005127 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005128 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005129 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005130
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005131 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5132 // If this is a reference variable, follow through to the expression that
5133 // it points to.
5134 if (V->hasLocalStorage() &&
5135 V->getType()->isReferenceType() && V->hasInit()) {
5136 // Add the reference variable to the "trail".
5137 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005138 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005139 }
5140
Craig Topperc3ec1492014-05-26 06:22:03 +00005141 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005142 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005143
Chris Lattner934edb22007-12-28 05:31:15 +00005144 case Stmt::UnaryOperatorClass: {
5145 // The only unary operator that make sense to handle here
5146 // is AddrOf. All others don't make sense as pointers.
5147 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005148
John McCalle3027922010-08-25 11:45:40 +00005149 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005150 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005151 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005152 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005153 }
Mike Stump11289f42009-09-09 15:08:12 +00005154
Chris Lattner934edb22007-12-28 05:31:15 +00005155 case Stmt::BinaryOperatorClass: {
5156 // Handle pointer arithmetic. All other binary operators are not valid
5157 // in this context.
5158 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005159 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005160
John McCalle3027922010-08-25 11:45:40 +00005161 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005162 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005163
Chris Lattner934edb22007-12-28 05:31:15 +00005164 Expr *Base = B->getLHS();
5165
5166 // Determine which argument is the real pointer base. It could be
5167 // the RHS argument instead of the LHS.
5168 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005169
Chris Lattner934edb22007-12-28 05:31:15 +00005170 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005171 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005172 }
Steve Naroff2752a172008-09-10 19:17:48 +00005173
Chris Lattner934edb22007-12-28 05:31:15 +00005174 // For conditional operators we need to see if either the LHS or RHS are
5175 // valid DeclRefExpr*s. If one of them is valid, we return it.
5176 case Stmt::ConditionalOperatorClass: {
5177 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005178
Chris Lattner934edb22007-12-28 05:31:15 +00005179 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005180 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5181 if (Expr *LHSExpr = C->getLHS()) {
5182 // In C++, we can have a throw-expression, which has 'void' type.
5183 if (!LHSExpr->getType()->isVoidType())
5184 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005185 return LHS;
5186 }
Chris Lattner934edb22007-12-28 05:31:15 +00005187
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005188 // In C++, we can have a throw-expression, which has 'void' type.
5189 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005190 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005191
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005192 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005193 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005194
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005195 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005196 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005197 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005198 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005199
5200 case Stmt::AddrLabelExprClass:
5201 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005202
John McCall28fc7092011-11-10 05:35:25 +00005203 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005204 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5205 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005206
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005207 // For casts, we need to handle conversions from arrays to
5208 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005209 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005210 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005211 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005212 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005213 case Stmt::CXXStaticCastExprClass:
5214 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005215 case Stmt::CXXConstCastExprClass:
5216 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005217 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5218 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005219 case CK_LValueToRValue:
5220 case CK_NoOp:
5221 case CK_BaseToDerived:
5222 case CK_DerivedToBase:
5223 case CK_UncheckedDerivedToBase:
5224 case CK_Dynamic:
5225 case CK_CPointerToObjCPointerCast:
5226 case CK_BlockPointerToObjCPointerCast:
5227 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005228 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005229
5230 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005231 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005232
Richard Trieudadefde2014-07-02 04:39:38 +00005233 case CK_BitCast:
5234 if (SubExpr->getType()->isAnyPointerType() ||
5235 SubExpr->getType()->isBlockPointerType() ||
5236 SubExpr->getType()->isObjCQualifiedIdType())
5237 return EvalAddr(SubExpr, refVars, ParentDecl);
5238 else
5239 return nullptr;
5240
Eli Friedman8195ad72012-02-23 23:04:32 +00005241 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005242 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005243 }
Chris Lattner934edb22007-12-28 05:31:15 +00005244 }
Mike Stump11289f42009-09-09 15:08:12 +00005245
Douglas Gregorfe314812011-06-21 17:03:29 +00005246 case Stmt::MaterializeTemporaryExprClass:
5247 if (Expr *Result = EvalAddr(
5248 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005249 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005250 return Result;
5251
5252 return E;
5253
Chris Lattner934edb22007-12-28 05:31:15 +00005254 // Everything else: we simply don't reason about them.
5255 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005256 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005257 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005258}
Mike Stump11289f42009-09-09 15:08:12 +00005259
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005260
5261/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5262/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005263static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5264 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005265do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005266 // We should only be called for evaluating non-pointer expressions, or
5267 // expressions with a pointer type that are not used as references but instead
5268 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005269
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005270 // Our "symbolic interpreter" is just a dispatch off the currently
5271 // viewed AST node. We then recursively traverse the AST by calling
5272 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005273
5274 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005275 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005276 case Stmt::ImplicitCastExprClass: {
5277 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005278 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005279 E = IE->getSubExpr();
5280 continue;
5281 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005282 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005283 }
5284
John McCall28fc7092011-11-10 05:35:25 +00005285 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005286 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005287
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005288 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005289 // When we hit a DeclRefExpr we are looking at code that refers to a
5290 // variable's name. If it's not a reference variable we check if it has
5291 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005292 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005293
Richard Smith40f08eb2014-01-30 22:05:38 +00005294 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005295 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005296 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005297
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005298 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5299 // Check if it refers to itself, e.g. "int& i = i;".
5300 if (V == ParentDecl)
5301 return DR;
5302
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005303 if (V->hasLocalStorage()) {
5304 if (!V->getType()->isReferenceType())
5305 return DR;
5306
5307 // Reference variable, follow through to the expression that
5308 // it points to.
5309 if (V->hasInit()) {
5310 // Add the reference variable to the "trail".
5311 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005312 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005313 }
5314 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005315 }
Mike Stump11289f42009-09-09 15:08:12 +00005316
Craig Topperc3ec1492014-05-26 06:22:03 +00005317 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005318 }
Mike Stump11289f42009-09-09 15:08:12 +00005319
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005320 case Stmt::UnaryOperatorClass: {
5321 // The only unary operator that make sense to handle here
5322 // is Deref. All others don't resolve to a "name." This includes
5323 // handling all sorts of rvalues passed to a unary operator.
5324 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005325
John McCalle3027922010-08-25 11:45:40 +00005326 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005327 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005328
Craig Topperc3ec1492014-05-26 06:22:03 +00005329 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005330 }
Mike Stump11289f42009-09-09 15:08:12 +00005331
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005332 case Stmt::ArraySubscriptExprClass: {
5333 // Array subscripts are potential references to data on the stack. We
5334 // retrieve the DeclRefExpr* for the array variable if it indeed
5335 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005336 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005337 }
Mike Stump11289f42009-09-09 15:08:12 +00005338
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005339 case Stmt::ConditionalOperatorClass: {
5340 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005341 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005342 ConditionalOperator *C = cast<ConditionalOperator>(E);
5343
Anders Carlsson801c5c72007-11-30 19:04:31 +00005344 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005345 if (Expr *LHSExpr = C->getLHS()) {
5346 // In C++, we can have a throw-expression, which has 'void' type.
5347 if (!LHSExpr->getType()->isVoidType())
5348 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5349 return LHS;
5350 }
5351
5352 // In C++, we can have a throw-expression, which has 'void' type.
5353 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005354 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005355
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005356 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005357 }
Mike Stump11289f42009-09-09 15:08:12 +00005358
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005359 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005360 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005361 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005362
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005363 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005364 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005365 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005366
5367 // Check whether the member type is itself a reference, in which case
5368 // we're not going to refer to the member, but to what the member refers to.
5369 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005370 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005371
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005372 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005373 }
Mike Stump11289f42009-09-09 15:08:12 +00005374
Douglas Gregorfe314812011-06-21 17:03:29 +00005375 case Stmt::MaterializeTemporaryExprClass:
5376 if (Expr *Result = EvalVal(
5377 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005378 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005379 return Result;
5380
5381 return E;
5382
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005383 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005384 // Check that we don't return or take the address of a reference to a
5385 // temporary. This is only useful in C++.
5386 if (!E->isTypeDependent() && E->isRValue())
5387 return E;
5388
5389 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005390 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005391 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005392} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005393}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005394
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005395void
5396Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5397 SourceLocation ReturnLoc,
5398 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005399 const AttrVec *Attrs,
5400 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005401 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5402
5403 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005404 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5405 CheckNonNullExpr(*this, RetValExp))
5406 Diag(ReturnLoc, diag::warn_null_ret)
5407 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005408
5409 // C++11 [basic.stc.dynamic.allocation]p4:
5410 // If an allocation function declared with a non-throwing
5411 // exception-specification fails to allocate storage, it shall return
5412 // a null pointer. Any other allocation function that fails to allocate
5413 // storage shall indicate failure only by throwing an exception [...]
5414 if (FD) {
5415 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5416 if (Op == OO_New || Op == OO_Array_New) {
5417 const FunctionProtoType *Proto
5418 = FD->getType()->castAs<FunctionProtoType>();
5419 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5420 CheckNonNullExpr(*this, RetValExp))
5421 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5422 << FD << getLangOpts().CPlusPlus11;
5423 }
5424 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005425}
5426
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005427//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5428
5429/// Check for comparisons of floating point operands using != and ==.
5430/// Issue a warning if these are no self-comparisons, as they are not likely
5431/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005432void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005433 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5434 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005435
5436 // Special case: check for x == x (which is OK).
5437 // Do not emit warnings for such cases.
5438 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5439 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5440 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005441 return;
Mike Stump11289f42009-09-09 15:08:12 +00005442
5443
Ted Kremenekeda40e22007-11-29 00:59:04 +00005444 // Special case: check for comparisons against literals that can be exactly
5445 // represented by APFloat. In such cases, do not emit a warning. This
5446 // is a heuristic: often comparison against such literals are used to
5447 // detect if a value in a variable has not changed. This clearly can
5448 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005449 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5450 if (FLL->isExact())
5451 return;
5452 } else
5453 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5454 if (FLR->isExact())
5455 return;
Mike Stump11289f42009-09-09 15:08:12 +00005456
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005457 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005458 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005459 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005460 return;
Mike Stump11289f42009-09-09 15:08:12 +00005461
David Blaikie1f4ff152012-07-16 20:47:22 +00005462 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005463 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005464 return;
Mike Stump11289f42009-09-09 15:08:12 +00005465
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005466 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005467 Diag(Loc, diag::warn_floatingpoint_eq)
5468 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005469}
John McCallca01b222010-01-04 23:21:16 +00005470
John McCall70aa5392010-01-06 05:24:50 +00005471//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5472//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005473
John McCall70aa5392010-01-06 05:24:50 +00005474namespace {
John McCallca01b222010-01-04 23:21:16 +00005475
John McCall70aa5392010-01-06 05:24:50 +00005476/// Structure recording the 'active' range of an integer-valued
5477/// expression.
5478struct IntRange {
5479 /// The number of bits active in the int.
5480 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005481
John McCall70aa5392010-01-06 05:24:50 +00005482 /// True if the int is known not to have negative values.
5483 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005484
John McCall70aa5392010-01-06 05:24:50 +00005485 IntRange(unsigned Width, bool NonNegative)
5486 : Width(Width), NonNegative(NonNegative)
5487 {}
John McCallca01b222010-01-04 23:21:16 +00005488
John McCall817d4af2010-11-10 23:38:19 +00005489 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005490 static IntRange forBoolType() {
5491 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005492 }
5493
John McCall817d4af2010-11-10 23:38:19 +00005494 /// Returns the range of an opaque value of the given integral type.
5495 static IntRange forValueOfType(ASTContext &C, QualType T) {
5496 return forValueOfCanonicalType(C,
5497 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005498 }
5499
John McCall817d4af2010-11-10 23:38:19 +00005500 /// Returns the range of an opaque value of a canonical integral type.
5501 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005502 assert(T->isCanonicalUnqualified());
5503
5504 if (const VectorType *VT = dyn_cast<VectorType>(T))
5505 T = VT->getElementType().getTypePtr();
5506 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5507 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005508 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5509 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005510
David Majnemer6a426652013-06-07 22:07:20 +00005511 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005512 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005513 EnumDecl *Enum = ET->getDecl();
5514 if (!Enum->isCompleteDefinition())
5515 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005516
David Majnemer6a426652013-06-07 22:07:20 +00005517 unsigned NumPositive = Enum->getNumPositiveBits();
5518 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005519
David Majnemer6a426652013-06-07 22:07:20 +00005520 if (NumNegative == 0)
5521 return IntRange(NumPositive, true/*NonNegative*/);
5522 else
5523 return IntRange(std::max(NumPositive + 1, NumNegative),
5524 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005525 }
John McCall70aa5392010-01-06 05:24:50 +00005526
5527 const BuiltinType *BT = cast<BuiltinType>(T);
5528 assert(BT->isInteger());
5529
5530 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5531 }
5532
John McCall817d4af2010-11-10 23:38:19 +00005533 /// Returns the "target" range of a canonical integral type, i.e.
5534 /// the range of values expressible in the type.
5535 ///
5536 /// This matches forValueOfCanonicalType except that enums have the
5537 /// full range of their type, not the range of their enumerators.
5538 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5539 assert(T->isCanonicalUnqualified());
5540
5541 if (const VectorType *VT = dyn_cast<VectorType>(T))
5542 T = VT->getElementType().getTypePtr();
5543 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5544 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005545 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5546 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005547 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005548 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005549
5550 const BuiltinType *BT = cast<BuiltinType>(T);
5551 assert(BT->isInteger());
5552
5553 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5554 }
5555
5556 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005557 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005558 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005559 L.NonNegative && R.NonNegative);
5560 }
5561
John McCall817d4af2010-11-10 23:38:19 +00005562 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005563 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005564 return IntRange(std::min(L.Width, R.Width),
5565 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005566 }
5567};
5568
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005569static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5570 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005571 if (value.isSigned() && value.isNegative())
5572 return IntRange(value.getMinSignedBits(), false);
5573
5574 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005575 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005576
5577 // isNonNegative() just checks the sign bit without considering
5578 // signedness.
5579 return IntRange(value.getActiveBits(), true);
5580}
5581
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005582static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5583 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005584 if (result.isInt())
5585 return GetValueRange(C, result.getInt(), MaxWidth);
5586
5587 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005588 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5589 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5590 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5591 R = IntRange::join(R, El);
5592 }
John McCall70aa5392010-01-06 05:24:50 +00005593 return R;
5594 }
5595
5596 if (result.isComplexInt()) {
5597 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5598 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5599 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005600 }
5601
5602 // This can happen with lossless casts to intptr_t of "based" lvalues.
5603 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005604 // FIXME: The only reason we need to pass the type in here is to get
5605 // the sign right on this one case. It would be nice if APValue
5606 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005607 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005608 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005609}
John McCall70aa5392010-01-06 05:24:50 +00005610
Eli Friedmane6d33952013-07-08 20:20:06 +00005611static QualType GetExprType(Expr *E) {
5612 QualType Ty = E->getType();
5613 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5614 Ty = AtomicRHS->getValueType();
5615 return Ty;
5616}
5617
John McCall70aa5392010-01-06 05:24:50 +00005618/// Pseudo-evaluate the given integer expression, estimating the
5619/// range of values it might take.
5620///
5621/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005622static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005623 E = E->IgnoreParens();
5624
5625 // Try a full evaluation first.
5626 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005627 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005628 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005629
5630 // I think we only want to look through implicit casts here; if the
5631 // user has an explicit widening cast, we should treat the value as
5632 // being of the new, wider type.
5633 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005634 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005635 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5636
Eli Friedmane6d33952013-07-08 20:20:06 +00005637 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005638
John McCalle3027922010-08-25 11:45:40 +00005639 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005640
John McCall70aa5392010-01-06 05:24:50 +00005641 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005642 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005643 return OutputTypeRange;
5644
5645 IntRange SubRange
5646 = GetExprRange(C, CE->getSubExpr(),
5647 std::min(MaxWidth, OutputTypeRange.Width));
5648
5649 // Bail out if the subexpr's range is as wide as the cast type.
5650 if (SubRange.Width >= OutputTypeRange.Width)
5651 return OutputTypeRange;
5652
5653 // Otherwise, we take the smaller width, and we're non-negative if
5654 // either the output type or the subexpr is.
5655 return IntRange(SubRange.Width,
5656 SubRange.NonNegative || OutputTypeRange.NonNegative);
5657 }
5658
5659 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5660 // If we can fold the condition, just take that operand.
5661 bool CondResult;
5662 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5663 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5664 : CO->getFalseExpr(),
5665 MaxWidth);
5666
5667 // Otherwise, conservatively merge.
5668 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5669 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5670 return IntRange::join(L, R);
5671 }
5672
5673 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5674 switch (BO->getOpcode()) {
5675
5676 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005677 case BO_LAnd:
5678 case BO_LOr:
5679 case BO_LT:
5680 case BO_GT:
5681 case BO_LE:
5682 case BO_GE:
5683 case BO_EQ:
5684 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005685 return IntRange::forBoolType();
5686
John McCallc3688382011-07-13 06:35:24 +00005687 // The type of the assignments is the type of the LHS, so the RHS
5688 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005689 case BO_MulAssign:
5690 case BO_DivAssign:
5691 case BO_RemAssign:
5692 case BO_AddAssign:
5693 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005694 case BO_XorAssign:
5695 case BO_OrAssign:
5696 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005697 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005698
John McCallc3688382011-07-13 06:35:24 +00005699 // Simple assignments just pass through the RHS, which will have
5700 // been coerced to the LHS type.
5701 case BO_Assign:
5702 // TODO: bitfields?
5703 return GetExprRange(C, BO->getRHS(), MaxWidth);
5704
John McCall70aa5392010-01-06 05:24:50 +00005705 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005706 case BO_PtrMemD:
5707 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005708 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005709
John McCall2ce81ad2010-01-06 22:07:33 +00005710 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005711 case BO_And:
5712 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005713 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5714 GetExprRange(C, BO->getRHS(), MaxWidth));
5715
John McCall70aa5392010-01-06 05:24:50 +00005716 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005717 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005718 // ...except that we want to treat '1 << (blah)' as logically
5719 // positive. It's an important idiom.
5720 if (IntegerLiteral *I
5721 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5722 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005723 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005724 return IntRange(R.Width, /*NonNegative*/ true);
5725 }
5726 }
5727 // fallthrough
5728
John McCalle3027922010-08-25 11:45:40 +00005729 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005730 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005731
John McCall2ce81ad2010-01-06 22:07:33 +00005732 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005733 case BO_Shr:
5734 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005735 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5736
5737 // If the shift amount is a positive constant, drop the width by
5738 // that much.
5739 llvm::APSInt shift;
5740 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5741 shift.isNonNegative()) {
5742 unsigned zext = shift.getZExtValue();
5743 if (zext >= L.Width)
5744 L.Width = (L.NonNegative ? 0 : 1);
5745 else
5746 L.Width -= zext;
5747 }
5748
5749 return L;
5750 }
5751
5752 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005753 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005754 return GetExprRange(C, BO->getRHS(), MaxWidth);
5755
John McCall2ce81ad2010-01-06 22:07:33 +00005756 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005757 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005758 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005759 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005760 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005761
John McCall51431812011-07-14 22:39:48 +00005762 // The width of a division result is mostly determined by the size
5763 // of the LHS.
5764 case BO_Div: {
5765 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005766 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005767 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5768
5769 // If the divisor is constant, use that.
5770 llvm::APSInt divisor;
5771 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5772 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5773 if (log2 >= L.Width)
5774 L.Width = (L.NonNegative ? 0 : 1);
5775 else
5776 L.Width = std::min(L.Width - log2, MaxWidth);
5777 return L;
5778 }
5779
5780 // Otherwise, just use the LHS's width.
5781 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5782 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5783 }
5784
5785 // The result of a remainder can't be larger than the result of
5786 // either side.
5787 case BO_Rem: {
5788 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005789 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005790 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5791 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5792
5793 IntRange meet = IntRange::meet(L, R);
5794 meet.Width = std::min(meet.Width, MaxWidth);
5795 return meet;
5796 }
5797
5798 // The default behavior is okay for these.
5799 case BO_Mul:
5800 case BO_Add:
5801 case BO_Xor:
5802 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005803 break;
5804 }
5805
John McCall51431812011-07-14 22:39:48 +00005806 // The default case is to treat the operation as if it were closed
5807 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005808 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5809 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5810 return IntRange::join(L, R);
5811 }
5812
5813 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5814 switch (UO->getOpcode()) {
5815 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005816 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005817 return IntRange::forBoolType();
5818
5819 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005820 case UO_Deref:
5821 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005822 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005823
5824 default:
5825 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5826 }
5827 }
5828
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005829 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5830 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5831
John McCalld25db7e2013-05-06 21:39:12 +00005832 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005833 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005834 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005835
Eli Friedmane6d33952013-07-08 20:20:06 +00005836 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005837}
John McCall263a48b2010-01-04 23:31:57 +00005838
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005839static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005840 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005841}
5842
John McCall263a48b2010-01-04 23:31:57 +00005843/// Checks whether the given value, which currently has the given
5844/// source semantics, has the same value when coerced through the
5845/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005846static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5847 const llvm::fltSemantics &Src,
5848 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005849 llvm::APFloat truncated = value;
5850
5851 bool ignored;
5852 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5853 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5854
5855 return truncated.bitwiseIsEqual(value);
5856}
5857
5858/// Checks whether the given value, which currently has the given
5859/// source semantics, has the same value when coerced through the
5860/// target semantics.
5861///
5862/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005863static bool IsSameFloatAfterCast(const APValue &value,
5864 const llvm::fltSemantics &Src,
5865 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005866 if (value.isFloat())
5867 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5868
5869 if (value.isVector()) {
5870 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5871 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5872 return false;
5873 return true;
5874 }
5875
5876 assert(value.isComplexFloat());
5877 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5878 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5879}
5880
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005881static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005882
Ted Kremenek6274be42010-09-23 21:43:44 +00005883static bool IsZero(Sema &S, Expr *E) {
5884 // Suppress cases where we are comparing against an enum constant.
5885 if (const DeclRefExpr *DR =
5886 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5887 if (isa<EnumConstantDecl>(DR->getDecl()))
5888 return false;
5889
5890 // Suppress cases where the '0' value is expanded from a macro.
5891 if (E->getLocStart().isMacroID())
5892 return false;
5893
John McCallcc7e5bf2010-05-06 08:58:33 +00005894 llvm::APSInt Value;
5895 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5896}
5897
John McCall2551c1b2010-10-06 00:25:24 +00005898static bool HasEnumType(Expr *E) {
5899 // Strip off implicit integral promotions.
5900 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005901 if (ICE->getCastKind() != CK_IntegralCast &&
5902 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005903 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005904 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005905 }
5906
5907 return E->getType()->isEnumeralType();
5908}
5909
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005910static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005911 // Disable warning in template instantiations.
5912 if (!S.ActiveTemplateInstantiations.empty())
5913 return;
5914
John McCalle3027922010-08-25 11:45:40 +00005915 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005916 if (E->isValueDependent())
5917 return;
5918
John McCalle3027922010-08-25 11:45:40 +00005919 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005920 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005921 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005922 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005923 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005924 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005925 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005926 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005927 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005928 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005929 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005930 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005931 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005932 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005933 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005934 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5935 }
5936}
5937
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005938static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005939 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005940 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005941 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005942 // Disable warning in template instantiations.
5943 if (!S.ActiveTemplateInstantiations.empty())
5944 return;
5945
Richard Trieu0f097742014-04-04 04:13:47 +00005946 // TODO: Investigate using GetExprRange() to get tighter bounds
5947 // on the bit ranges.
5948 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005949 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5950 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005951 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5952 unsigned OtherWidth = OtherRange.Width;
5953
5954 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5955
Richard Trieu560910c2012-11-14 22:50:24 +00005956 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005957 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005958 return;
5959
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005960 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005961 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005962
Richard Trieu0f097742014-04-04 04:13:47 +00005963 // Used for diagnostic printout.
5964 enum {
5965 LiteralConstant = 0,
5966 CXXBoolLiteralTrue,
5967 CXXBoolLiteralFalse
5968 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005969
Richard Trieu0f097742014-04-04 04:13:47 +00005970 if (!OtherIsBooleanType) {
5971 QualType ConstantT = Constant->getType();
5972 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005973
Richard Trieu0f097742014-04-04 04:13:47 +00005974 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5975 return;
5976 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5977 "comparison with non-integer type");
5978
5979 bool ConstantSigned = ConstantT->isSignedIntegerType();
5980 bool CommonSigned = CommonT->isSignedIntegerType();
5981
5982 bool EqualityOnly = false;
5983
5984 if (CommonSigned) {
5985 // The common type is signed, therefore no signed to unsigned conversion.
5986 if (!OtherRange.NonNegative) {
5987 // Check that the constant is representable in type OtherT.
5988 if (ConstantSigned) {
5989 if (OtherWidth >= Value.getMinSignedBits())
5990 return;
5991 } else { // !ConstantSigned
5992 if (OtherWidth >= Value.getActiveBits() + 1)
5993 return;
5994 }
5995 } else { // !OtherSigned
5996 // Check that the constant is representable in type OtherT.
5997 // Negative values are out of range.
5998 if (ConstantSigned) {
5999 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6000 return;
6001 } else { // !ConstantSigned
6002 if (OtherWidth >= Value.getActiveBits())
6003 return;
6004 }
Richard Trieu560910c2012-11-14 22:50:24 +00006005 }
Richard Trieu0f097742014-04-04 04:13:47 +00006006 } else { // !CommonSigned
6007 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006008 if (OtherWidth >= Value.getActiveBits())
6009 return;
Craig Toppercf360162014-06-18 05:13:11 +00006010 } else { // OtherSigned
6011 assert(!ConstantSigned &&
6012 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006013 // Check to see if the constant is representable in OtherT.
6014 if (OtherWidth > Value.getActiveBits())
6015 return;
6016 // Check to see if the constant is equivalent to a negative value
6017 // cast to CommonT.
6018 if (S.Context.getIntWidth(ConstantT) ==
6019 S.Context.getIntWidth(CommonT) &&
6020 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6021 return;
6022 // The constant value rests between values that OtherT can represent
6023 // after conversion. Relational comparison still works, but equality
6024 // comparisons will be tautological.
6025 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006026 }
6027 }
Richard Trieu0f097742014-04-04 04:13:47 +00006028
6029 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6030
6031 if (op == BO_EQ || op == BO_NE) {
6032 IsTrue = op == BO_NE;
6033 } else if (EqualityOnly) {
6034 return;
6035 } else if (RhsConstant) {
6036 if (op == BO_GT || op == BO_GE)
6037 IsTrue = !PositiveConstant;
6038 else // op == BO_LT || op == BO_LE
6039 IsTrue = PositiveConstant;
6040 } else {
6041 if (op == BO_LT || op == BO_LE)
6042 IsTrue = !PositiveConstant;
6043 else // op == BO_GT || op == BO_GE
6044 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006045 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006046 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006047 // Other isKnownToHaveBooleanValue
6048 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6049 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6050 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6051
6052 static const struct LinkedConditions {
6053 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6054 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6055 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6056 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6057 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6058 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6059
6060 } TruthTable = {
6061 // Constant on LHS. | Constant on RHS. |
6062 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6063 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6064 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6065 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6066 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6067 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6068 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6069 };
6070
6071 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6072
6073 enum ConstantValue ConstVal = Zero;
6074 if (Value.isUnsigned() || Value.isNonNegative()) {
6075 if (Value == 0) {
6076 LiteralOrBoolConstant =
6077 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6078 ConstVal = Zero;
6079 } else if (Value == 1) {
6080 LiteralOrBoolConstant =
6081 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6082 ConstVal = One;
6083 } else {
6084 LiteralOrBoolConstant = LiteralConstant;
6085 ConstVal = GT_One;
6086 }
6087 } else {
6088 ConstVal = LT_Zero;
6089 }
6090
6091 CompareBoolWithConstantResult CmpRes;
6092
6093 switch (op) {
6094 case BO_LT:
6095 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6096 break;
6097 case BO_GT:
6098 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6099 break;
6100 case BO_LE:
6101 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6102 break;
6103 case BO_GE:
6104 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6105 break;
6106 case BO_EQ:
6107 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6108 break;
6109 case BO_NE:
6110 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6111 break;
6112 default:
6113 CmpRes = Unkwn;
6114 break;
6115 }
6116
6117 if (CmpRes == AFals) {
6118 IsTrue = false;
6119 } else if (CmpRes == ATrue) {
6120 IsTrue = true;
6121 } else {
6122 return;
6123 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006124 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006125
6126 // If this is a comparison to an enum constant, include that
6127 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006128 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006129 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6130 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6131
6132 SmallString<64> PrettySourceValue;
6133 llvm::raw_svector_ostream OS(PrettySourceValue);
6134 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006135 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006136 else
6137 OS << Value;
6138
Richard Trieu0f097742014-04-04 04:13:47 +00006139 S.DiagRuntimeBehavior(
6140 E->getOperatorLoc(), E,
6141 S.PDiag(diag::warn_out_of_range_compare)
6142 << OS.str() << LiteralOrBoolConstant
6143 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6144 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006145}
6146
John McCallcc7e5bf2010-05-06 08:58:33 +00006147/// Analyze the operands of the given comparison. Implements the
6148/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006149static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006150 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6151 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006152}
John McCall263a48b2010-01-04 23:31:57 +00006153
John McCallca01b222010-01-04 23:21:16 +00006154/// \brief Implements -Wsign-compare.
6155///
Richard Trieu82402a02011-09-15 21:56:47 +00006156/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006157static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006158 // The type the comparison is being performed in.
6159 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006160
6161 // Only analyze comparison operators where both sides have been converted to
6162 // the same type.
6163 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6164 return AnalyzeImpConvsInComparison(S, E);
6165
6166 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006167 if (E->isValueDependent())
6168 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006169
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006170 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6171 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006172
6173 bool IsComparisonConstant = false;
6174
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006175 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006176 // of 'true' or 'false'.
6177 if (T->isIntegralType(S.Context)) {
6178 llvm::APSInt RHSValue;
6179 bool IsRHSIntegralLiteral =
6180 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6181 llvm::APSInt LHSValue;
6182 bool IsLHSIntegralLiteral =
6183 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6184 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6185 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6186 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6187 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6188 else
6189 IsComparisonConstant =
6190 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006191 } else if (!T->hasUnsignedIntegerRepresentation())
6192 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006193
John McCallcc7e5bf2010-05-06 08:58:33 +00006194 // We don't do anything special if this isn't an unsigned integral
6195 // comparison: we're only interested in integral comparisons, and
6196 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006197 //
6198 // We also don't care about value-dependent expressions or expressions
6199 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006200 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006201 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006202
John McCallcc7e5bf2010-05-06 08:58:33 +00006203 // Check to see if one of the (unmodified) operands is of different
6204 // signedness.
6205 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006206 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6207 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006208 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006209 signedOperand = LHS;
6210 unsignedOperand = RHS;
6211 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6212 signedOperand = RHS;
6213 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006214 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006215 CheckTrivialUnsignedComparison(S, E);
6216 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006217 }
6218
John McCallcc7e5bf2010-05-06 08:58:33 +00006219 // Otherwise, calculate the effective range of the signed operand.
6220 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006221
John McCallcc7e5bf2010-05-06 08:58:33 +00006222 // Go ahead and analyze implicit conversions in the operands. Note
6223 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006224 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6225 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006226
John McCallcc7e5bf2010-05-06 08:58:33 +00006227 // If the signed range is non-negative, -Wsign-compare won't fire,
6228 // but we should still check for comparisons which are always true
6229 // or false.
6230 if (signedRange.NonNegative)
6231 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006232
6233 // For (in)equality comparisons, if the unsigned operand is a
6234 // constant which cannot collide with a overflowed signed operand,
6235 // then reinterpreting the signed operand as unsigned will not
6236 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006237 if (E->isEqualityOp()) {
6238 unsigned comparisonWidth = S.Context.getIntWidth(T);
6239 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006240
John McCallcc7e5bf2010-05-06 08:58:33 +00006241 // We should never be unable to prove that the unsigned operand is
6242 // non-negative.
6243 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6244
6245 if (unsignedRange.Width < comparisonWidth)
6246 return;
6247 }
6248
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006249 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6250 S.PDiag(diag::warn_mixed_sign_comparison)
6251 << LHS->getType() << RHS->getType()
6252 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006253}
6254
John McCall1f425642010-11-11 03:21:53 +00006255/// Analyzes an attempt to assign the given value to a bitfield.
6256///
6257/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006258static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6259 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006260 assert(Bitfield->isBitField());
6261 if (Bitfield->isInvalidDecl())
6262 return false;
6263
John McCalldeebbcf2010-11-11 05:33:51 +00006264 // White-list bool bitfields.
6265 if (Bitfield->getType()->isBooleanType())
6266 return false;
6267
Douglas Gregor789adec2011-02-04 13:09:01 +00006268 // Ignore value- or type-dependent expressions.
6269 if (Bitfield->getBitWidth()->isValueDependent() ||
6270 Bitfield->getBitWidth()->isTypeDependent() ||
6271 Init->isValueDependent() ||
6272 Init->isTypeDependent())
6273 return false;
6274
John McCall1f425642010-11-11 03:21:53 +00006275 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6276
Richard Smith5fab0c92011-12-28 19:48:30 +00006277 llvm::APSInt Value;
6278 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006279 return false;
6280
John McCall1f425642010-11-11 03:21:53 +00006281 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006282 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006283
6284 if (OriginalWidth <= FieldWidth)
6285 return false;
6286
Eli Friedmanc267a322012-01-26 23:11:39 +00006287 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006288 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006289 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006290
Eli Friedmanc267a322012-01-26 23:11:39 +00006291 // Check whether the stored value is equal to the original value.
6292 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006293 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006294 return false;
6295
Eli Friedmanc267a322012-01-26 23:11:39 +00006296 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006297 // therefore don't strictly fit into a signed bitfield of width 1.
6298 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006299 return false;
6300
John McCall1f425642010-11-11 03:21:53 +00006301 std::string PrettyValue = Value.toString(10);
6302 std::string PrettyTrunc = TruncatedValue.toString(10);
6303
6304 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6305 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6306 << Init->getSourceRange();
6307
6308 return true;
6309}
6310
John McCalld2a53122010-11-09 23:24:47 +00006311/// Analyze the given simple or compound assignment for warning-worthy
6312/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006313static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006314 // Just recurse on the LHS.
6315 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6316
6317 // We want to recurse on the RHS as normal unless we're assigning to
6318 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006319 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006320 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006321 E->getOperatorLoc())) {
6322 // Recurse, ignoring any implicit conversions on the RHS.
6323 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6324 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006325 }
6326 }
6327
6328 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6329}
6330
John McCall263a48b2010-01-04 23:31:57 +00006331/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006332static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006333 SourceLocation CContext, unsigned diag,
6334 bool pruneControlFlow = false) {
6335 if (pruneControlFlow) {
6336 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6337 S.PDiag(diag)
6338 << SourceType << T << E->getSourceRange()
6339 << SourceRange(CContext));
6340 return;
6341 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006342 S.Diag(E->getExprLoc(), diag)
6343 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6344}
6345
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006346/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006347static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006348 SourceLocation CContext, unsigned diag,
6349 bool pruneControlFlow = false) {
6350 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006351}
6352
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006353/// Diagnose an implicit cast from a literal expression. Does not warn when the
6354/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006355void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6356 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006357 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006358 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006359 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006360 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6361 T->hasUnsignedIntegerRepresentation());
6362 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006363 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006364 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006365 return;
6366
Eli Friedman07185912013-08-29 23:44:43 +00006367 // FIXME: Force the precision of the source value down so we don't print
6368 // digits which are usually useless (we don't really care here if we
6369 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6370 // would automatically print the shortest representation, but it's a bit
6371 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006372 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006373 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6374 precision = (precision * 59 + 195) / 196;
6375 Value.toString(PrettySourceValue, precision);
6376
David Blaikie9b88cc02012-05-15 17:18:27 +00006377 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006378 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6379 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6380 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006381 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006382
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006383 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006384 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6385 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006386}
6387
John McCall18a2c2c2010-11-09 22:22:12 +00006388std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6389 if (!Range.Width) return "0";
6390
6391 llvm::APSInt ValueInRange = Value;
6392 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006393 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006394 return ValueInRange.toString(10);
6395}
6396
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006397static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6398 if (!isa<ImplicitCastExpr>(Ex))
6399 return false;
6400
6401 Expr *InnerE = Ex->IgnoreParenImpCasts();
6402 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6403 const Type *Source =
6404 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6405 if (Target->isDependentType())
6406 return false;
6407
6408 const BuiltinType *FloatCandidateBT =
6409 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6410 const Type *BoolCandidateType = ToBool ? Target : Source;
6411
6412 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6413 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6414}
6415
6416void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6417 SourceLocation CC) {
6418 unsigned NumArgs = TheCall->getNumArgs();
6419 for (unsigned i = 0; i < NumArgs; ++i) {
6420 Expr *CurrA = TheCall->getArg(i);
6421 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6422 continue;
6423
6424 bool IsSwapped = ((i > 0) &&
6425 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6426 IsSwapped |= ((i < (NumArgs - 1)) &&
6427 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6428 if (IsSwapped) {
6429 // Warn on this floating-point to bool conversion.
6430 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6431 CurrA->getType(), CC,
6432 diag::warn_impcast_floating_point_to_bool);
6433 }
6434 }
6435}
6436
Richard Trieu5b993502014-10-15 03:42:06 +00006437static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6438 SourceLocation CC) {
6439 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6440 E->getExprLoc()))
6441 return;
6442
6443 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6444 const Expr::NullPointerConstantKind NullKind =
6445 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6446 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6447 return;
6448
6449 // Return if target type is a safe conversion.
6450 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6451 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6452 return;
6453
6454 SourceLocation Loc = E->getSourceRange().getBegin();
6455
6456 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6457 if (NullKind == Expr::NPCK_GNUNull) {
6458 if (Loc.isMacroID())
6459 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6460 }
6461
6462 // Only warn if the null and context location are in the same macro expansion.
6463 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6464 return;
6465
6466 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6467 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6468 << FixItHint::CreateReplacement(Loc,
6469 S.getFixItZeroLiteralForType(T, Loc));
6470}
6471
John McCallcc7e5bf2010-05-06 08:58:33 +00006472void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006473 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006474 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006475
John McCallcc7e5bf2010-05-06 08:58:33 +00006476 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6477 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6478 if (Source == Target) return;
6479 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006480
Chandler Carruthc22845a2011-07-26 05:40:03 +00006481 // If the conversion context location is invalid don't complain. We also
6482 // don't want to emit a warning if the issue occurs from the expansion of
6483 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6484 // delay this check as long as possible. Once we detect we are in that
6485 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006486 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006487 return;
6488
Richard Trieu021baa32011-09-23 20:10:00 +00006489 // Diagnose implicit casts to bool.
6490 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6491 if (isa<StringLiteral>(E))
6492 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006493 // and expressions, for instance, assert(0 && "error here"), are
6494 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006495 return DiagnoseImpCast(S, E, T, CC,
6496 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006497 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6498 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6499 // This covers the literal expressions that evaluate to Objective-C
6500 // objects.
6501 return DiagnoseImpCast(S, E, T, CC,
6502 diag::warn_impcast_objective_c_literal_to_bool);
6503 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006504 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6505 // Warn on pointer to bool conversion that is always true.
6506 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6507 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006508 }
Richard Trieu021baa32011-09-23 20:10:00 +00006509 }
John McCall263a48b2010-01-04 23:31:57 +00006510
6511 // Strip vector types.
6512 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006513 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006514 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006515 return;
John McCallacf0ee52010-10-08 02:01:28 +00006516 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006517 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006518
6519 // If the vector cast is cast between two vectors of the same size, it is
6520 // a bitcast, not a conversion.
6521 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6522 return;
John McCall263a48b2010-01-04 23:31:57 +00006523
6524 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6525 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6526 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006527 if (auto VecTy = dyn_cast<VectorType>(Target))
6528 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006529
6530 // Strip complex types.
6531 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006532 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006533 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006534 return;
6535
John McCallacf0ee52010-10-08 02:01:28 +00006536 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006537 }
John McCall263a48b2010-01-04 23:31:57 +00006538
6539 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6540 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6541 }
6542
6543 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6544 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6545
6546 // If the source is floating point...
6547 if (SourceBT && SourceBT->isFloatingPoint()) {
6548 // ...and the target is floating point...
6549 if (TargetBT && TargetBT->isFloatingPoint()) {
6550 // ...then warn if we're dropping FP rank.
6551
6552 // Builtin FP kinds are ordered by increasing FP rank.
6553 if (SourceBT->getKind() > TargetBT->getKind()) {
6554 // Don't warn about float constants that are precisely
6555 // representable in the target type.
6556 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006557 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006558 // Value might be a float, a float vector, or a float complex.
6559 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006560 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6561 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006562 return;
6563 }
6564
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006565 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006566 return;
6567
John McCallacf0ee52010-10-08 02:01:28 +00006568 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006569 }
6570 return;
6571 }
6572
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006573 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006574 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006575 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006576 return;
6577
Chandler Carruth22c7a792011-02-17 11:05:49 +00006578 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006579 // We also want to warn on, e.g., "int i = -1.234"
6580 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6581 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6582 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6583
Chandler Carruth016ef402011-04-10 08:36:24 +00006584 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6585 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006586 } else {
6587 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6588 }
6589 }
John McCall263a48b2010-01-04 23:31:57 +00006590
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006591 // If the target is bool, warn if expr is a function or method call.
6592 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6593 isa<CallExpr>(E)) {
6594 // Check last argument of function call to see if it is an
6595 // implicit cast from a type matching the type the result
6596 // is being cast to.
6597 CallExpr *CEx = cast<CallExpr>(E);
6598 unsigned NumArgs = CEx->getNumArgs();
6599 if (NumArgs > 0) {
6600 Expr *LastA = CEx->getArg(NumArgs - 1);
6601 Expr *InnerE = LastA->IgnoreParenImpCasts();
6602 const Type *InnerType =
6603 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6604 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6605 // Warn on this floating-point to bool conversion
6606 DiagnoseImpCast(S, E, T, CC,
6607 diag::warn_impcast_floating_point_to_bool);
6608 }
6609 }
6610 }
John McCall263a48b2010-01-04 23:31:57 +00006611 return;
6612 }
6613
Richard Trieu5b993502014-10-15 03:42:06 +00006614 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006615
David Blaikie9366d2b2012-06-19 21:19:06 +00006616 if (!Source->isIntegerType() || !Target->isIntegerType())
6617 return;
6618
David Blaikie7555b6a2012-05-15 16:56:36 +00006619 // TODO: remove this early return once the false positives for constant->bool
6620 // in templates, macros, etc, are reduced or removed.
6621 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6622 return;
6623
John McCallcc7e5bf2010-05-06 08:58:33 +00006624 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006625 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006626
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006627 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006628 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006629 // TODO: this should happen for bitfield stores, too.
6630 llvm::APSInt Value(32);
6631 if (E->isIntegerConstantExpr(Value, S.Context)) {
6632 if (S.SourceMgr.isInSystemMacro(CC))
6633 return;
6634
John McCall18a2c2c2010-11-09 22:22:12 +00006635 std::string PrettySourceValue = Value.toString(10);
6636 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006637
Ted Kremenek33ba9952011-10-22 02:37:33 +00006638 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6639 S.PDiag(diag::warn_impcast_integer_precision_constant)
6640 << PrettySourceValue << PrettyTargetValue
6641 << E->getType() << T << E->getSourceRange()
6642 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006643 return;
6644 }
6645
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006646 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6647 if (S.SourceMgr.isInSystemMacro(CC))
6648 return;
6649
David Blaikie9455da02012-04-12 22:40:54 +00006650 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006651 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6652 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006653 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006654 }
6655
6656 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6657 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6658 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006659
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006660 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006661 return;
6662
John McCallcc7e5bf2010-05-06 08:58:33 +00006663 unsigned DiagID = diag::warn_impcast_integer_sign;
6664
6665 // Traditionally, gcc has warned about this under -Wsign-compare.
6666 // We also want to warn about it in -Wconversion.
6667 // So if -Wconversion is off, use a completely identical diagnostic
6668 // in the sign-compare group.
6669 // The conditional-checking code will
6670 if (ICContext) {
6671 DiagID = diag::warn_impcast_integer_sign_conditional;
6672 *ICContext = true;
6673 }
6674
John McCallacf0ee52010-10-08 02:01:28 +00006675 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006676 }
6677
Douglas Gregora78f1932011-02-22 02:45:07 +00006678 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006679 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6680 // type, to give us better diagnostics.
6681 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006682 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006683 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6684 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6685 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6686 SourceType = S.Context.getTypeDeclType(Enum);
6687 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6688 }
6689 }
6690
Douglas Gregora78f1932011-02-22 02:45:07 +00006691 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6692 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006693 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6694 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006695 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006696 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006697 return;
6698
Douglas Gregor364f7db2011-03-12 00:14:31 +00006699 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006700 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006701 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006702
John McCall263a48b2010-01-04 23:31:57 +00006703 return;
6704}
6705
David Blaikie18e9ac72012-05-15 21:57:38 +00006706void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6707 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006708
6709void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006710 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006711 E = E->IgnoreParenImpCasts();
6712
6713 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006714 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006715
John McCallacf0ee52010-10-08 02:01:28 +00006716 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006717 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006718 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006719 return;
6720}
6721
David Blaikie18e9ac72012-05-15 21:57:38 +00006722void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6723 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006724 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006725
6726 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006727 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6728 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006729
6730 // If -Wconversion would have warned about either of the candidates
6731 // for a signedness conversion to the context type...
6732 if (!Suspicious) return;
6733
6734 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006735 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006736 return;
6737
John McCallcc7e5bf2010-05-06 08:58:33 +00006738 // ...then check whether it would have warned about either of the
6739 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006740 if (E->getType() == T) return;
6741
6742 Suspicious = false;
6743 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6744 E->getType(), CC, &Suspicious);
6745 if (!Suspicious)
6746 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006747 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006748}
6749
Richard Trieu65724892014-11-15 06:37:39 +00006750/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6751/// Input argument E is a logical expression.
6752static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6753 if (S.getLangOpts().Bool)
6754 return;
6755 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6756}
6757
John McCallcc7e5bf2010-05-06 08:58:33 +00006758/// AnalyzeImplicitConversions - Find and report any interesting
6759/// implicit conversions in the given expression. There are a couple
6760/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006761void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006762 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006763 Expr *E = OrigE->IgnoreParenImpCasts();
6764
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006765 if (E->isTypeDependent() || E->isValueDependent())
6766 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006767
John McCallcc7e5bf2010-05-06 08:58:33 +00006768 // For conditional operators, we analyze the arguments as if they
6769 // were being fed directly into the output.
6770 if (isa<ConditionalOperator>(E)) {
6771 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006772 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006773 return;
6774 }
6775
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006776 // Check implicit argument conversions for function calls.
6777 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6778 CheckImplicitArgumentConversions(S, Call, CC);
6779
John McCallcc7e5bf2010-05-06 08:58:33 +00006780 // Go ahead and check any implicit conversions we might have skipped.
6781 // The non-canonical typecheck is just an optimization;
6782 // CheckImplicitConversion will filter out dead implicit conversions.
6783 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006784 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006785
6786 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006787
6788 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006789 if (POE->getResultExpr())
6790 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006791 }
6792
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00006793 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
6794 if (OVE->getSourceExpr())
6795 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6796 return;
6797 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006798
John McCallcc7e5bf2010-05-06 08:58:33 +00006799 // Skip past explicit casts.
6800 if (isa<ExplicitCastExpr>(E)) {
6801 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006802 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006803 }
6804
John McCalld2a53122010-11-09 23:24:47 +00006805 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6806 // Do a somewhat different check with comparison operators.
6807 if (BO->isComparisonOp())
6808 return AnalyzeComparison(S, BO);
6809
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006810 // And with simple assignments.
6811 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006812 return AnalyzeAssignment(S, BO);
6813 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006814
6815 // These break the otherwise-useful invariant below. Fortunately,
6816 // we don't really need to recurse into them, because any internal
6817 // expressions should have been analyzed already when they were
6818 // built into statements.
6819 if (isa<StmtExpr>(E)) return;
6820
6821 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006822 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006823
6824 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006825 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006826 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006827 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006828 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006829 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006830 if (!ChildExpr)
6831 continue;
6832
Richard Trieu955231d2014-01-25 01:10:35 +00006833 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006834 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006835 // Ignore checking string literals that are in logical and operators.
6836 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006837 continue;
6838 AnalyzeImplicitConversions(S, ChildExpr, CC);
6839 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006840
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006841 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006842 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6843 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006844 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00006845
6846 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6847 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006848 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006849 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006850
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006851 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6852 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00006853 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006854}
6855
6856} // end anonymous namespace
6857
Richard Trieu3bb8b562014-02-26 02:36:06 +00006858enum {
6859 AddressOf,
6860 FunctionPointer,
6861 ArrayPointer
6862};
6863
Richard Trieuc1888e02014-06-28 23:25:37 +00006864// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6865// Returns true when emitting a warning about taking the address of a reference.
6866static bool CheckForReference(Sema &SemaRef, const Expr *E,
6867 PartialDiagnostic PD) {
6868 E = E->IgnoreParenImpCasts();
6869
6870 const FunctionDecl *FD = nullptr;
6871
6872 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6873 if (!DRE->getDecl()->getType()->isReferenceType())
6874 return false;
6875 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6876 if (!M->getMemberDecl()->getType()->isReferenceType())
6877 return false;
6878 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00006879 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00006880 return false;
6881 FD = Call->getDirectCallee();
6882 } else {
6883 return false;
6884 }
6885
6886 SemaRef.Diag(E->getExprLoc(), PD);
6887
6888 // If possible, point to location of function.
6889 if (FD) {
6890 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6891 }
6892
6893 return true;
6894}
6895
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006896// Returns true if the SourceLocation is expanded from any macro body.
6897// Returns false if the SourceLocation is invalid, is from not in a macro
6898// expansion, or is from expanded from a top-level macro argument.
6899static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6900 if (Loc.isInvalid())
6901 return false;
6902
6903 while (Loc.isMacroID()) {
6904 if (SM.isMacroBodyExpansion(Loc))
6905 return true;
6906 Loc = SM.getImmediateMacroCallerLoc(Loc);
6907 }
6908
6909 return false;
6910}
6911
Richard Trieu3bb8b562014-02-26 02:36:06 +00006912/// \brief Diagnose pointers that are always non-null.
6913/// \param E the expression containing the pointer
6914/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6915/// compared to a null pointer
6916/// \param IsEqual True when the comparison is equal to a null pointer
6917/// \param Range Extra SourceRange to highlight in the diagnostic
6918void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6919 Expr::NullPointerConstantKind NullKind,
6920 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006921 if (!E)
6922 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006923
6924 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006925 if (E->getExprLoc().isMacroID()) {
6926 const SourceManager &SM = getSourceManager();
6927 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6928 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006929 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006930 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006931 E = E->IgnoreImpCasts();
6932
6933 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6934
Richard Trieuf7432752014-06-06 21:39:26 +00006935 if (isa<CXXThisExpr>(E)) {
6936 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6937 : diag::warn_this_bool_conversion;
6938 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6939 return;
6940 }
6941
Richard Trieu3bb8b562014-02-26 02:36:06 +00006942 bool IsAddressOf = false;
6943
6944 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6945 if (UO->getOpcode() != UO_AddrOf)
6946 return;
6947 IsAddressOf = true;
6948 E = UO->getSubExpr();
6949 }
6950
Richard Trieuc1888e02014-06-28 23:25:37 +00006951 if (IsAddressOf) {
6952 unsigned DiagID = IsCompare
6953 ? diag::warn_address_of_reference_null_compare
6954 : diag::warn_address_of_reference_bool_conversion;
6955 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6956 << IsEqual;
6957 if (CheckForReference(*this, E, PD)) {
6958 return;
6959 }
6960 }
6961
Richard Trieu3bb8b562014-02-26 02:36:06 +00006962 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006963 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006964 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6965 D = R->getDecl();
6966 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6967 D = M->getMemberDecl();
6968 }
6969
6970 // Weak Decls can be null.
6971 if (!D || D->isWeak())
6972 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006973
6974 // Check for parameter decl with nonnull attribute
6975 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6976 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6977 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6978 unsigned NumArgs = FD->getNumParams();
6979 llvm::SmallBitVector AttrNonNull(NumArgs);
6980 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6981 if (!NonNull->args_size()) {
6982 AttrNonNull.set(0, NumArgs);
6983 break;
6984 }
6985 for (unsigned Val : NonNull->args()) {
6986 if (Val >= NumArgs)
6987 continue;
6988 AttrNonNull.set(Val);
6989 }
6990 }
6991 if (!AttrNonNull.empty())
6992 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00006993 if (FD->getParamDecl(i) == PV &&
6994 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006995 std::string Str;
6996 llvm::raw_string_ostream S(Str);
6997 E->printPretty(S, nullptr, getPrintingPolicy());
6998 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
6999 : diag::warn_cast_nonnull_to_bool;
7000 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7001 << Range << IsEqual;
7002 return;
7003 }
7004 }
7005 }
7006
Richard Trieu3bb8b562014-02-26 02:36:06 +00007007 QualType T = D->getType();
7008 const bool IsArray = T->isArrayType();
7009 const bool IsFunction = T->isFunctionType();
7010
Richard Trieuc1888e02014-06-28 23:25:37 +00007011 // Address of function is used to silence the function warning.
7012 if (IsAddressOf && IsFunction) {
7013 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007014 }
7015
7016 // Found nothing.
7017 if (!IsAddressOf && !IsFunction && !IsArray)
7018 return;
7019
7020 // Pretty print the expression for the diagnostic.
7021 std::string Str;
7022 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007023 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007024
7025 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7026 : diag::warn_impcast_pointer_to_bool;
7027 unsigned DiagType;
7028 if (IsAddressOf)
7029 DiagType = AddressOf;
7030 else if (IsFunction)
7031 DiagType = FunctionPointer;
7032 else if (IsArray)
7033 DiagType = ArrayPointer;
7034 else
7035 llvm_unreachable("Could not determine diagnostic.");
7036 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7037 << Range << IsEqual;
7038
7039 if (!IsFunction)
7040 return;
7041
7042 // Suggest '&' to silence the function warning.
7043 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7044 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7045
7046 // Check to see if '()' fixit should be emitted.
7047 QualType ReturnType;
7048 UnresolvedSet<4> NonTemplateOverloads;
7049 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7050 if (ReturnType.isNull())
7051 return;
7052
7053 if (IsCompare) {
7054 // There are two cases here. If there is null constant, the only suggest
7055 // for a pointer return type. If the null is 0, then suggest if the return
7056 // type is a pointer or an integer type.
7057 if (!ReturnType->isPointerType()) {
7058 if (NullKind == Expr::NPCK_ZeroExpression ||
7059 NullKind == Expr::NPCK_ZeroLiteral) {
7060 if (!ReturnType->isIntegerType())
7061 return;
7062 } else {
7063 return;
7064 }
7065 }
7066 } else { // !IsCompare
7067 // For function to bool, only suggest if the function pointer has bool
7068 // return type.
7069 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7070 return;
7071 }
7072 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007073 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007074}
7075
7076
John McCallcc7e5bf2010-05-06 08:58:33 +00007077/// Diagnoses "dangerous" implicit conversions within the given
7078/// expression (which is a full expression). Implements -Wconversion
7079/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007080///
7081/// \param CC the "context" location of the implicit conversion, i.e.
7082/// the most location of the syntactic entity requiring the implicit
7083/// conversion
7084void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007085 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007086 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007087 return;
7088
7089 // Don't diagnose for value- or type-dependent expressions.
7090 if (E->isTypeDependent() || E->isValueDependent())
7091 return;
7092
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007093 // Check for array bounds violations in cases where the check isn't triggered
7094 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7095 // ArraySubscriptExpr is on the RHS of a variable initialization.
7096 CheckArrayAccess(E);
7097
John McCallacf0ee52010-10-08 02:01:28 +00007098 // This is not the right CC for (e.g.) a variable initialization.
7099 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007100}
7101
Richard Trieu65724892014-11-15 06:37:39 +00007102/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7103/// Input argument E is a logical expression.
7104void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7105 ::CheckBoolLikeConversion(*this, E, CC);
7106}
7107
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007108/// Diagnose when expression is an integer constant expression and its evaluation
7109/// results in integer overflow
7110void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007111 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7112 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007113}
7114
Richard Smithc406cb72013-01-17 01:17:56 +00007115namespace {
7116/// \brief Visitor for expressions which looks for unsequenced operations on the
7117/// same object.
7118class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007119 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7120
Richard Smithc406cb72013-01-17 01:17:56 +00007121 /// \brief A tree of sequenced regions within an expression. Two regions are
7122 /// unsequenced if one is an ancestor or a descendent of the other. When we
7123 /// finish processing an expression with sequencing, such as a comma
7124 /// expression, we fold its tree nodes into its parent, since they are
7125 /// unsequenced with respect to nodes we will visit later.
7126 class SequenceTree {
7127 struct Value {
7128 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7129 unsigned Parent : 31;
7130 bool Merged : 1;
7131 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007132 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007133
7134 public:
7135 /// \brief A region within an expression which may be sequenced with respect
7136 /// to some other region.
7137 class Seq {
7138 explicit Seq(unsigned N) : Index(N) {}
7139 unsigned Index;
7140 friend class SequenceTree;
7141 public:
7142 Seq() : Index(0) {}
7143 };
7144
7145 SequenceTree() { Values.push_back(Value(0)); }
7146 Seq root() const { return Seq(0); }
7147
7148 /// \brief Create a new sequence of operations, which is an unsequenced
7149 /// subset of \p Parent. This sequence of operations is sequenced with
7150 /// respect to other children of \p Parent.
7151 Seq allocate(Seq Parent) {
7152 Values.push_back(Value(Parent.Index));
7153 return Seq(Values.size() - 1);
7154 }
7155
7156 /// \brief Merge a sequence of operations into its parent.
7157 void merge(Seq S) {
7158 Values[S.Index].Merged = true;
7159 }
7160
7161 /// \brief Determine whether two operations are unsequenced. This operation
7162 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7163 /// should have been merged into its parent as appropriate.
7164 bool isUnsequenced(Seq Cur, Seq Old) {
7165 unsigned C = representative(Cur.Index);
7166 unsigned Target = representative(Old.Index);
7167 while (C >= Target) {
7168 if (C == Target)
7169 return true;
7170 C = Values[C].Parent;
7171 }
7172 return false;
7173 }
7174
7175 private:
7176 /// \brief Pick a representative for a sequence.
7177 unsigned representative(unsigned K) {
7178 if (Values[K].Merged)
7179 // Perform path compression as we go.
7180 return Values[K].Parent = representative(Values[K].Parent);
7181 return K;
7182 }
7183 };
7184
7185 /// An object for which we can track unsequenced uses.
7186 typedef NamedDecl *Object;
7187
7188 /// Different flavors of object usage which we track. We only track the
7189 /// least-sequenced usage of each kind.
7190 enum UsageKind {
7191 /// A read of an object. Multiple unsequenced reads are OK.
7192 UK_Use,
7193 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007194 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007195 UK_ModAsValue,
7196 /// A modification of an object which is not sequenced before the value
7197 /// computation of the expression, such as n++.
7198 UK_ModAsSideEffect,
7199
7200 UK_Count = UK_ModAsSideEffect + 1
7201 };
7202
7203 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007204 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007205 Expr *Use;
7206 SequenceTree::Seq Seq;
7207 };
7208
7209 struct UsageInfo {
7210 UsageInfo() : Diagnosed(false) {}
7211 Usage Uses[UK_Count];
7212 /// Have we issued a diagnostic for this variable already?
7213 bool Diagnosed;
7214 };
7215 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7216
7217 Sema &SemaRef;
7218 /// Sequenced regions within the expression.
7219 SequenceTree Tree;
7220 /// Declaration modifications and references which we have seen.
7221 UsageInfoMap UsageMap;
7222 /// The region we are currently within.
7223 SequenceTree::Seq Region;
7224 /// Filled in with declarations which were modified as a side-effect
7225 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007226 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007227 /// Expressions to check later. We defer checking these to reduce
7228 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007229 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007230
7231 /// RAII object wrapping the visitation of a sequenced subexpression of an
7232 /// expression. At the end of this process, the side-effects of the evaluation
7233 /// become sequenced with respect to the value computation of the result, so
7234 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7235 /// UK_ModAsValue.
7236 struct SequencedSubexpression {
7237 SequencedSubexpression(SequenceChecker &Self)
7238 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7239 Self.ModAsSideEffect = &ModAsSideEffect;
7240 }
7241 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007242 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7243 MI != ME; ++MI) {
7244 UsageInfo &U = Self.UsageMap[MI->first];
7245 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7246 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7247 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007248 }
7249 Self.ModAsSideEffect = OldModAsSideEffect;
7250 }
7251
7252 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007253 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7254 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007255 };
7256
Richard Smith40238f02013-06-20 22:21:56 +00007257 /// RAII object wrapping the visitation of a subexpression which we might
7258 /// choose to evaluate as a constant. If any subexpression is evaluated and
7259 /// found to be non-constant, this allows us to suppress the evaluation of
7260 /// the outer expression.
7261 class EvaluationTracker {
7262 public:
7263 EvaluationTracker(SequenceChecker &Self)
7264 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7265 Self.EvalTracker = this;
7266 }
7267 ~EvaluationTracker() {
7268 Self.EvalTracker = Prev;
7269 if (Prev)
7270 Prev->EvalOK &= EvalOK;
7271 }
7272
7273 bool evaluate(const Expr *E, bool &Result) {
7274 if (!EvalOK || E->isValueDependent())
7275 return false;
7276 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7277 return EvalOK;
7278 }
7279
7280 private:
7281 SequenceChecker &Self;
7282 EvaluationTracker *Prev;
7283 bool EvalOK;
7284 } *EvalTracker;
7285
Richard Smithc406cb72013-01-17 01:17:56 +00007286 /// \brief Find the object which is produced by the specified expression,
7287 /// if any.
7288 Object getObject(Expr *E, bool Mod) const {
7289 E = E->IgnoreParenCasts();
7290 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7291 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7292 return getObject(UO->getSubExpr(), Mod);
7293 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7294 if (BO->getOpcode() == BO_Comma)
7295 return getObject(BO->getRHS(), Mod);
7296 if (Mod && BO->isAssignmentOp())
7297 return getObject(BO->getLHS(), Mod);
7298 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7299 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7300 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7301 return ME->getMemberDecl();
7302 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7303 // FIXME: If this is a reference, map through to its value.
7304 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007305 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007306 }
7307
7308 /// \brief Note that an object was modified or used by an expression.
7309 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7310 Usage &U = UI.Uses[UK];
7311 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7312 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7313 ModAsSideEffect->push_back(std::make_pair(O, U));
7314 U.Use = Ref;
7315 U.Seq = Region;
7316 }
7317 }
7318 /// \brief Check whether a modification or use conflicts with a prior usage.
7319 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7320 bool IsModMod) {
7321 if (UI.Diagnosed)
7322 return;
7323
7324 const Usage &U = UI.Uses[OtherKind];
7325 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7326 return;
7327
7328 Expr *Mod = U.Use;
7329 Expr *ModOrUse = Ref;
7330 if (OtherKind == UK_Use)
7331 std::swap(Mod, ModOrUse);
7332
7333 SemaRef.Diag(Mod->getExprLoc(),
7334 IsModMod ? diag::warn_unsequenced_mod_mod
7335 : diag::warn_unsequenced_mod_use)
7336 << O << SourceRange(ModOrUse->getExprLoc());
7337 UI.Diagnosed = true;
7338 }
7339
7340 void notePreUse(Object O, Expr *Use) {
7341 UsageInfo &U = UsageMap[O];
7342 // Uses conflict with other modifications.
7343 checkUsage(O, U, Use, UK_ModAsValue, false);
7344 }
7345 void notePostUse(Object O, Expr *Use) {
7346 UsageInfo &U = UsageMap[O];
7347 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7348 addUsage(U, O, Use, UK_Use);
7349 }
7350
7351 void notePreMod(Object O, Expr *Mod) {
7352 UsageInfo &U = UsageMap[O];
7353 // Modifications conflict with other modifications and with uses.
7354 checkUsage(O, U, Mod, UK_ModAsValue, true);
7355 checkUsage(O, U, Mod, UK_Use, false);
7356 }
7357 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7358 UsageInfo &U = UsageMap[O];
7359 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7360 addUsage(U, O, Use, UK);
7361 }
7362
7363public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007364 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007365 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7366 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007367 Visit(E);
7368 }
7369
7370 void VisitStmt(Stmt *S) {
7371 // Skip all statements which aren't expressions for now.
7372 }
7373
7374 void VisitExpr(Expr *E) {
7375 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007376 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007377 }
7378
7379 void VisitCastExpr(CastExpr *E) {
7380 Object O = Object();
7381 if (E->getCastKind() == CK_LValueToRValue)
7382 O = getObject(E->getSubExpr(), false);
7383
7384 if (O)
7385 notePreUse(O, E);
7386 VisitExpr(E);
7387 if (O)
7388 notePostUse(O, E);
7389 }
7390
7391 void VisitBinComma(BinaryOperator *BO) {
7392 // C++11 [expr.comma]p1:
7393 // Every value computation and side effect associated with the left
7394 // expression is sequenced before every value computation and side
7395 // effect associated with the right expression.
7396 SequenceTree::Seq LHS = Tree.allocate(Region);
7397 SequenceTree::Seq RHS = Tree.allocate(Region);
7398 SequenceTree::Seq OldRegion = Region;
7399
7400 {
7401 SequencedSubexpression SeqLHS(*this);
7402 Region = LHS;
7403 Visit(BO->getLHS());
7404 }
7405
7406 Region = RHS;
7407 Visit(BO->getRHS());
7408
7409 Region = OldRegion;
7410
7411 // Forget that LHS and RHS are sequenced. They are both unsequenced
7412 // with respect to other stuff.
7413 Tree.merge(LHS);
7414 Tree.merge(RHS);
7415 }
7416
7417 void VisitBinAssign(BinaryOperator *BO) {
7418 // The modification is sequenced after the value computation of the LHS
7419 // and RHS, so check it before inspecting the operands and update the
7420 // map afterwards.
7421 Object O = getObject(BO->getLHS(), true);
7422 if (!O)
7423 return VisitExpr(BO);
7424
7425 notePreMod(O, BO);
7426
7427 // C++11 [expr.ass]p7:
7428 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7429 // only once.
7430 //
7431 // Therefore, for a compound assignment operator, O is considered used
7432 // everywhere except within the evaluation of E1 itself.
7433 if (isa<CompoundAssignOperator>(BO))
7434 notePreUse(O, BO);
7435
7436 Visit(BO->getLHS());
7437
7438 if (isa<CompoundAssignOperator>(BO))
7439 notePostUse(O, BO);
7440
7441 Visit(BO->getRHS());
7442
Richard Smith83e37bee2013-06-26 23:16:51 +00007443 // C++11 [expr.ass]p1:
7444 // the assignment is sequenced [...] before the value computation of the
7445 // assignment expression.
7446 // C11 6.5.16/3 has no such rule.
7447 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7448 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007449 }
7450 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7451 VisitBinAssign(CAO);
7452 }
7453
7454 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7455 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7456 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7457 Object O = getObject(UO->getSubExpr(), true);
7458 if (!O)
7459 return VisitExpr(UO);
7460
7461 notePreMod(O, UO);
7462 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007463 // C++11 [expr.pre.incr]p1:
7464 // the expression ++x is equivalent to x+=1
7465 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7466 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007467 }
7468
7469 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7470 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7471 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7472 Object O = getObject(UO->getSubExpr(), true);
7473 if (!O)
7474 return VisitExpr(UO);
7475
7476 notePreMod(O, UO);
7477 Visit(UO->getSubExpr());
7478 notePostMod(O, UO, UK_ModAsSideEffect);
7479 }
7480
7481 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7482 void VisitBinLOr(BinaryOperator *BO) {
7483 // The side-effects of the LHS of an '&&' are sequenced before the
7484 // value computation of the RHS, and hence before the value computation
7485 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7486 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007487 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007488 {
7489 SequencedSubexpression Sequenced(*this);
7490 Visit(BO->getLHS());
7491 }
7492
7493 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007494 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007495 if (!Result)
7496 Visit(BO->getRHS());
7497 } else {
7498 // Check for unsequenced operations in the RHS, treating it as an
7499 // entirely separate evaluation.
7500 //
7501 // FIXME: If there are operations in the RHS which are unsequenced
7502 // with respect to operations outside the RHS, and those operations
7503 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007504 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007505 }
Richard Smithc406cb72013-01-17 01:17:56 +00007506 }
7507 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007508 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007509 {
7510 SequencedSubexpression Sequenced(*this);
7511 Visit(BO->getLHS());
7512 }
7513
7514 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007515 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007516 if (Result)
7517 Visit(BO->getRHS());
7518 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007519 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007520 }
Richard Smithc406cb72013-01-17 01:17:56 +00007521 }
7522
7523 // Only visit the condition, unless we can be sure which subexpression will
7524 // be chosen.
7525 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007526 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007527 {
7528 SequencedSubexpression Sequenced(*this);
7529 Visit(CO->getCond());
7530 }
Richard Smithc406cb72013-01-17 01:17:56 +00007531
7532 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007533 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007534 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007535 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007536 WorkList.push_back(CO->getTrueExpr());
7537 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007538 }
Richard Smithc406cb72013-01-17 01:17:56 +00007539 }
7540
Richard Smithe3dbfe02013-06-30 10:40:20 +00007541 void VisitCallExpr(CallExpr *CE) {
7542 // C++11 [intro.execution]p15:
7543 // When calling a function [...], every value computation and side effect
7544 // associated with any argument expression, or with the postfix expression
7545 // designating the called function, is sequenced before execution of every
7546 // expression or statement in the body of the function [and thus before
7547 // the value computation of its result].
7548 SequencedSubexpression Sequenced(*this);
7549 Base::VisitCallExpr(CE);
7550
7551 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7552 }
7553
Richard Smithc406cb72013-01-17 01:17:56 +00007554 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007555 // This is a call, so all subexpressions are sequenced before the result.
7556 SequencedSubexpression Sequenced(*this);
7557
Richard Smithc406cb72013-01-17 01:17:56 +00007558 if (!CCE->isListInitialization())
7559 return VisitExpr(CCE);
7560
7561 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007562 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007563 SequenceTree::Seq Parent = Region;
7564 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7565 E = CCE->arg_end();
7566 I != E; ++I) {
7567 Region = Tree.allocate(Parent);
7568 Elts.push_back(Region);
7569 Visit(*I);
7570 }
7571
7572 // Forget that the initializers are sequenced.
7573 Region = Parent;
7574 for (unsigned I = 0; I < Elts.size(); ++I)
7575 Tree.merge(Elts[I]);
7576 }
7577
7578 void VisitInitListExpr(InitListExpr *ILE) {
7579 if (!SemaRef.getLangOpts().CPlusPlus11)
7580 return VisitExpr(ILE);
7581
7582 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007583 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007584 SequenceTree::Seq Parent = Region;
7585 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7586 Expr *E = ILE->getInit(I);
7587 if (!E) continue;
7588 Region = Tree.allocate(Parent);
7589 Elts.push_back(Region);
7590 Visit(E);
7591 }
7592
7593 // Forget that the initializers are sequenced.
7594 Region = Parent;
7595 for (unsigned I = 0; I < Elts.size(); ++I)
7596 Tree.merge(Elts[I]);
7597 }
7598};
7599}
7600
7601void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007602 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007603 WorkList.push_back(E);
7604 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007605 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007606 SequenceChecker(*this, Item, WorkList);
7607 }
Richard Smithc406cb72013-01-17 01:17:56 +00007608}
7609
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007610void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7611 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007612 CheckImplicitConversions(E, CheckLoc);
7613 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007614 if (!IsConstexpr && !E->isValueDependent())
7615 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007616}
7617
John McCall1f425642010-11-11 03:21:53 +00007618void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7619 FieldDecl *BitField,
7620 Expr *Init) {
7621 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7622}
7623
Mike Stump0c2ec772010-01-21 03:59:47 +00007624/// CheckParmsForFunctionDef - Check that the parameters of the given
7625/// function are appropriate for the definition of a function. This
7626/// takes care of any checks that cannot be performed on the
7627/// declaration itself, e.g., that the types of each of the function
7628/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007629bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7630 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007631 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007632 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007633 for (; P != PEnd; ++P) {
7634 ParmVarDecl *Param = *P;
7635
Mike Stump0c2ec772010-01-21 03:59:47 +00007636 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7637 // function declarator that is part of a function definition of
7638 // that function shall not have incomplete type.
7639 //
7640 // This is also C++ [dcl.fct]p6.
7641 if (!Param->isInvalidDecl() &&
7642 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007643 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007644 Param->setInvalidDecl();
7645 HasInvalidParm = true;
7646 }
7647
7648 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7649 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007650 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007651 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007652 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007653 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007654 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007655
7656 // C99 6.7.5.3p12:
7657 // If the function declarator is not part of a definition of that
7658 // function, parameters may have incomplete type and may use the [*]
7659 // notation in their sequences of declarator specifiers to specify
7660 // variable length array types.
7661 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007662 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007663 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007664 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007665 // information is added for it.
7666 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007667 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007668 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007669 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007670 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007671
7672 // MSVC destroys objects passed by value in the callee. Therefore a
7673 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007674 // object's destructor. However, we don't perform any direct access check
7675 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007676 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7677 .getCXXABI()
7678 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007679 if (!Param->isInvalidDecl()) {
7680 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7681 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7682 if (!ClassDecl->isInvalidDecl() &&
7683 !ClassDecl->hasIrrelevantDestructor() &&
7684 !ClassDecl->isDependentContext()) {
7685 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7686 MarkFunctionReferenced(Param->getLocation(), Destructor);
7687 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7688 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007689 }
7690 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007691 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007692 }
7693
7694 return HasInvalidParm;
7695}
John McCall2b5c1b22010-08-12 21:44:57 +00007696
7697/// CheckCastAlign - Implements -Wcast-align, which warns when a
7698/// pointer cast increases the alignment requirements.
7699void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7700 // This is actually a lot of work to potentially be doing on every
7701 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007702 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007703 return;
7704
7705 // Ignore dependent types.
7706 if (T->isDependentType() || Op->getType()->isDependentType())
7707 return;
7708
7709 // Require that the destination be a pointer type.
7710 const PointerType *DestPtr = T->getAs<PointerType>();
7711 if (!DestPtr) return;
7712
7713 // If the destination has alignment 1, we're done.
7714 QualType DestPointee = DestPtr->getPointeeType();
7715 if (DestPointee->isIncompleteType()) return;
7716 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7717 if (DestAlign.isOne()) return;
7718
7719 // Require that the source be a pointer type.
7720 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7721 if (!SrcPtr) return;
7722 QualType SrcPointee = SrcPtr->getPointeeType();
7723
7724 // Whitelist casts from cv void*. We already implicitly
7725 // whitelisted casts to cv void*, since they have alignment 1.
7726 // Also whitelist casts involving incomplete types, which implicitly
7727 // includes 'void'.
7728 if (SrcPointee->isIncompleteType()) return;
7729
7730 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7731 if (SrcAlign >= DestAlign) return;
7732
7733 Diag(TRange.getBegin(), diag::warn_cast_align)
7734 << Op->getType() << T
7735 << static_cast<unsigned>(SrcAlign.getQuantity())
7736 << static_cast<unsigned>(DestAlign.getQuantity())
7737 << TRange << Op->getSourceRange();
7738}
7739
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007740static const Type* getElementType(const Expr *BaseExpr) {
7741 const Type* EltType = BaseExpr->getType().getTypePtr();
7742 if (EltType->isAnyPointerType())
7743 return EltType->getPointeeType().getTypePtr();
7744 else if (EltType->isArrayType())
7745 return EltType->getBaseElementTypeUnsafe();
7746 return EltType;
7747}
7748
Chandler Carruth28389f02011-08-05 09:10:50 +00007749/// \brief Check whether this array fits the idiom of a size-one tail padded
7750/// array member of a struct.
7751///
7752/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7753/// commonly used to emulate flexible arrays in C89 code.
7754static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7755 const NamedDecl *ND) {
7756 if (Size != 1 || !ND) return false;
7757
7758 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7759 if (!FD) return false;
7760
7761 // Don't consider sizes resulting from macro expansions or template argument
7762 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007763
7764 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007765 while (TInfo) {
7766 TypeLoc TL = TInfo->getTypeLoc();
7767 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007768 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7769 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007770 TInfo = TDL->getTypeSourceInfo();
7771 continue;
7772 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007773 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7774 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007775 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7776 return false;
7777 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007778 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007779 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007780
7781 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007782 if (!RD) return false;
7783 if (RD->isUnion()) return false;
7784 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7785 if (!CRD->isStandardLayout()) return false;
7786 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007787
Benjamin Kramer8c543672011-08-06 03:04:42 +00007788 // See if this is the last field decl in the record.
7789 const Decl *D = FD;
7790 while ((D = D->getNextDeclInContext()))
7791 if (isa<FieldDecl>(D))
7792 return false;
7793 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007794}
7795
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007796void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007797 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007798 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007799 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007800 if (IndexExpr->isValueDependent())
7801 return;
7802
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007803 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007804 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007805 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007806 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007807 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007808 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007809
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007810 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007811 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007812 return;
Richard Smith13f67182011-12-16 19:31:14 +00007813 if (IndexNegated)
7814 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007815
Craig Topperc3ec1492014-05-26 06:22:03 +00007816 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007817 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7818 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007819 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007820 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007821
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007822 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007823 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007824 if (!size.isStrictlyPositive())
7825 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007826
7827 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007828 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007829 // Make sure we're comparing apples to apples when comparing index to size
7830 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7831 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007832 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007833 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007834 if (ptrarith_typesize != array_typesize) {
7835 // There's a cast to a different size type involved
7836 uint64_t ratio = array_typesize / ptrarith_typesize;
7837 // TODO: Be smarter about handling cases where array_typesize is not a
7838 // multiple of ptrarith_typesize
7839 if (ptrarith_typesize * ratio == array_typesize)
7840 size *= llvm::APInt(size.getBitWidth(), ratio);
7841 }
7842 }
7843
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007844 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007845 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007846 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007847 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007848
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007849 // For array subscripting the index must be less than size, but for pointer
7850 // arithmetic also allow the index (offset) to be equal to size since
7851 // computing the next address after the end of the array is legal and
7852 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007853 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007854 return;
7855
7856 // Also don't warn for arrays of size 1 which are members of some
7857 // structure. These are often used to approximate flexible arrays in C89
7858 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007859 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007860 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007861
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007862 // Suppress the warning if the subscript expression (as identified by the
7863 // ']' location) and the index expression are both from macro expansions
7864 // within a system header.
7865 if (ASE) {
7866 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7867 ASE->getRBracketLoc());
7868 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7869 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7870 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007871 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007872 return;
7873 }
7874 }
7875
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007876 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007877 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007878 DiagID = diag::warn_array_index_exceeds_bounds;
7879
7880 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7881 PDiag(DiagID) << index.toString(10, true)
7882 << size.toString(10, true)
7883 << (unsigned)size.getLimitedValue(~0U)
7884 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007885 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007886 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007887 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007888 DiagID = diag::warn_ptr_arith_precedes_bounds;
7889 if (index.isNegative()) index = -index;
7890 }
7891
7892 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7893 PDiag(DiagID) << index.toString(10, true)
7894 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007895 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007896
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007897 if (!ND) {
7898 // Try harder to find a NamedDecl to point at in the note.
7899 while (const ArraySubscriptExpr *ASE =
7900 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7901 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7902 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7903 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7904 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7905 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7906 }
7907
Chandler Carruth1af88f12011-02-17 21:10:52 +00007908 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007909 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7910 PDiag(diag::note_array_index_out_of_bounds)
7911 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007912}
7913
Ted Kremenekdf26df72011-03-01 18:41:00 +00007914void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007915 int AllowOnePastEnd = 0;
7916 while (expr) {
7917 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007918 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007919 case Stmt::ArraySubscriptExprClass: {
7920 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007921 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007922 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007923 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007924 }
7925 case Stmt::UnaryOperatorClass: {
7926 // Only unwrap the * and & unary operators
7927 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7928 expr = UO->getSubExpr();
7929 switch (UO->getOpcode()) {
7930 case UO_AddrOf:
7931 AllowOnePastEnd++;
7932 break;
7933 case UO_Deref:
7934 AllowOnePastEnd--;
7935 break;
7936 default:
7937 return;
7938 }
7939 break;
7940 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007941 case Stmt::ConditionalOperatorClass: {
7942 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7943 if (const Expr *lhs = cond->getLHS())
7944 CheckArrayAccess(lhs);
7945 if (const Expr *rhs = cond->getRHS())
7946 CheckArrayAccess(rhs);
7947 return;
7948 }
7949 default:
7950 return;
7951 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007952 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007953}
John McCall31168b02011-06-15 23:02:42 +00007954
7955//===--- CHECK: Objective-C retain cycles ----------------------------------//
7956
7957namespace {
7958 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007959 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007960 VarDecl *Variable;
7961 SourceRange Range;
7962 SourceLocation Loc;
7963 bool Indirect;
7964
7965 void setLocsFrom(Expr *e) {
7966 Loc = e->getExprLoc();
7967 Range = e->getSourceRange();
7968 }
7969 };
7970}
7971
7972/// Consider whether capturing the given variable can possibly lead to
7973/// a retain cycle.
7974static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007975 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007976 // lifetime. In MRR, it's captured strongly if the variable is
7977 // __block and has an appropriate type.
7978 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7979 return false;
7980
7981 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007982 if (ref)
7983 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007984 return true;
7985}
7986
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007987static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007988 while (true) {
7989 e = e->IgnoreParens();
7990 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7991 switch (cast->getCastKind()) {
7992 case CK_BitCast:
7993 case CK_LValueBitCast:
7994 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007995 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007996 e = cast->getSubExpr();
7997 continue;
7998
John McCall31168b02011-06-15 23:02:42 +00007999 default:
8000 return false;
8001 }
8002 }
8003
8004 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8005 ObjCIvarDecl *ivar = ref->getDecl();
8006 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8007 return false;
8008
8009 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008010 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008011 return false;
8012
8013 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8014 owner.Indirect = true;
8015 return true;
8016 }
8017
8018 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8019 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8020 if (!var) return false;
8021 return considerVariable(var, ref, owner);
8022 }
8023
John McCall31168b02011-06-15 23:02:42 +00008024 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8025 if (member->isArrow()) return false;
8026
8027 // Don't count this as an indirect ownership.
8028 e = member->getBase();
8029 continue;
8030 }
8031
John McCallfe96e0b2011-11-06 09:01:30 +00008032 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8033 // Only pay attention to pseudo-objects on property references.
8034 ObjCPropertyRefExpr *pre
8035 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8036 ->IgnoreParens());
8037 if (!pre) return false;
8038 if (pre->isImplicitProperty()) return false;
8039 ObjCPropertyDecl *property = pre->getExplicitProperty();
8040 if (!property->isRetaining() &&
8041 !(property->getPropertyIvarDecl() &&
8042 property->getPropertyIvarDecl()->getType()
8043 .getObjCLifetime() == Qualifiers::OCL_Strong))
8044 return false;
8045
8046 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008047 if (pre->isSuperReceiver()) {
8048 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8049 if (!owner.Variable)
8050 return false;
8051 owner.Loc = pre->getLocation();
8052 owner.Range = pre->getSourceRange();
8053 return true;
8054 }
John McCallfe96e0b2011-11-06 09:01:30 +00008055 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8056 ->getSourceExpr());
8057 continue;
8058 }
8059
John McCall31168b02011-06-15 23:02:42 +00008060 // Array ivars?
8061
8062 return false;
8063 }
8064}
8065
8066namespace {
8067 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8068 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8069 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008070 Context(Context), Variable(variable), Capturer(nullptr),
8071 VarWillBeReased(false) {}
8072 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008073 VarDecl *Variable;
8074 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008075 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008076
8077 void VisitDeclRefExpr(DeclRefExpr *ref) {
8078 if (ref->getDecl() == Variable && !Capturer)
8079 Capturer = ref;
8080 }
8081
John McCall31168b02011-06-15 23:02:42 +00008082 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8083 if (Capturer) return;
8084 Visit(ref->getBase());
8085 if (Capturer && ref->isFreeIvar())
8086 Capturer = ref;
8087 }
8088
8089 void VisitBlockExpr(BlockExpr *block) {
8090 // Look inside nested blocks
8091 if (block->getBlockDecl()->capturesVariable(Variable))
8092 Visit(block->getBlockDecl()->getBody());
8093 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008094
8095 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8096 if (Capturer) return;
8097 if (OVE->getSourceExpr())
8098 Visit(OVE->getSourceExpr());
8099 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008100 void VisitBinaryOperator(BinaryOperator *BinOp) {
8101 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8102 return;
8103 Expr *LHS = BinOp->getLHS();
8104 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8105 if (DRE->getDecl() != Variable)
8106 return;
8107 if (Expr *RHS = BinOp->getRHS()) {
8108 RHS = RHS->IgnoreParenCasts();
8109 llvm::APSInt Value;
8110 VarWillBeReased =
8111 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8112 }
8113 }
8114 }
John McCall31168b02011-06-15 23:02:42 +00008115 };
8116}
8117
8118/// Check whether the given argument is a block which captures a
8119/// variable.
8120static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8121 assert(owner.Variable && owner.Loc.isValid());
8122
8123 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008124
8125 // Look through [^{...} copy] and Block_copy(^{...}).
8126 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8127 Selector Cmd = ME->getSelector();
8128 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8129 e = ME->getInstanceReceiver();
8130 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008131 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008132 e = e->IgnoreParenCasts();
8133 }
8134 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8135 if (CE->getNumArgs() == 1) {
8136 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008137 if (Fn) {
8138 const IdentifierInfo *FnI = Fn->getIdentifier();
8139 if (FnI && FnI->isStr("_Block_copy")) {
8140 e = CE->getArg(0)->IgnoreParenCasts();
8141 }
8142 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008143 }
8144 }
8145
John McCall31168b02011-06-15 23:02:42 +00008146 BlockExpr *block = dyn_cast<BlockExpr>(e);
8147 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008148 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008149
8150 FindCaptureVisitor visitor(S.Context, owner.Variable);
8151 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008152 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008153}
8154
8155static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8156 RetainCycleOwner &owner) {
8157 assert(capturer);
8158 assert(owner.Variable && owner.Loc.isValid());
8159
8160 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8161 << owner.Variable << capturer->getSourceRange();
8162 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8163 << owner.Indirect << owner.Range;
8164}
8165
8166/// Check for a keyword selector that starts with the word 'add' or
8167/// 'set'.
8168static bool isSetterLikeSelector(Selector sel) {
8169 if (sel.isUnarySelector()) return false;
8170
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008171 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008172 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008173 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008174 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008175 else if (str.startswith("add")) {
8176 // Specially whitelist 'addOperationWithBlock:'.
8177 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8178 return false;
8179 str = str.substr(3);
8180 }
John McCall31168b02011-06-15 23:02:42 +00008181 else
8182 return false;
8183
8184 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008185 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008186}
8187
8188/// Check a message send to see if it's likely to cause a retain cycle.
8189void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8190 // Only check instance methods whose selector looks like a setter.
8191 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8192 return;
8193
8194 // Try to find a variable that the receiver is strongly owned by.
8195 RetainCycleOwner owner;
8196 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008197 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008198 return;
8199 } else {
8200 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8201 owner.Variable = getCurMethodDecl()->getSelfDecl();
8202 owner.Loc = msg->getSuperLoc();
8203 owner.Range = msg->getSuperLoc();
8204 }
8205
8206 // Check whether the receiver is captured by any of the arguments.
8207 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8208 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8209 return diagnoseRetainCycle(*this, capturer, owner);
8210}
8211
8212/// Check a property assign to see if it's likely to cause a retain cycle.
8213void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8214 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008215 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008216 return;
8217
8218 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8219 diagnoseRetainCycle(*this, capturer, owner);
8220}
8221
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008222void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8223 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008224 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008225 return;
8226
8227 // Because we don't have an expression for the variable, we have to set the
8228 // location explicitly here.
8229 Owner.Loc = Var->getLocation();
8230 Owner.Range = Var->getSourceRange();
8231
8232 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8233 diagnoseRetainCycle(*this, Capturer, Owner);
8234}
8235
Ted Kremenek9304da92012-12-21 08:04:28 +00008236static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8237 Expr *RHS, bool isProperty) {
8238 // Check if RHS is an Objective-C object literal, which also can get
8239 // immediately zapped in a weak reference. Note that we explicitly
8240 // allow ObjCStringLiterals, since those are designed to never really die.
8241 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008242
Ted Kremenek64873352012-12-21 22:46:35 +00008243 // This enum needs to match with the 'select' in
8244 // warn_objc_arc_literal_assign (off-by-1).
8245 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8246 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8247 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008248
8249 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008250 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008251 << (isProperty ? 0 : 1)
8252 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008253
8254 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008255}
8256
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008257static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8258 Qualifiers::ObjCLifetime LT,
8259 Expr *RHS, bool isProperty) {
8260 // Strip off any implicit cast added to get to the one ARC-specific.
8261 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8262 if (cast->getCastKind() == CK_ARCConsumeObject) {
8263 S.Diag(Loc, diag::warn_arc_retained_assign)
8264 << (LT == Qualifiers::OCL_ExplicitNone)
8265 << (isProperty ? 0 : 1)
8266 << RHS->getSourceRange();
8267 return true;
8268 }
8269 RHS = cast->getSubExpr();
8270 }
8271
8272 if (LT == Qualifiers::OCL_Weak &&
8273 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8274 return true;
8275
8276 return false;
8277}
8278
Ted Kremenekb36234d2012-12-21 08:04:20 +00008279bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8280 QualType LHS, Expr *RHS) {
8281 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8282
8283 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8284 return false;
8285
8286 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8287 return true;
8288
8289 return false;
8290}
8291
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008292void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8293 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008294 QualType LHSType;
8295 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008296 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008297 ObjCPropertyRefExpr *PRE
8298 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8299 if (PRE && !PRE->isImplicitProperty()) {
8300 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8301 if (PD)
8302 LHSType = PD->getType();
8303 }
8304
8305 if (LHSType.isNull())
8306 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008307
8308 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8309
8310 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008311 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008312 getCurFunction()->markSafeWeakUse(LHS);
8313 }
8314
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008315 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8316 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008317
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008318 // FIXME. Check for other life times.
8319 if (LT != Qualifiers::OCL_None)
8320 return;
8321
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008322 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008323 if (PRE->isImplicitProperty())
8324 return;
8325 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8326 if (!PD)
8327 return;
8328
Bill Wendling44426052012-12-20 19:22:21 +00008329 unsigned Attributes = PD->getPropertyAttributes();
8330 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008331 // when 'assign' attribute was not explicitly specified
8332 // by user, ignore it and rely on property type itself
8333 // for lifetime info.
8334 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8335 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8336 LHSType->isObjCRetainableType())
8337 return;
8338
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008339 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008340 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008341 Diag(Loc, diag::warn_arc_retained_property_assign)
8342 << RHS->getSourceRange();
8343 return;
8344 }
8345 RHS = cast->getSubExpr();
8346 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008347 }
Bill Wendling44426052012-12-20 19:22:21 +00008348 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008349 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8350 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008351 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008352 }
8353}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008354
8355//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8356
8357namespace {
8358bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8359 SourceLocation StmtLoc,
8360 const NullStmt *Body) {
8361 // Do not warn if the body is a macro that expands to nothing, e.g:
8362 //
8363 // #define CALL(x)
8364 // if (condition)
8365 // CALL(0);
8366 //
8367 if (Body->hasLeadingEmptyMacro())
8368 return false;
8369
8370 // Get line numbers of statement and body.
8371 bool StmtLineInvalid;
8372 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8373 &StmtLineInvalid);
8374 if (StmtLineInvalid)
8375 return false;
8376
8377 bool BodyLineInvalid;
8378 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8379 &BodyLineInvalid);
8380 if (BodyLineInvalid)
8381 return false;
8382
8383 // Warn if null statement and body are on the same line.
8384 if (StmtLine != BodyLine)
8385 return false;
8386
8387 return true;
8388}
8389} // Unnamed namespace
8390
8391void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8392 const Stmt *Body,
8393 unsigned DiagID) {
8394 // Since this is a syntactic check, don't emit diagnostic for template
8395 // instantiations, this just adds noise.
8396 if (CurrentInstantiationScope)
8397 return;
8398
8399 // The body should be a null statement.
8400 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8401 if (!NBody)
8402 return;
8403
8404 // Do the usual checks.
8405 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8406 return;
8407
8408 Diag(NBody->getSemiLoc(), DiagID);
8409 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8410}
8411
8412void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8413 const Stmt *PossibleBody) {
8414 assert(!CurrentInstantiationScope); // Ensured by caller
8415
8416 SourceLocation StmtLoc;
8417 const Stmt *Body;
8418 unsigned DiagID;
8419 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8420 StmtLoc = FS->getRParenLoc();
8421 Body = FS->getBody();
8422 DiagID = diag::warn_empty_for_body;
8423 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8424 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8425 Body = WS->getBody();
8426 DiagID = diag::warn_empty_while_body;
8427 } else
8428 return; // Neither `for' nor `while'.
8429
8430 // The body should be a null statement.
8431 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8432 if (!NBody)
8433 return;
8434
8435 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008436 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008437 return;
8438
8439 // Do the usual checks.
8440 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8441 return;
8442
8443 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8444 // noise level low, emit diagnostics only if for/while is followed by a
8445 // CompoundStmt, e.g.:
8446 // for (int i = 0; i < n; i++);
8447 // {
8448 // a(i);
8449 // }
8450 // or if for/while is followed by a statement with more indentation
8451 // than for/while itself:
8452 // for (int i = 0; i < n; i++);
8453 // a(i);
8454 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8455 if (!ProbableTypo) {
8456 bool BodyColInvalid;
8457 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8458 PossibleBody->getLocStart(),
8459 &BodyColInvalid);
8460 if (BodyColInvalid)
8461 return;
8462
8463 bool StmtColInvalid;
8464 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8465 S->getLocStart(),
8466 &StmtColInvalid);
8467 if (StmtColInvalid)
8468 return;
8469
8470 if (BodyCol > StmtCol)
8471 ProbableTypo = true;
8472 }
8473
8474 if (ProbableTypo) {
8475 Diag(NBody->getSemiLoc(), DiagID);
8476 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8477 }
8478}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008479
Richard Trieu36d0b2b2015-01-13 02:32:02 +00008480//===--- CHECK: Warn on self move with std::move. -------------------------===//
8481
8482/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8483void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8484 SourceLocation OpLoc) {
8485
8486 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8487 return;
8488
8489 if (!ActiveTemplateInstantiations.empty())
8490 return;
8491
8492 // Strip parens and casts away.
8493 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8494 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8495
8496 // Check for a call expression
8497 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8498 if (!CE || CE->getNumArgs() != 1)
8499 return;
8500
8501 // Check for a call to std::move
8502 const FunctionDecl *FD = CE->getDirectCallee();
8503 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8504 !FD->getIdentifier()->isStr("move"))
8505 return;
8506
8507 // Get argument from std::move
8508 RHSExpr = CE->getArg(0);
8509
8510 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8511 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8512
8513 // Two DeclRefExpr's, check that the decls are the same.
8514 if (LHSDeclRef && RHSDeclRef) {
8515 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8516 return;
8517 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8518 RHSDeclRef->getDecl()->getCanonicalDecl())
8519 return;
8520
8521 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8522 << LHSExpr->getSourceRange()
8523 << RHSExpr->getSourceRange();
8524 return;
8525 }
8526
8527 // Member variables require a different approach to check for self moves.
8528 // MemberExpr's are the same if every nested MemberExpr refers to the same
8529 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8530 // the base Expr's are CXXThisExpr's.
8531 const Expr *LHSBase = LHSExpr;
8532 const Expr *RHSBase = RHSExpr;
8533 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8534 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8535 if (!LHSME || !RHSME)
8536 return;
8537
8538 while (LHSME && RHSME) {
8539 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8540 RHSME->getMemberDecl()->getCanonicalDecl())
8541 return;
8542
8543 LHSBase = LHSME->getBase();
8544 RHSBase = RHSME->getBase();
8545 LHSME = dyn_cast<MemberExpr>(LHSBase);
8546 RHSME = dyn_cast<MemberExpr>(RHSBase);
8547 }
8548
8549 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8550 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8551 if (LHSDeclRef && RHSDeclRef) {
8552 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8553 return;
8554 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8555 RHSDeclRef->getDecl()->getCanonicalDecl())
8556 return;
8557
8558 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8559 << LHSExpr->getSourceRange()
8560 << RHSExpr->getSourceRange();
8561 return;
8562 }
8563
8564 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8565 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8566 << LHSExpr->getSourceRange()
8567 << RHSExpr->getSourceRange();
8568}
8569
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008570//===--- Layout compatibility ----------------------------------------------//
8571
8572namespace {
8573
8574bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8575
8576/// \brief Check if two enumeration types are layout-compatible.
8577bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8578 // C++11 [dcl.enum] p8:
8579 // Two enumeration types are layout-compatible if they have the same
8580 // underlying type.
8581 return ED1->isComplete() && ED2->isComplete() &&
8582 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8583}
8584
8585/// \brief Check if two fields are layout-compatible.
8586bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8587 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8588 return false;
8589
8590 if (Field1->isBitField() != Field2->isBitField())
8591 return false;
8592
8593 if (Field1->isBitField()) {
8594 // Make sure that the bit-fields are the same length.
8595 unsigned Bits1 = Field1->getBitWidthValue(C);
8596 unsigned Bits2 = Field2->getBitWidthValue(C);
8597
8598 if (Bits1 != Bits2)
8599 return false;
8600 }
8601
8602 return true;
8603}
8604
8605/// \brief Check if two standard-layout structs are layout-compatible.
8606/// (C++11 [class.mem] p17)
8607bool isLayoutCompatibleStruct(ASTContext &C,
8608 RecordDecl *RD1,
8609 RecordDecl *RD2) {
8610 // If both records are C++ classes, check that base classes match.
8611 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8612 // If one of records is a CXXRecordDecl we are in C++ mode,
8613 // thus the other one is a CXXRecordDecl, too.
8614 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8615 // Check number of base classes.
8616 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8617 return false;
8618
8619 // Check the base classes.
8620 for (CXXRecordDecl::base_class_const_iterator
8621 Base1 = D1CXX->bases_begin(),
8622 BaseEnd1 = D1CXX->bases_end(),
8623 Base2 = D2CXX->bases_begin();
8624 Base1 != BaseEnd1;
8625 ++Base1, ++Base2) {
8626 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8627 return false;
8628 }
8629 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8630 // If only RD2 is a C++ class, it should have zero base classes.
8631 if (D2CXX->getNumBases() > 0)
8632 return false;
8633 }
8634
8635 // Check the fields.
8636 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8637 Field2End = RD2->field_end(),
8638 Field1 = RD1->field_begin(),
8639 Field1End = RD1->field_end();
8640 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8641 if (!isLayoutCompatible(C, *Field1, *Field2))
8642 return false;
8643 }
8644 if (Field1 != Field1End || Field2 != Field2End)
8645 return false;
8646
8647 return true;
8648}
8649
8650/// \brief Check if two standard-layout unions are layout-compatible.
8651/// (C++11 [class.mem] p18)
8652bool isLayoutCompatibleUnion(ASTContext &C,
8653 RecordDecl *RD1,
8654 RecordDecl *RD2) {
8655 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008656 for (auto *Field2 : RD2->fields())
8657 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008658
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008659 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008660 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8661 I = UnmatchedFields.begin(),
8662 E = UnmatchedFields.end();
8663
8664 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008665 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008666 bool Result = UnmatchedFields.erase(*I);
8667 (void) Result;
8668 assert(Result);
8669 break;
8670 }
8671 }
8672 if (I == E)
8673 return false;
8674 }
8675
8676 return UnmatchedFields.empty();
8677}
8678
8679bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8680 if (RD1->isUnion() != RD2->isUnion())
8681 return false;
8682
8683 if (RD1->isUnion())
8684 return isLayoutCompatibleUnion(C, RD1, RD2);
8685 else
8686 return isLayoutCompatibleStruct(C, RD1, RD2);
8687}
8688
8689/// \brief Check if two types are layout-compatible in C++11 sense.
8690bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8691 if (T1.isNull() || T2.isNull())
8692 return false;
8693
8694 // C++11 [basic.types] p11:
8695 // If two types T1 and T2 are the same type, then T1 and T2 are
8696 // layout-compatible types.
8697 if (C.hasSameType(T1, T2))
8698 return true;
8699
8700 T1 = T1.getCanonicalType().getUnqualifiedType();
8701 T2 = T2.getCanonicalType().getUnqualifiedType();
8702
8703 const Type::TypeClass TC1 = T1->getTypeClass();
8704 const Type::TypeClass TC2 = T2->getTypeClass();
8705
8706 if (TC1 != TC2)
8707 return false;
8708
8709 if (TC1 == Type::Enum) {
8710 return isLayoutCompatible(C,
8711 cast<EnumType>(T1)->getDecl(),
8712 cast<EnumType>(T2)->getDecl());
8713 } else if (TC1 == Type::Record) {
8714 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8715 return false;
8716
8717 return isLayoutCompatible(C,
8718 cast<RecordType>(T1)->getDecl(),
8719 cast<RecordType>(T2)->getDecl());
8720 }
8721
8722 return false;
8723}
8724}
8725
8726//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8727
8728namespace {
8729/// \brief Given a type tag expression find the type tag itself.
8730///
8731/// \param TypeExpr Type tag expression, as it appears in user's code.
8732///
8733/// \param VD Declaration of an identifier that appears in a type tag.
8734///
8735/// \param MagicValue Type tag magic value.
8736bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8737 const ValueDecl **VD, uint64_t *MagicValue) {
8738 while(true) {
8739 if (!TypeExpr)
8740 return false;
8741
8742 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8743
8744 switch (TypeExpr->getStmtClass()) {
8745 case Stmt::UnaryOperatorClass: {
8746 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8747 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8748 TypeExpr = UO->getSubExpr();
8749 continue;
8750 }
8751 return false;
8752 }
8753
8754 case Stmt::DeclRefExprClass: {
8755 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8756 *VD = DRE->getDecl();
8757 return true;
8758 }
8759
8760 case Stmt::IntegerLiteralClass: {
8761 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8762 llvm::APInt MagicValueAPInt = IL->getValue();
8763 if (MagicValueAPInt.getActiveBits() <= 64) {
8764 *MagicValue = MagicValueAPInt.getZExtValue();
8765 return true;
8766 } else
8767 return false;
8768 }
8769
8770 case Stmt::BinaryConditionalOperatorClass:
8771 case Stmt::ConditionalOperatorClass: {
8772 const AbstractConditionalOperator *ACO =
8773 cast<AbstractConditionalOperator>(TypeExpr);
8774 bool Result;
8775 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8776 if (Result)
8777 TypeExpr = ACO->getTrueExpr();
8778 else
8779 TypeExpr = ACO->getFalseExpr();
8780 continue;
8781 }
8782 return false;
8783 }
8784
8785 case Stmt::BinaryOperatorClass: {
8786 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8787 if (BO->getOpcode() == BO_Comma) {
8788 TypeExpr = BO->getRHS();
8789 continue;
8790 }
8791 return false;
8792 }
8793
8794 default:
8795 return false;
8796 }
8797 }
8798}
8799
8800/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8801///
8802/// \param TypeExpr Expression that specifies a type tag.
8803///
8804/// \param MagicValues Registered magic values.
8805///
8806/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8807/// kind.
8808///
8809/// \param TypeInfo Information about the corresponding C type.
8810///
8811/// \returns true if the corresponding C type was found.
8812bool GetMatchingCType(
8813 const IdentifierInfo *ArgumentKind,
8814 const Expr *TypeExpr, const ASTContext &Ctx,
8815 const llvm::DenseMap<Sema::TypeTagMagicValue,
8816 Sema::TypeTagData> *MagicValues,
8817 bool &FoundWrongKind,
8818 Sema::TypeTagData &TypeInfo) {
8819 FoundWrongKind = false;
8820
8821 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008822 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008823
8824 uint64_t MagicValue;
8825
8826 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8827 return false;
8828
8829 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008830 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008831 if (I->getArgumentKind() != ArgumentKind) {
8832 FoundWrongKind = true;
8833 return false;
8834 }
8835 TypeInfo.Type = I->getMatchingCType();
8836 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8837 TypeInfo.MustBeNull = I->getMustBeNull();
8838 return true;
8839 }
8840 return false;
8841 }
8842
8843 if (!MagicValues)
8844 return false;
8845
8846 llvm::DenseMap<Sema::TypeTagMagicValue,
8847 Sema::TypeTagData>::const_iterator I =
8848 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8849 if (I == MagicValues->end())
8850 return false;
8851
8852 TypeInfo = I->second;
8853 return true;
8854}
8855} // unnamed namespace
8856
8857void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8858 uint64_t MagicValue, QualType Type,
8859 bool LayoutCompatible,
8860 bool MustBeNull) {
8861 if (!TypeTagForDatatypeMagicValues)
8862 TypeTagForDatatypeMagicValues.reset(
8863 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8864
8865 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8866 (*TypeTagForDatatypeMagicValues)[Magic] =
8867 TypeTagData(Type, LayoutCompatible, MustBeNull);
8868}
8869
8870namespace {
8871bool IsSameCharType(QualType T1, QualType T2) {
8872 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8873 if (!BT1)
8874 return false;
8875
8876 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8877 if (!BT2)
8878 return false;
8879
8880 BuiltinType::Kind T1Kind = BT1->getKind();
8881 BuiltinType::Kind T2Kind = BT2->getKind();
8882
8883 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8884 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8885 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8886 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8887}
8888} // unnamed namespace
8889
8890void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8891 const Expr * const *ExprArgs) {
8892 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8893 bool IsPointerAttr = Attr->getIsPointer();
8894
8895 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8896 bool FoundWrongKind;
8897 TypeTagData TypeInfo;
8898 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8899 TypeTagForDatatypeMagicValues.get(),
8900 FoundWrongKind, TypeInfo)) {
8901 if (FoundWrongKind)
8902 Diag(TypeTagExpr->getExprLoc(),
8903 diag::warn_type_tag_for_datatype_wrong_kind)
8904 << TypeTagExpr->getSourceRange();
8905 return;
8906 }
8907
8908 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8909 if (IsPointerAttr) {
8910 // Skip implicit cast of pointer to `void *' (as a function argument).
8911 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008912 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008913 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008914 ArgumentExpr = ICE->getSubExpr();
8915 }
8916 QualType ArgumentType = ArgumentExpr->getType();
8917
8918 // Passing a `void*' pointer shouldn't trigger a warning.
8919 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8920 return;
8921
8922 if (TypeInfo.MustBeNull) {
8923 // Type tag with matching void type requires a null pointer.
8924 if (!ArgumentExpr->isNullPointerConstant(Context,
8925 Expr::NPC_ValueDependentIsNotNull)) {
8926 Diag(ArgumentExpr->getExprLoc(),
8927 diag::warn_type_safety_null_pointer_required)
8928 << ArgumentKind->getName()
8929 << ArgumentExpr->getSourceRange()
8930 << TypeTagExpr->getSourceRange();
8931 }
8932 return;
8933 }
8934
8935 QualType RequiredType = TypeInfo.Type;
8936 if (IsPointerAttr)
8937 RequiredType = Context.getPointerType(RequiredType);
8938
8939 bool mismatch = false;
8940 if (!TypeInfo.LayoutCompatible) {
8941 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8942
8943 // C++11 [basic.fundamental] p1:
8944 // Plain char, signed char, and unsigned char are three distinct types.
8945 //
8946 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8947 // char' depending on the current char signedness mode.
8948 if (mismatch)
8949 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8950 RequiredType->getPointeeType())) ||
8951 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8952 mismatch = false;
8953 } else
8954 if (IsPointerAttr)
8955 mismatch = !isLayoutCompatible(Context,
8956 ArgumentType->getPointeeType(),
8957 RequiredType->getPointeeType());
8958 else
8959 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8960
8961 if (mismatch)
8962 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008963 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008964 << TypeInfo.LayoutCompatible << RequiredType
8965 << ArgumentExpr->getSourceRange()
8966 << TypeTagExpr->getSourceRange();
8967}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008968