blob: 72cb6003f5a172b6a617492a2698594fb5cba3af [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 Cantrellb4802962015-03-04 03:12:10 +00004039 analyze_format_string::ArgType::MatchKind match =
4040 AT.matchesType(S.Context, Ex->getType());
4041 if (AT.isValid() && match != analyze_format_string::ArgType::Match) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004042 ScanfSpecifier fixedFS = FS;
Seth Cantrellb4802962015-03-04 03:12:10 +00004043 bool success =
4044 fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4045 S.getLangOpts(), S.Context);
4046
4047 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4048 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4049 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4050 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004051
4052 if (success) {
4053 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004054 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004055 llvm::raw_svector_ostream os(buf);
4056 fixedFS.toString(os);
4057
4058 EmitFormatDiagnostic(
Seth Cantrellb4802962015-03-04 03:12:10 +00004059 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4060 << Ex->getType() << false << Ex->getSourceRange(),
4061 Ex->getLocStart(),
4062 /*IsStringLocation*/ false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004063 getSpecifierRange(startSpecifier, specifierLen),
Seth Cantrellb4802962015-03-04 03:12:10 +00004064 FixItHint::CreateReplacement(
4065 getSpecifierRange(startSpecifier, specifierLen), os.str()));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004066 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00004067 EmitFormatDiagnostic(
Seth Cantrellb4802962015-03-04 03:12:10 +00004068 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4069 << Ex->getType() << false << Ex->getSourceRange(),
4070 Ex->getLocStart(),
4071 /*IsStringLocation*/ false,
4072 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004073 }
4074 }
4075
Ted Kremenek02087932010-07-16 02:11:22 +00004076 return true;
4077}
4078
4079void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004080 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004081 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004082 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004083 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004084 bool inFunctionCall, VariadicCallType CallType,
4085 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004086
Ted Kremenekab278de2010-01-28 23:39:18 +00004087 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004088 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004089 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004090 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004091 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4092 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004093 return;
4094 }
Ted Kremenek02087932010-07-16 02:11:22 +00004095
Ted Kremenekab278de2010-01-28 23:39:18 +00004096 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004097 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004098 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004099 // Account for cases where the string literal is truncated in a declaration.
4100 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4101 assert(T && "String literal not of constant array type!");
4102 size_t TypeSize = T->getSize().getZExtValue();
4103 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004104 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004105
4106 // Emit a warning if the string literal is truncated and does not contain an
4107 // embedded null character.
4108 if (TypeSize <= StrRef.size() &&
4109 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4110 CheckFormatHandler::EmitFormatDiagnostic(
4111 *this, inFunctionCall, Args[format_idx],
4112 PDiag(diag::warn_printf_format_string_not_null_terminated),
4113 FExpr->getLocStart(),
4114 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4115 return;
4116 }
4117
Ted Kremenekab278de2010-01-28 23:39:18 +00004118 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004119 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004120 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004121 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004122 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4123 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004124 return;
4125 }
Ted Kremenek02087932010-07-16 02:11:22 +00004126
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004127 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004128 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004129 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004130 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004131 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004132 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004133
Hans Wennborg23926bd2011-12-15 10:25:47 +00004134 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004135 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004136 Context.getTargetInfo(),
4137 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004138 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004139 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004140 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004141 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004142 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004143
Hans Wennborg23926bd2011-12-15 10:25:47 +00004144 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004145 getLangOpts(),
4146 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004147 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004148 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004149}
4150
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004151bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4152 // Str - The format string. NOTE: this is NOT null-terminated!
4153 StringRef StrRef = FExpr->getString();
4154 const char *Str = StrRef.data();
4155 // Account for cases where the string literal is truncated in a declaration.
4156 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4157 assert(T && "String literal not of constant array type!");
4158 size_t TypeSize = T->getSize().getZExtValue();
4159 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4160 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4161 getLangOpts(),
4162 Context.getTargetInfo());
4163}
4164
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004165//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4166
4167// Returns the related absolute value function that is larger, of 0 if one
4168// does not exist.
4169static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4170 switch (AbsFunction) {
4171 default:
4172 return 0;
4173
4174 case Builtin::BI__builtin_abs:
4175 return Builtin::BI__builtin_labs;
4176 case Builtin::BI__builtin_labs:
4177 return Builtin::BI__builtin_llabs;
4178 case Builtin::BI__builtin_llabs:
4179 return 0;
4180
4181 case Builtin::BI__builtin_fabsf:
4182 return Builtin::BI__builtin_fabs;
4183 case Builtin::BI__builtin_fabs:
4184 return Builtin::BI__builtin_fabsl;
4185 case Builtin::BI__builtin_fabsl:
4186 return 0;
4187
4188 case Builtin::BI__builtin_cabsf:
4189 return Builtin::BI__builtin_cabs;
4190 case Builtin::BI__builtin_cabs:
4191 return Builtin::BI__builtin_cabsl;
4192 case Builtin::BI__builtin_cabsl:
4193 return 0;
4194
4195 case Builtin::BIabs:
4196 return Builtin::BIlabs;
4197 case Builtin::BIlabs:
4198 return Builtin::BIllabs;
4199 case Builtin::BIllabs:
4200 return 0;
4201
4202 case Builtin::BIfabsf:
4203 return Builtin::BIfabs;
4204 case Builtin::BIfabs:
4205 return Builtin::BIfabsl;
4206 case Builtin::BIfabsl:
4207 return 0;
4208
4209 case Builtin::BIcabsf:
4210 return Builtin::BIcabs;
4211 case Builtin::BIcabs:
4212 return Builtin::BIcabsl;
4213 case Builtin::BIcabsl:
4214 return 0;
4215 }
4216}
4217
4218// Returns the argument type of the absolute value function.
4219static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4220 unsigned AbsType) {
4221 if (AbsType == 0)
4222 return QualType();
4223
4224 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4225 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4226 if (Error != ASTContext::GE_None)
4227 return QualType();
4228
4229 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4230 if (!FT)
4231 return QualType();
4232
4233 if (FT->getNumParams() != 1)
4234 return QualType();
4235
4236 return FT->getParamType(0);
4237}
4238
4239// Returns the best absolute value function, or zero, based on type and
4240// current absolute value function.
4241static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4242 unsigned AbsFunctionKind) {
4243 unsigned BestKind = 0;
4244 uint64_t ArgSize = Context.getTypeSize(ArgType);
4245 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4246 Kind = getLargerAbsoluteValueFunction(Kind)) {
4247 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4248 if (Context.getTypeSize(ParamType) >= ArgSize) {
4249 if (BestKind == 0)
4250 BestKind = Kind;
4251 else if (Context.hasSameType(ParamType, ArgType)) {
4252 BestKind = Kind;
4253 break;
4254 }
4255 }
4256 }
4257 return BestKind;
4258}
4259
4260enum AbsoluteValueKind {
4261 AVK_Integer,
4262 AVK_Floating,
4263 AVK_Complex
4264};
4265
4266static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4267 if (T->isIntegralOrEnumerationType())
4268 return AVK_Integer;
4269 if (T->isRealFloatingType())
4270 return AVK_Floating;
4271 if (T->isAnyComplexType())
4272 return AVK_Complex;
4273
4274 llvm_unreachable("Type not integer, floating, or complex");
4275}
4276
4277// Changes the absolute value function to a different type. Preserves whether
4278// the function is a builtin.
4279static unsigned changeAbsFunction(unsigned AbsKind,
4280 AbsoluteValueKind ValueKind) {
4281 switch (ValueKind) {
4282 case AVK_Integer:
4283 switch (AbsKind) {
4284 default:
4285 return 0;
4286 case Builtin::BI__builtin_fabsf:
4287 case Builtin::BI__builtin_fabs:
4288 case Builtin::BI__builtin_fabsl:
4289 case Builtin::BI__builtin_cabsf:
4290 case Builtin::BI__builtin_cabs:
4291 case Builtin::BI__builtin_cabsl:
4292 return Builtin::BI__builtin_abs;
4293 case Builtin::BIfabsf:
4294 case Builtin::BIfabs:
4295 case Builtin::BIfabsl:
4296 case Builtin::BIcabsf:
4297 case Builtin::BIcabs:
4298 case Builtin::BIcabsl:
4299 return Builtin::BIabs;
4300 }
4301 case AVK_Floating:
4302 switch (AbsKind) {
4303 default:
4304 return 0;
4305 case Builtin::BI__builtin_abs:
4306 case Builtin::BI__builtin_labs:
4307 case Builtin::BI__builtin_llabs:
4308 case Builtin::BI__builtin_cabsf:
4309 case Builtin::BI__builtin_cabs:
4310 case Builtin::BI__builtin_cabsl:
4311 return Builtin::BI__builtin_fabsf;
4312 case Builtin::BIabs:
4313 case Builtin::BIlabs:
4314 case Builtin::BIllabs:
4315 case Builtin::BIcabsf:
4316 case Builtin::BIcabs:
4317 case Builtin::BIcabsl:
4318 return Builtin::BIfabsf;
4319 }
4320 case AVK_Complex:
4321 switch (AbsKind) {
4322 default:
4323 return 0;
4324 case Builtin::BI__builtin_abs:
4325 case Builtin::BI__builtin_labs:
4326 case Builtin::BI__builtin_llabs:
4327 case Builtin::BI__builtin_fabsf:
4328 case Builtin::BI__builtin_fabs:
4329 case Builtin::BI__builtin_fabsl:
4330 return Builtin::BI__builtin_cabsf;
4331 case Builtin::BIabs:
4332 case Builtin::BIlabs:
4333 case Builtin::BIllabs:
4334 case Builtin::BIfabsf:
4335 case Builtin::BIfabs:
4336 case Builtin::BIfabsl:
4337 return Builtin::BIcabsf;
4338 }
4339 }
4340 llvm_unreachable("Unable to convert function");
4341}
4342
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004343static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004344 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4345 if (!FnInfo)
4346 return 0;
4347
4348 switch (FDecl->getBuiltinID()) {
4349 default:
4350 return 0;
4351 case Builtin::BI__builtin_abs:
4352 case Builtin::BI__builtin_fabs:
4353 case Builtin::BI__builtin_fabsf:
4354 case Builtin::BI__builtin_fabsl:
4355 case Builtin::BI__builtin_labs:
4356 case Builtin::BI__builtin_llabs:
4357 case Builtin::BI__builtin_cabs:
4358 case Builtin::BI__builtin_cabsf:
4359 case Builtin::BI__builtin_cabsl:
4360 case Builtin::BIabs:
4361 case Builtin::BIlabs:
4362 case Builtin::BIllabs:
4363 case Builtin::BIfabs:
4364 case Builtin::BIfabsf:
4365 case Builtin::BIfabsl:
4366 case Builtin::BIcabs:
4367 case Builtin::BIcabsf:
4368 case Builtin::BIcabsl:
4369 return FDecl->getBuiltinID();
4370 }
4371 llvm_unreachable("Unknown Builtin type");
4372}
4373
4374// If the replacement is valid, emit a note with replacement function.
4375// Additionally, suggest including the proper header if not already included.
4376static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004377 unsigned AbsKind, QualType ArgType) {
4378 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004379 const char *HeaderName = nullptr;
4380 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004381 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4382 FunctionName = "std::abs";
4383 if (ArgType->isIntegralOrEnumerationType()) {
4384 HeaderName = "cstdlib";
4385 } else if (ArgType->isRealFloatingType()) {
4386 HeaderName = "cmath";
4387 } else {
4388 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004389 }
Richard Trieubeffb832014-04-15 23:47:53 +00004390
4391 // Lookup all std::abs
4392 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004393 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004394 R.suppressDiagnostics();
4395 S.LookupQualifiedName(R, Std);
4396
4397 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004398 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004399 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4400 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4401 } else {
4402 FDecl = dyn_cast<FunctionDecl>(I);
4403 }
4404 if (!FDecl)
4405 continue;
4406
4407 // Found std::abs(), check that they are the right ones.
4408 if (FDecl->getNumParams() != 1)
4409 continue;
4410
4411 // Check that the parameter type can handle the argument.
4412 QualType ParamType = FDecl->getParamDecl(0)->getType();
4413 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4414 S.Context.getTypeSize(ArgType) <=
4415 S.Context.getTypeSize(ParamType)) {
4416 // Found a function, don't need the header hint.
4417 EmitHeaderHint = false;
4418 break;
4419 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004420 }
Richard Trieubeffb832014-04-15 23:47:53 +00004421 }
4422 } else {
4423 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4424 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4425
4426 if (HeaderName) {
4427 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4428 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4429 R.suppressDiagnostics();
4430 S.LookupName(R, S.getCurScope());
4431
4432 if (R.isSingleResult()) {
4433 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4434 if (FD && FD->getBuiltinID() == AbsKind) {
4435 EmitHeaderHint = false;
4436 } else {
4437 return;
4438 }
4439 } else if (!R.empty()) {
4440 return;
4441 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004442 }
4443 }
4444
4445 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004446 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004447
Richard Trieubeffb832014-04-15 23:47:53 +00004448 if (!HeaderName)
4449 return;
4450
4451 if (!EmitHeaderHint)
4452 return;
4453
Alp Toker5d96e0a2014-07-11 20:53:51 +00004454 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4455 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004456}
4457
4458static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4459 if (!FDecl)
4460 return false;
4461
4462 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4463 return false;
4464
4465 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4466
4467 while (ND && ND->isInlineNamespace()) {
4468 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004469 }
Richard Trieubeffb832014-04-15 23:47:53 +00004470
4471 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4472 return false;
4473
4474 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4475 return false;
4476
4477 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004478}
4479
4480// Warn when using the wrong abs() function.
4481void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4482 const FunctionDecl *FDecl,
4483 IdentifierInfo *FnInfo) {
4484 if (Call->getNumArgs() != 1)
4485 return;
4486
4487 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004488 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4489 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004490 return;
4491
4492 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4493 QualType ParamType = Call->getArg(0)->getType();
4494
Alp Toker5d96e0a2014-07-11 20:53:51 +00004495 // Unsigned types cannot be negative. Suggest removing the absolute value
4496 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004497 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004498 const char *FunctionName =
4499 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004500 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4501 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004502 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004503 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4504 return;
4505 }
4506
Richard Trieubeffb832014-04-15 23:47:53 +00004507 // std::abs has overloads which prevent most of the absolute value problems
4508 // from occurring.
4509 if (IsStdAbs)
4510 return;
4511
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004512 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4513 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4514
4515 // The argument and parameter are the same kind. Check if they are the right
4516 // size.
4517 if (ArgValueKind == ParamValueKind) {
4518 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4519 return;
4520
4521 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4522 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4523 << FDecl << ArgType << ParamType;
4524
4525 if (NewAbsKind == 0)
4526 return;
4527
4528 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004529 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004530 return;
4531 }
4532
4533 // ArgValueKind != ParamValueKind
4534 // The wrong type of absolute value function was used. Attempt to find the
4535 // proper one.
4536 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4537 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4538 if (NewAbsKind == 0)
4539 return;
4540
4541 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4542 << FDecl << ParamValueKind << ArgValueKind;
4543
4544 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004545 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004546 return;
4547}
4548
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004549//===--- CHECK: Standard memory functions ---------------------------------===//
4550
Nico Weber0e6daef2013-12-26 23:38:39 +00004551/// \brief Takes the expression passed to the size_t parameter of functions
4552/// such as memcmp, strncat, etc and warns if it's a comparison.
4553///
4554/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4555static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4556 IdentifierInfo *FnName,
4557 SourceLocation FnLoc,
4558 SourceLocation RParenLoc) {
4559 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4560 if (!Size)
4561 return false;
4562
4563 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4564 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4565 return false;
4566
Nico Weber0e6daef2013-12-26 23:38:39 +00004567 SourceRange SizeRange = Size->getSourceRange();
4568 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4569 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004570 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004571 << FnName << FixItHint::CreateInsertion(
4572 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004573 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004574 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004575 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004576 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4577 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004578
4579 return true;
4580}
4581
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004582/// \brief Determine whether the given type is or contains a dynamic class type
4583/// (e.g., whether it has a vtable).
4584static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4585 bool &IsContained) {
4586 // Look through array types while ignoring qualifiers.
4587 const Type *Ty = T->getBaseElementTypeUnsafe();
4588 IsContained = false;
4589
4590 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4591 RD = RD ? RD->getDefinition() : nullptr;
4592 if (!RD)
4593 return nullptr;
4594
4595 if (RD->isDynamicClass())
4596 return RD;
4597
4598 // Check all the fields. If any bases were dynamic, the class is dynamic.
4599 // It's impossible for a class to transitively contain itself by value, so
4600 // infinite recursion is impossible.
4601 for (auto *FD : RD->fields()) {
4602 bool SubContained;
4603 if (const CXXRecordDecl *ContainedRD =
4604 getContainedDynamicClass(FD->getType(), SubContained)) {
4605 IsContained = true;
4606 return ContainedRD;
4607 }
4608 }
4609
4610 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004611}
4612
Chandler Carruth889ed862011-06-21 23:04:20 +00004613/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004614/// otherwise returns NULL.
4615static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004616 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004617 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4618 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4619 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004620
Craig Topperc3ec1492014-05-26 06:22:03 +00004621 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004622}
4623
Chandler Carruth889ed862011-06-21 23:04:20 +00004624/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004625static QualType getSizeOfArgType(const Expr* E) {
4626 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4627 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4628 if (SizeOf->getKind() == clang::UETT_SizeOf)
4629 return SizeOf->getTypeOfArgument();
4630
4631 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004632}
4633
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004634/// \brief Check for dangerous or invalid arguments to memset().
4635///
Chandler Carruthac687262011-06-03 06:23:57 +00004636/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004637/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4638/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004639///
4640/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004641void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004642 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004643 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004644 assert(BId != 0);
4645
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004646 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004647 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004648 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004649 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004650 return;
4651
Anna Zaks22122702012-01-17 00:37:07 +00004652 unsigned LastArg = (BId == Builtin::BImemset ||
4653 BId == Builtin::BIstrndup ? 1 : 2);
4654 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004655 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004656
Nico Weber0e6daef2013-12-26 23:38:39 +00004657 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4658 Call->getLocStart(), Call->getRParenLoc()))
4659 return;
4660
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004661 // We have special checking when the length is a sizeof expression.
4662 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4663 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4664 llvm::FoldingSetNodeID SizeOfArgID;
4665
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004666 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4667 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004668 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004669
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004670 QualType DestTy = Dest->getType();
4671 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4672 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004673
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004674 // Never warn about void type pointers. This can be used to suppress
4675 // false positives.
4676 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004677 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004678
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004679 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4680 // actually comparing the expressions for equality. Because computing the
4681 // expression IDs can be expensive, we only do this if the diagnostic is
4682 // enabled.
4683 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004684 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4685 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004686 // We only compute IDs for expressions if the warning is enabled, and
4687 // cache the sizeof arg's ID.
4688 if (SizeOfArgID == llvm::FoldingSetNodeID())
4689 SizeOfArg->Profile(SizeOfArgID, Context, true);
4690 llvm::FoldingSetNodeID DestID;
4691 Dest->Profile(DestID, Context, true);
4692 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004693 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4694 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004695 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004696 StringRef ReadableName = FnName->getName();
4697
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004698 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004699 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004700 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004701 if (!PointeeTy->isIncompleteType() &&
4702 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004703 ActionIdx = 2; // If the pointee's size is sizeof(char),
4704 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004705
4706 // If the function is defined as a builtin macro, do not show macro
4707 // expansion.
4708 SourceLocation SL = SizeOfArg->getExprLoc();
4709 SourceRange DSR = Dest->getSourceRange();
4710 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004711 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004712
4713 if (SM.isMacroArgExpansion(SL)) {
4714 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4715 SL = SM.getSpellingLoc(SL);
4716 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4717 SM.getSpellingLoc(DSR.getEnd()));
4718 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4719 SM.getSpellingLoc(SSR.getEnd()));
4720 }
4721
Anna Zaksd08d9152012-05-30 23:14:52 +00004722 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004723 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004724 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004725 << PointeeTy
4726 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004727 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004728 << SSR);
4729 DiagRuntimeBehavior(SL, SizeOfArg,
4730 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4731 << ActionIdx
4732 << SSR);
4733
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004734 break;
4735 }
4736 }
4737
4738 // Also check for cases where the sizeof argument is the exact same
4739 // type as the memory argument, and where it points to a user-defined
4740 // record type.
4741 if (SizeOfArgTy != QualType()) {
4742 if (PointeeTy->isRecordType() &&
4743 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4744 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4745 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4746 << FnName << SizeOfArgTy << ArgIdx
4747 << PointeeTy << Dest->getSourceRange()
4748 << LenExpr->getSourceRange());
4749 break;
4750 }
Nico Weberc5e73862011-06-14 16:14:58 +00004751 }
4752
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004753 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004754 bool IsContained;
4755 if (const CXXRecordDecl *ContainedRD =
4756 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004757
4758 unsigned OperationType = 0;
4759 // "overwritten" if we're warning about the destination for any call
4760 // but memcmp; otherwise a verb appropriate to the call.
4761 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4762 if (BId == Builtin::BImemcpy)
4763 OperationType = 1;
4764 else if(BId == Builtin::BImemmove)
4765 OperationType = 2;
4766 else if (BId == Builtin::BImemcmp)
4767 OperationType = 3;
4768 }
4769
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004770 DiagRuntimeBehavior(
4771 Dest->getExprLoc(), Dest,
4772 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004773 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004774 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004775 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004776 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4777 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004778 DiagRuntimeBehavior(
4779 Dest->getExprLoc(), Dest,
4780 PDiag(diag::warn_arc_object_memaccess)
4781 << ArgIdx << FnName << PointeeTy
4782 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004783 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004784 continue;
John McCall31168b02011-06-15 23:02:42 +00004785
4786 DiagRuntimeBehavior(
4787 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004788 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004789 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4790 break;
4791 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004792 }
4793}
4794
Ted Kremenek6865f772011-08-18 20:55:45 +00004795// A little helper routine: ignore addition and subtraction of integer literals.
4796// This intentionally does not ignore all integer constant expressions because
4797// we don't want to remove sizeof().
4798static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4799 Ex = Ex->IgnoreParenCasts();
4800
4801 for (;;) {
4802 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4803 if (!BO || !BO->isAdditiveOp())
4804 break;
4805
4806 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4807 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4808
4809 if (isa<IntegerLiteral>(RHS))
4810 Ex = LHS;
4811 else if (isa<IntegerLiteral>(LHS))
4812 Ex = RHS;
4813 else
4814 break;
4815 }
4816
4817 return Ex;
4818}
4819
Anna Zaks13b08572012-08-08 21:42:23 +00004820static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4821 ASTContext &Context) {
4822 // Only handle constant-sized or VLAs, but not flexible members.
4823 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4824 // Only issue the FIXIT for arrays of size > 1.
4825 if (CAT->getSize().getSExtValue() <= 1)
4826 return false;
4827 } else if (!Ty->isVariableArrayType()) {
4828 return false;
4829 }
4830 return true;
4831}
4832
Ted Kremenek6865f772011-08-18 20:55:45 +00004833// Warn if the user has made the 'size' argument to strlcpy or strlcat
4834// be the size of the source, instead of the destination.
4835void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4836 IdentifierInfo *FnName) {
4837
4838 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004839 unsigned NumArgs = Call->getNumArgs();
4840 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004841 return;
4842
4843 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4844 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004845 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004846
4847 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4848 Call->getLocStart(), Call->getRParenLoc()))
4849 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004850
4851 // Look for 'strlcpy(dst, x, sizeof(x))'
4852 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4853 CompareWithSrc = Ex;
4854 else {
4855 // Look for 'strlcpy(dst, x, strlen(x))'
4856 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004857 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4858 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004859 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4860 }
4861 }
4862
4863 if (!CompareWithSrc)
4864 return;
4865
4866 // Determine if the argument to sizeof/strlen is equal to the source
4867 // argument. In principle there's all kinds of things you could do
4868 // here, for instance creating an == expression and evaluating it with
4869 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4870 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4871 if (!SrcArgDRE)
4872 return;
4873
4874 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4875 if (!CompareWithSrcDRE ||
4876 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4877 return;
4878
4879 const Expr *OriginalSizeArg = Call->getArg(2);
4880 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4881 << OriginalSizeArg->getSourceRange() << FnName;
4882
4883 // Output a FIXIT hint if the destination is an array (rather than a
4884 // pointer to an array). This could be enhanced to handle some
4885 // pointers if we know the actual size, like if DstArg is 'array+2'
4886 // we could say 'sizeof(array)-2'.
4887 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004888 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004889 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004890
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004891 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004892 llvm::raw_svector_ostream OS(sizeString);
4893 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004894 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004895 OS << ")";
4896
4897 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4898 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4899 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004900}
4901
Anna Zaks314cd092012-02-01 19:08:57 +00004902/// Check if two expressions refer to the same declaration.
4903static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4904 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4905 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4906 return D1->getDecl() == D2->getDecl();
4907 return false;
4908}
4909
4910static const Expr *getStrlenExprArg(const Expr *E) {
4911 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4912 const FunctionDecl *FD = CE->getDirectCallee();
4913 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004914 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004915 return CE->getArg(0)->IgnoreParenCasts();
4916 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004917 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004918}
4919
4920// Warn on anti-patterns as the 'size' argument to strncat.
4921// The correct size argument should look like following:
4922// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4923void Sema::CheckStrncatArguments(const CallExpr *CE,
4924 IdentifierInfo *FnName) {
4925 // Don't crash if the user has the wrong number of arguments.
4926 if (CE->getNumArgs() < 3)
4927 return;
4928 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4929 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4930 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4931
Nico Weber0e6daef2013-12-26 23:38:39 +00004932 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4933 CE->getRParenLoc()))
4934 return;
4935
Anna Zaks314cd092012-02-01 19:08:57 +00004936 // Identify common expressions, which are wrongly used as the size argument
4937 // to strncat and may lead to buffer overflows.
4938 unsigned PatternType = 0;
4939 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4940 // - sizeof(dst)
4941 if (referToTheSameDecl(SizeOfArg, DstArg))
4942 PatternType = 1;
4943 // - sizeof(src)
4944 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4945 PatternType = 2;
4946 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4947 if (BE->getOpcode() == BO_Sub) {
4948 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4949 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4950 // - sizeof(dst) - strlen(dst)
4951 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4952 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4953 PatternType = 1;
4954 // - sizeof(src) - (anything)
4955 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4956 PatternType = 2;
4957 }
4958 }
4959
4960 if (PatternType == 0)
4961 return;
4962
Anna Zaks5069aa32012-02-03 01:27:37 +00004963 // Generate the diagnostic.
4964 SourceLocation SL = LenArg->getLocStart();
4965 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004966 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004967
4968 // If the function is defined as a builtin macro, do not show macro expansion.
4969 if (SM.isMacroArgExpansion(SL)) {
4970 SL = SM.getSpellingLoc(SL);
4971 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4972 SM.getSpellingLoc(SR.getEnd()));
4973 }
4974
Anna Zaks13b08572012-08-08 21:42:23 +00004975 // Check if the destination is an array (rather than a pointer to an array).
4976 QualType DstTy = DstArg->getType();
4977 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4978 Context);
4979 if (!isKnownSizeArray) {
4980 if (PatternType == 1)
4981 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4982 else
4983 Diag(SL, diag::warn_strncat_src_size) << SR;
4984 return;
4985 }
4986
Anna Zaks314cd092012-02-01 19:08:57 +00004987 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004988 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004989 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004990 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004991
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004992 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004993 llvm::raw_svector_ostream OS(sizeString);
4994 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004995 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004996 OS << ") - ";
4997 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004998 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004999 OS << ") - 1";
5000
Anna Zaks5069aa32012-02-03 01:27:37 +00005001 Diag(SL, diag::note_strncat_wrong_size)
5002 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005003}
5004
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005005//===--- CHECK: Return Address of Stack Variable --------------------------===//
5006
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005007static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5008 Decl *ParentDecl);
5009static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5010 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005011
5012/// CheckReturnStackAddr - Check if a return statement returns the address
5013/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005014static void
5015CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5016 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005017
Craig Topperc3ec1492014-05-26 06:22:03 +00005018 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005019 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005020
5021 // Perform checking for returned stack addresses, local blocks,
5022 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005023 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005024 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005025 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005026 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005027 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005028 }
5029
Craig Topperc3ec1492014-05-26 06:22:03 +00005030 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005031 return; // Nothing suspicious was found.
5032
5033 SourceLocation diagLoc;
5034 SourceRange diagRange;
5035 if (refVars.empty()) {
5036 diagLoc = stackE->getLocStart();
5037 diagRange = stackE->getSourceRange();
5038 } else {
5039 // We followed through a reference variable. 'stackE' contains the
5040 // problematic expression but we will warn at the return statement pointing
5041 // at the reference variable. We will later display the "trail" of
5042 // reference variables using notes.
5043 diagLoc = refVars[0]->getLocStart();
5044 diagRange = refVars[0]->getSourceRange();
5045 }
5046
5047 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005048 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005049 : diag::warn_ret_stack_addr)
5050 << DR->getDecl()->getDeclName() << diagRange;
5051 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005052 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005053 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005054 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005055 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005056 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5057 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005058 << diagRange;
5059 }
5060
5061 // Display the "trail" of reference variables that we followed until we
5062 // found the problematic expression using notes.
5063 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5064 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5065 // If this var binds to another reference var, show the range of the next
5066 // var, otherwise the var binds to the problematic expression, in which case
5067 // show the range of the expression.
5068 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5069 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005070 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5071 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005072 }
5073}
5074
5075/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5076/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005077/// to a location on the stack, a local block, an address of a label, or a
5078/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005079/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005080/// encounter a subexpression that (1) clearly does not lead to one of the
5081/// above problematic expressions (2) is something we cannot determine leads to
5082/// a problematic expression based on such local checking.
5083///
5084/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5085/// the expression that they point to. Such variables are added to the
5086/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005087///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005088/// EvalAddr processes expressions that are pointers that are used as
5089/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005090/// At the base case of the recursion is a check for the above problematic
5091/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005092///
5093/// This implementation handles:
5094///
5095/// * pointer-to-pointer casts
5096/// * implicit conversions from array references to pointers
5097/// * taking the address of fields
5098/// * arbitrary interplay between "&" and "*" operators
5099/// * pointer arithmetic from an address of a stack variable
5100/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005101static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5102 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005103 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005104 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005105
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005106 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005107 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005108 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005109 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005110 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005111
Peter Collingbourne91147592011-04-15 00:35:48 +00005112 E = E->IgnoreParens();
5113
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005114 // Our "symbolic interpreter" is just a dispatch off the currently
5115 // viewed AST node. We then recursively traverse the AST by calling
5116 // EvalAddr and EvalVal appropriately.
5117 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005118 case Stmt::DeclRefExprClass: {
5119 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5120
Richard Smith40f08eb2014-01-30 22:05:38 +00005121 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005122 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005123 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005124
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005125 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5126 // If this is a reference variable, follow through to the expression that
5127 // it points to.
5128 if (V->hasLocalStorage() &&
5129 V->getType()->isReferenceType() && V->hasInit()) {
5130 // Add the reference variable to the "trail".
5131 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005132 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005133 }
5134
Craig Topperc3ec1492014-05-26 06:22:03 +00005135 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005136 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005137
Chris Lattner934edb22007-12-28 05:31:15 +00005138 case Stmt::UnaryOperatorClass: {
5139 // The only unary operator that make sense to handle here
5140 // is AddrOf. All others don't make sense as pointers.
5141 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005142
John McCalle3027922010-08-25 11:45:40 +00005143 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005144 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005145 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005146 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005147 }
Mike Stump11289f42009-09-09 15:08:12 +00005148
Chris Lattner934edb22007-12-28 05:31:15 +00005149 case Stmt::BinaryOperatorClass: {
5150 // Handle pointer arithmetic. All other binary operators are not valid
5151 // in this context.
5152 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005153 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005154
John McCalle3027922010-08-25 11:45:40 +00005155 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005156 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005157
Chris Lattner934edb22007-12-28 05:31:15 +00005158 Expr *Base = B->getLHS();
5159
5160 // Determine which argument is the real pointer base. It could be
5161 // the RHS argument instead of the LHS.
5162 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005163
Chris Lattner934edb22007-12-28 05:31:15 +00005164 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005165 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005166 }
Steve Naroff2752a172008-09-10 19:17:48 +00005167
Chris Lattner934edb22007-12-28 05:31:15 +00005168 // For conditional operators we need to see if either the LHS or RHS are
5169 // valid DeclRefExpr*s. If one of them is valid, we return it.
5170 case Stmt::ConditionalOperatorClass: {
5171 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005172
Chris Lattner934edb22007-12-28 05:31:15 +00005173 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005174 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5175 if (Expr *LHSExpr = C->getLHS()) {
5176 // In C++, we can have a throw-expression, which has 'void' type.
5177 if (!LHSExpr->getType()->isVoidType())
5178 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005179 return LHS;
5180 }
Chris Lattner934edb22007-12-28 05:31:15 +00005181
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005182 // In C++, we can have a throw-expression, which has 'void' type.
5183 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005184 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005185
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005186 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005187 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005188
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005189 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005190 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005191 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005192 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005193
5194 case Stmt::AddrLabelExprClass:
5195 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005196
John McCall28fc7092011-11-10 05:35:25 +00005197 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005198 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5199 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005200
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005201 // For casts, we need to handle conversions from arrays to
5202 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005203 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005204 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005205 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005206 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005207 case Stmt::CXXStaticCastExprClass:
5208 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005209 case Stmt::CXXConstCastExprClass:
5210 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005211 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5212 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005213 case CK_LValueToRValue:
5214 case CK_NoOp:
5215 case CK_BaseToDerived:
5216 case CK_DerivedToBase:
5217 case CK_UncheckedDerivedToBase:
5218 case CK_Dynamic:
5219 case CK_CPointerToObjCPointerCast:
5220 case CK_BlockPointerToObjCPointerCast:
5221 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005222 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005223
5224 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005225 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005226
Richard Trieudadefde2014-07-02 04:39:38 +00005227 case CK_BitCast:
5228 if (SubExpr->getType()->isAnyPointerType() ||
5229 SubExpr->getType()->isBlockPointerType() ||
5230 SubExpr->getType()->isObjCQualifiedIdType())
5231 return EvalAddr(SubExpr, refVars, ParentDecl);
5232 else
5233 return nullptr;
5234
Eli Friedman8195ad72012-02-23 23:04:32 +00005235 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005236 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005237 }
Chris Lattner934edb22007-12-28 05:31:15 +00005238 }
Mike Stump11289f42009-09-09 15:08:12 +00005239
Douglas Gregorfe314812011-06-21 17:03:29 +00005240 case Stmt::MaterializeTemporaryExprClass:
5241 if (Expr *Result = EvalAddr(
5242 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005243 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005244 return Result;
5245
5246 return E;
5247
Chris Lattner934edb22007-12-28 05:31:15 +00005248 // Everything else: we simply don't reason about them.
5249 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005250 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005251 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005252}
Mike Stump11289f42009-09-09 15:08:12 +00005253
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005254
5255/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5256/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005257static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5258 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005259do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005260 // We should only be called for evaluating non-pointer expressions, or
5261 // expressions with a pointer type that are not used as references but instead
5262 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005263
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005264 // Our "symbolic interpreter" is just a dispatch off the currently
5265 // viewed AST node. We then recursively traverse the AST by calling
5266 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005267
5268 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005269 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005270 case Stmt::ImplicitCastExprClass: {
5271 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005272 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005273 E = IE->getSubExpr();
5274 continue;
5275 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005276 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005277 }
5278
John McCall28fc7092011-11-10 05:35:25 +00005279 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005280 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005281
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005282 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005283 // When we hit a DeclRefExpr we are looking at code that refers to a
5284 // variable's name. If it's not a reference variable we check if it has
5285 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005286 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005287
Richard Smith40f08eb2014-01-30 22:05:38 +00005288 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005289 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005290 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005291
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005292 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5293 // Check if it refers to itself, e.g. "int& i = i;".
5294 if (V == ParentDecl)
5295 return DR;
5296
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005297 if (V->hasLocalStorage()) {
5298 if (!V->getType()->isReferenceType())
5299 return DR;
5300
5301 // Reference variable, follow through to the expression that
5302 // it points to.
5303 if (V->hasInit()) {
5304 // Add the reference variable to the "trail".
5305 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005306 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005307 }
5308 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005309 }
Mike Stump11289f42009-09-09 15:08:12 +00005310
Craig Topperc3ec1492014-05-26 06:22:03 +00005311 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005312 }
Mike Stump11289f42009-09-09 15:08:12 +00005313
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005314 case Stmt::UnaryOperatorClass: {
5315 // The only unary operator that make sense to handle here
5316 // is Deref. All others don't resolve to a "name." This includes
5317 // handling all sorts of rvalues passed to a unary operator.
5318 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005319
John McCalle3027922010-08-25 11:45:40 +00005320 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005321 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005322
Craig Topperc3ec1492014-05-26 06:22:03 +00005323 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005324 }
Mike Stump11289f42009-09-09 15:08:12 +00005325
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005326 case Stmt::ArraySubscriptExprClass: {
5327 // Array subscripts are potential references to data on the stack. We
5328 // retrieve the DeclRefExpr* for the array variable if it indeed
5329 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005330 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005331 }
Mike Stump11289f42009-09-09 15:08:12 +00005332
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005333 case Stmt::ConditionalOperatorClass: {
5334 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005335 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005336 ConditionalOperator *C = cast<ConditionalOperator>(E);
5337
Anders Carlsson801c5c72007-11-30 19:04:31 +00005338 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005339 if (Expr *LHSExpr = C->getLHS()) {
5340 // In C++, we can have a throw-expression, which has 'void' type.
5341 if (!LHSExpr->getType()->isVoidType())
5342 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5343 return LHS;
5344 }
5345
5346 // In C++, we can have a throw-expression, which has 'void' type.
5347 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005348 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005349
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005350 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005351 }
Mike Stump11289f42009-09-09 15:08:12 +00005352
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005353 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005354 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005355 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005356
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005357 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005358 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005359 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005360
5361 // Check whether the member type is itself a reference, in which case
5362 // we're not going to refer to the member, but to what the member refers to.
5363 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005364 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005365
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005366 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005367 }
Mike Stump11289f42009-09-09 15:08:12 +00005368
Douglas Gregorfe314812011-06-21 17:03:29 +00005369 case Stmt::MaterializeTemporaryExprClass:
5370 if (Expr *Result = EvalVal(
5371 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005372 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005373 return Result;
5374
5375 return E;
5376
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005377 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005378 // Check that we don't return or take the address of a reference to a
5379 // temporary. This is only useful in C++.
5380 if (!E->isTypeDependent() && E->isRValue())
5381 return E;
5382
5383 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005384 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005385 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005386} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005387}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005388
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005389void
5390Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5391 SourceLocation ReturnLoc,
5392 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005393 const AttrVec *Attrs,
5394 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005395 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5396
5397 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005398 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5399 CheckNonNullExpr(*this, RetValExp))
5400 Diag(ReturnLoc, diag::warn_null_ret)
5401 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005402
5403 // C++11 [basic.stc.dynamic.allocation]p4:
5404 // If an allocation function declared with a non-throwing
5405 // exception-specification fails to allocate storage, it shall return
5406 // a null pointer. Any other allocation function that fails to allocate
5407 // storage shall indicate failure only by throwing an exception [...]
5408 if (FD) {
5409 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5410 if (Op == OO_New || Op == OO_Array_New) {
5411 const FunctionProtoType *Proto
5412 = FD->getType()->castAs<FunctionProtoType>();
5413 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5414 CheckNonNullExpr(*this, RetValExp))
5415 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5416 << FD << getLangOpts().CPlusPlus11;
5417 }
5418 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005419}
5420
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005421//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5422
5423/// Check for comparisons of floating point operands using != and ==.
5424/// Issue a warning if these are no self-comparisons, as they are not likely
5425/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005426void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005427 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5428 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005429
5430 // Special case: check for x == x (which is OK).
5431 // Do not emit warnings for such cases.
5432 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5433 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5434 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005435 return;
Mike Stump11289f42009-09-09 15:08:12 +00005436
5437
Ted Kremenekeda40e22007-11-29 00:59:04 +00005438 // Special case: check for comparisons against literals that can be exactly
5439 // represented by APFloat. In such cases, do not emit a warning. This
5440 // is a heuristic: often comparison against such literals are used to
5441 // detect if a value in a variable has not changed. This clearly can
5442 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005443 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5444 if (FLL->isExact())
5445 return;
5446 } else
5447 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5448 if (FLR->isExact())
5449 return;
Mike Stump11289f42009-09-09 15:08:12 +00005450
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005451 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005452 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005453 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005454 return;
Mike Stump11289f42009-09-09 15:08:12 +00005455
David Blaikie1f4ff152012-07-16 20:47:22 +00005456 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005457 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005458 return;
Mike Stump11289f42009-09-09 15:08:12 +00005459
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005460 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005461 Diag(Loc, diag::warn_floatingpoint_eq)
5462 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005463}
John McCallca01b222010-01-04 23:21:16 +00005464
John McCall70aa5392010-01-06 05:24:50 +00005465//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5466//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005467
John McCall70aa5392010-01-06 05:24:50 +00005468namespace {
John McCallca01b222010-01-04 23:21:16 +00005469
John McCall70aa5392010-01-06 05:24:50 +00005470/// Structure recording the 'active' range of an integer-valued
5471/// expression.
5472struct IntRange {
5473 /// The number of bits active in the int.
5474 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005475
John McCall70aa5392010-01-06 05:24:50 +00005476 /// True if the int is known not to have negative values.
5477 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005478
John McCall70aa5392010-01-06 05:24:50 +00005479 IntRange(unsigned Width, bool NonNegative)
5480 : Width(Width), NonNegative(NonNegative)
5481 {}
John McCallca01b222010-01-04 23:21:16 +00005482
John McCall817d4af2010-11-10 23:38:19 +00005483 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005484 static IntRange forBoolType() {
5485 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005486 }
5487
John McCall817d4af2010-11-10 23:38:19 +00005488 /// Returns the range of an opaque value of the given integral type.
5489 static IntRange forValueOfType(ASTContext &C, QualType T) {
5490 return forValueOfCanonicalType(C,
5491 T->getCanonicalTypeInternal().getTypePtr());
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 a canonical integral type.
5495 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005496 assert(T->isCanonicalUnqualified());
5497
5498 if (const VectorType *VT = dyn_cast<VectorType>(T))
5499 T = VT->getElementType().getTypePtr();
5500 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5501 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005502 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5503 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005504
David Majnemer6a426652013-06-07 22:07:20 +00005505 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005506 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005507 EnumDecl *Enum = ET->getDecl();
5508 if (!Enum->isCompleteDefinition())
5509 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005510
David Majnemer6a426652013-06-07 22:07:20 +00005511 unsigned NumPositive = Enum->getNumPositiveBits();
5512 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005513
David Majnemer6a426652013-06-07 22:07:20 +00005514 if (NumNegative == 0)
5515 return IntRange(NumPositive, true/*NonNegative*/);
5516 else
5517 return IntRange(std::max(NumPositive + 1, NumNegative),
5518 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005519 }
John McCall70aa5392010-01-06 05:24:50 +00005520
5521 const BuiltinType *BT = cast<BuiltinType>(T);
5522 assert(BT->isInteger());
5523
5524 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5525 }
5526
John McCall817d4af2010-11-10 23:38:19 +00005527 /// Returns the "target" range of a canonical integral type, i.e.
5528 /// the range of values expressible in the type.
5529 ///
5530 /// This matches forValueOfCanonicalType except that enums have the
5531 /// full range of their type, not the range of their enumerators.
5532 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5533 assert(T->isCanonicalUnqualified());
5534
5535 if (const VectorType *VT = dyn_cast<VectorType>(T))
5536 T = VT->getElementType().getTypePtr();
5537 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5538 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005539 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5540 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005541 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005542 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005543
5544 const BuiltinType *BT = cast<BuiltinType>(T);
5545 assert(BT->isInteger());
5546
5547 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5548 }
5549
5550 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005551 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005552 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005553 L.NonNegative && R.NonNegative);
5554 }
5555
John McCall817d4af2010-11-10 23:38:19 +00005556 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005557 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005558 return IntRange(std::min(L.Width, R.Width),
5559 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005560 }
5561};
5562
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005563static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5564 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005565 if (value.isSigned() && value.isNegative())
5566 return IntRange(value.getMinSignedBits(), false);
5567
5568 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005569 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005570
5571 // isNonNegative() just checks the sign bit without considering
5572 // signedness.
5573 return IntRange(value.getActiveBits(), true);
5574}
5575
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005576static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5577 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005578 if (result.isInt())
5579 return GetValueRange(C, result.getInt(), MaxWidth);
5580
5581 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005582 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5583 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5584 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5585 R = IntRange::join(R, El);
5586 }
John McCall70aa5392010-01-06 05:24:50 +00005587 return R;
5588 }
5589
5590 if (result.isComplexInt()) {
5591 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5592 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5593 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005594 }
5595
5596 // This can happen with lossless casts to intptr_t of "based" lvalues.
5597 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005598 // FIXME: The only reason we need to pass the type in here is to get
5599 // the sign right on this one case. It would be nice if APValue
5600 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005601 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005602 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005603}
John McCall70aa5392010-01-06 05:24:50 +00005604
Eli Friedmane6d33952013-07-08 20:20:06 +00005605static QualType GetExprType(Expr *E) {
5606 QualType Ty = E->getType();
5607 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5608 Ty = AtomicRHS->getValueType();
5609 return Ty;
5610}
5611
John McCall70aa5392010-01-06 05:24:50 +00005612/// Pseudo-evaluate the given integer expression, estimating the
5613/// range of values it might take.
5614///
5615/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005616static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005617 E = E->IgnoreParens();
5618
5619 // Try a full evaluation first.
5620 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005621 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005622 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005623
5624 // I think we only want to look through implicit casts here; if the
5625 // user has an explicit widening cast, we should treat the value as
5626 // being of the new, wider type.
5627 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005628 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005629 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5630
Eli Friedmane6d33952013-07-08 20:20:06 +00005631 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005632
John McCalle3027922010-08-25 11:45:40 +00005633 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005634
John McCall70aa5392010-01-06 05:24:50 +00005635 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005636 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005637 return OutputTypeRange;
5638
5639 IntRange SubRange
5640 = GetExprRange(C, CE->getSubExpr(),
5641 std::min(MaxWidth, OutputTypeRange.Width));
5642
5643 // Bail out if the subexpr's range is as wide as the cast type.
5644 if (SubRange.Width >= OutputTypeRange.Width)
5645 return OutputTypeRange;
5646
5647 // Otherwise, we take the smaller width, and we're non-negative if
5648 // either the output type or the subexpr is.
5649 return IntRange(SubRange.Width,
5650 SubRange.NonNegative || OutputTypeRange.NonNegative);
5651 }
5652
5653 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5654 // If we can fold the condition, just take that operand.
5655 bool CondResult;
5656 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5657 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5658 : CO->getFalseExpr(),
5659 MaxWidth);
5660
5661 // Otherwise, conservatively merge.
5662 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5663 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5664 return IntRange::join(L, R);
5665 }
5666
5667 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5668 switch (BO->getOpcode()) {
5669
5670 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005671 case BO_LAnd:
5672 case BO_LOr:
5673 case BO_LT:
5674 case BO_GT:
5675 case BO_LE:
5676 case BO_GE:
5677 case BO_EQ:
5678 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005679 return IntRange::forBoolType();
5680
John McCallc3688382011-07-13 06:35:24 +00005681 // The type of the assignments is the type of the LHS, so the RHS
5682 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005683 case BO_MulAssign:
5684 case BO_DivAssign:
5685 case BO_RemAssign:
5686 case BO_AddAssign:
5687 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005688 case BO_XorAssign:
5689 case BO_OrAssign:
5690 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005691 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005692
John McCallc3688382011-07-13 06:35:24 +00005693 // Simple assignments just pass through the RHS, which will have
5694 // been coerced to the LHS type.
5695 case BO_Assign:
5696 // TODO: bitfields?
5697 return GetExprRange(C, BO->getRHS(), MaxWidth);
5698
John McCall70aa5392010-01-06 05:24:50 +00005699 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005700 case BO_PtrMemD:
5701 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005702 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005703
John McCall2ce81ad2010-01-06 22:07:33 +00005704 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005705 case BO_And:
5706 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005707 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5708 GetExprRange(C, BO->getRHS(), MaxWidth));
5709
John McCall70aa5392010-01-06 05:24:50 +00005710 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005711 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005712 // ...except that we want to treat '1 << (blah)' as logically
5713 // positive. It's an important idiom.
5714 if (IntegerLiteral *I
5715 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5716 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005717 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005718 return IntRange(R.Width, /*NonNegative*/ true);
5719 }
5720 }
5721 // fallthrough
5722
John McCalle3027922010-08-25 11:45:40 +00005723 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005724 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005725
John McCall2ce81ad2010-01-06 22:07:33 +00005726 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005727 case BO_Shr:
5728 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005729 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5730
5731 // If the shift amount is a positive constant, drop the width by
5732 // that much.
5733 llvm::APSInt shift;
5734 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5735 shift.isNonNegative()) {
5736 unsigned zext = shift.getZExtValue();
5737 if (zext >= L.Width)
5738 L.Width = (L.NonNegative ? 0 : 1);
5739 else
5740 L.Width -= zext;
5741 }
5742
5743 return L;
5744 }
5745
5746 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005747 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005748 return GetExprRange(C, BO->getRHS(), MaxWidth);
5749
John McCall2ce81ad2010-01-06 22:07:33 +00005750 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005751 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005752 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005753 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005754 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005755
John McCall51431812011-07-14 22:39:48 +00005756 // The width of a division result is mostly determined by the size
5757 // of the LHS.
5758 case BO_Div: {
5759 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005760 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005761 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5762
5763 // If the divisor is constant, use that.
5764 llvm::APSInt divisor;
5765 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5766 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5767 if (log2 >= L.Width)
5768 L.Width = (L.NonNegative ? 0 : 1);
5769 else
5770 L.Width = std::min(L.Width - log2, MaxWidth);
5771 return L;
5772 }
5773
5774 // Otherwise, just use the LHS's width.
5775 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5776 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5777 }
5778
5779 // The result of a remainder can't be larger than the result of
5780 // either side.
5781 case BO_Rem: {
5782 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005783 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005784 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5785 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5786
5787 IntRange meet = IntRange::meet(L, R);
5788 meet.Width = std::min(meet.Width, MaxWidth);
5789 return meet;
5790 }
5791
5792 // The default behavior is okay for these.
5793 case BO_Mul:
5794 case BO_Add:
5795 case BO_Xor:
5796 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005797 break;
5798 }
5799
John McCall51431812011-07-14 22:39:48 +00005800 // The default case is to treat the operation as if it were closed
5801 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005802 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5803 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5804 return IntRange::join(L, R);
5805 }
5806
5807 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5808 switch (UO->getOpcode()) {
5809 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005810 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005811 return IntRange::forBoolType();
5812
5813 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005814 case UO_Deref:
5815 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005816 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005817
5818 default:
5819 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5820 }
5821 }
5822
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005823 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5824 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5825
John McCalld25db7e2013-05-06 21:39:12 +00005826 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005827 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005828 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005829
Eli Friedmane6d33952013-07-08 20:20:06 +00005830 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005831}
John McCall263a48b2010-01-04 23:31:57 +00005832
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005833static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005834 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005835}
5836
John McCall263a48b2010-01-04 23:31:57 +00005837/// Checks whether the given value, which currently has the given
5838/// source semantics, has the same value when coerced through the
5839/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005840static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5841 const llvm::fltSemantics &Src,
5842 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005843 llvm::APFloat truncated = value;
5844
5845 bool ignored;
5846 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5847 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5848
5849 return truncated.bitwiseIsEqual(value);
5850}
5851
5852/// Checks whether the given value, which currently has the given
5853/// source semantics, has the same value when coerced through the
5854/// target semantics.
5855///
5856/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005857static bool IsSameFloatAfterCast(const APValue &value,
5858 const llvm::fltSemantics &Src,
5859 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005860 if (value.isFloat())
5861 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5862
5863 if (value.isVector()) {
5864 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5865 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5866 return false;
5867 return true;
5868 }
5869
5870 assert(value.isComplexFloat());
5871 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5872 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5873}
5874
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005875static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005876
Ted Kremenek6274be42010-09-23 21:43:44 +00005877static bool IsZero(Sema &S, Expr *E) {
5878 // Suppress cases where we are comparing against an enum constant.
5879 if (const DeclRefExpr *DR =
5880 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5881 if (isa<EnumConstantDecl>(DR->getDecl()))
5882 return false;
5883
5884 // Suppress cases where the '0' value is expanded from a macro.
5885 if (E->getLocStart().isMacroID())
5886 return false;
5887
John McCallcc7e5bf2010-05-06 08:58:33 +00005888 llvm::APSInt Value;
5889 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5890}
5891
John McCall2551c1b2010-10-06 00:25:24 +00005892static bool HasEnumType(Expr *E) {
5893 // Strip off implicit integral promotions.
5894 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005895 if (ICE->getCastKind() != CK_IntegralCast &&
5896 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005897 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005898 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005899 }
5900
5901 return E->getType()->isEnumeralType();
5902}
5903
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005904static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005905 // Disable warning in template instantiations.
5906 if (!S.ActiveTemplateInstantiations.empty())
5907 return;
5908
John McCalle3027922010-08-25 11:45:40 +00005909 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005910 if (E->isValueDependent())
5911 return;
5912
John McCalle3027922010-08-25 11:45:40 +00005913 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005914 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005915 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005916 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005917 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005918 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005919 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005920 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005921 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005922 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005923 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005924 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005925 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005926 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005927 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005928 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5929 }
5930}
5931
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005932static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005933 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005934 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005935 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005936 // Disable warning in template instantiations.
5937 if (!S.ActiveTemplateInstantiations.empty())
5938 return;
5939
Richard Trieu0f097742014-04-04 04:13:47 +00005940 // TODO: Investigate using GetExprRange() to get tighter bounds
5941 // on the bit ranges.
5942 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005943 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5944 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005945 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5946 unsigned OtherWidth = OtherRange.Width;
5947
5948 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5949
Richard Trieu560910c2012-11-14 22:50:24 +00005950 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005951 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005952 return;
5953
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005954 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005955 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005956
Richard Trieu0f097742014-04-04 04:13:47 +00005957 // Used for diagnostic printout.
5958 enum {
5959 LiteralConstant = 0,
5960 CXXBoolLiteralTrue,
5961 CXXBoolLiteralFalse
5962 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005963
Richard Trieu0f097742014-04-04 04:13:47 +00005964 if (!OtherIsBooleanType) {
5965 QualType ConstantT = Constant->getType();
5966 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005967
Richard Trieu0f097742014-04-04 04:13:47 +00005968 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5969 return;
5970 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5971 "comparison with non-integer type");
5972
5973 bool ConstantSigned = ConstantT->isSignedIntegerType();
5974 bool CommonSigned = CommonT->isSignedIntegerType();
5975
5976 bool EqualityOnly = false;
5977
5978 if (CommonSigned) {
5979 // The common type is signed, therefore no signed to unsigned conversion.
5980 if (!OtherRange.NonNegative) {
5981 // Check that the constant is representable in type OtherT.
5982 if (ConstantSigned) {
5983 if (OtherWidth >= Value.getMinSignedBits())
5984 return;
5985 } else { // !ConstantSigned
5986 if (OtherWidth >= Value.getActiveBits() + 1)
5987 return;
5988 }
5989 } else { // !OtherSigned
5990 // Check that the constant is representable in type OtherT.
5991 // Negative values are out of range.
5992 if (ConstantSigned) {
5993 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5994 return;
5995 } else { // !ConstantSigned
5996 if (OtherWidth >= Value.getActiveBits())
5997 return;
5998 }
Richard Trieu560910c2012-11-14 22:50:24 +00005999 }
Richard Trieu0f097742014-04-04 04:13:47 +00006000 } else { // !CommonSigned
6001 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006002 if (OtherWidth >= Value.getActiveBits())
6003 return;
Craig Toppercf360162014-06-18 05:13:11 +00006004 } else { // OtherSigned
6005 assert(!ConstantSigned &&
6006 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006007 // Check to see if the constant is representable in OtherT.
6008 if (OtherWidth > Value.getActiveBits())
6009 return;
6010 // Check to see if the constant is equivalent to a negative value
6011 // cast to CommonT.
6012 if (S.Context.getIntWidth(ConstantT) ==
6013 S.Context.getIntWidth(CommonT) &&
6014 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6015 return;
6016 // The constant value rests between values that OtherT can represent
6017 // after conversion. Relational comparison still works, but equality
6018 // comparisons will be tautological.
6019 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006020 }
6021 }
Richard Trieu0f097742014-04-04 04:13:47 +00006022
6023 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6024
6025 if (op == BO_EQ || op == BO_NE) {
6026 IsTrue = op == BO_NE;
6027 } else if (EqualityOnly) {
6028 return;
6029 } else if (RhsConstant) {
6030 if (op == BO_GT || op == BO_GE)
6031 IsTrue = !PositiveConstant;
6032 else // op == BO_LT || op == BO_LE
6033 IsTrue = PositiveConstant;
6034 } else {
6035 if (op == BO_LT || op == BO_LE)
6036 IsTrue = !PositiveConstant;
6037 else // op == BO_GT || op == BO_GE
6038 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006039 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006040 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006041 // Other isKnownToHaveBooleanValue
6042 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6043 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6044 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6045
6046 static const struct LinkedConditions {
6047 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6048 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6049 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6050 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6051 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6052 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6053
6054 } TruthTable = {
6055 // Constant on LHS. | Constant on RHS. |
6056 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6057 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6058 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6059 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6060 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6061 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6062 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6063 };
6064
6065 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6066
6067 enum ConstantValue ConstVal = Zero;
6068 if (Value.isUnsigned() || Value.isNonNegative()) {
6069 if (Value == 0) {
6070 LiteralOrBoolConstant =
6071 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6072 ConstVal = Zero;
6073 } else if (Value == 1) {
6074 LiteralOrBoolConstant =
6075 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6076 ConstVal = One;
6077 } else {
6078 LiteralOrBoolConstant = LiteralConstant;
6079 ConstVal = GT_One;
6080 }
6081 } else {
6082 ConstVal = LT_Zero;
6083 }
6084
6085 CompareBoolWithConstantResult CmpRes;
6086
6087 switch (op) {
6088 case BO_LT:
6089 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6090 break;
6091 case BO_GT:
6092 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6093 break;
6094 case BO_LE:
6095 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6096 break;
6097 case BO_GE:
6098 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6099 break;
6100 case BO_EQ:
6101 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6102 break;
6103 case BO_NE:
6104 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6105 break;
6106 default:
6107 CmpRes = Unkwn;
6108 break;
6109 }
6110
6111 if (CmpRes == AFals) {
6112 IsTrue = false;
6113 } else if (CmpRes == ATrue) {
6114 IsTrue = true;
6115 } else {
6116 return;
6117 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006118 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006119
6120 // If this is a comparison to an enum constant, include that
6121 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006122 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006123 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6124 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6125
6126 SmallString<64> PrettySourceValue;
6127 llvm::raw_svector_ostream OS(PrettySourceValue);
6128 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006129 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006130 else
6131 OS << Value;
6132
Richard Trieu0f097742014-04-04 04:13:47 +00006133 S.DiagRuntimeBehavior(
6134 E->getOperatorLoc(), E,
6135 S.PDiag(diag::warn_out_of_range_compare)
6136 << OS.str() << LiteralOrBoolConstant
6137 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6138 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006139}
6140
John McCallcc7e5bf2010-05-06 08:58:33 +00006141/// Analyze the operands of the given comparison. Implements the
6142/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006143static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006144 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6145 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006146}
John McCall263a48b2010-01-04 23:31:57 +00006147
John McCallca01b222010-01-04 23:21:16 +00006148/// \brief Implements -Wsign-compare.
6149///
Richard Trieu82402a02011-09-15 21:56:47 +00006150/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006151static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006152 // The type the comparison is being performed in.
6153 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006154
6155 // Only analyze comparison operators where both sides have been converted to
6156 // the same type.
6157 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6158 return AnalyzeImpConvsInComparison(S, E);
6159
6160 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006161 if (E->isValueDependent())
6162 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006163
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006164 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6165 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006166
6167 bool IsComparisonConstant = false;
6168
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006169 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006170 // of 'true' or 'false'.
6171 if (T->isIntegralType(S.Context)) {
6172 llvm::APSInt RHSValue;
6173 bool IsRHSIntegralLiteral =
6174 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6175 llvm::APSInt LHSValue;
6176 bool IsLHSIntegralLiteral =
6177 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6178 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6179 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6180 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6181 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6182 else
6183 IsComparisonConstant =
6184 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006185 } else if (!T->hasUnsignedIntegerRepresentation())
6186 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006187
John McCallcc7e5bf2010-05-06 08:58:33 +00006188 // We don't do anything special if this isn't an unsigned integral
6189 // comparison: we're only interested in integral comparisons, and
6190 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006191 //
6192 // We also don't care about value-dependent expressions or expressions
6193 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006194 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006195 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006196
John McCallcc7e5bf2010-05-06 08:58:33 +00006197 // Check to see if one of the (unmodified) operands is of different
6198 // signedness.
6199 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006200 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6201 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006202 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006203 signedOperand = LHS;
6204 unsignedOperand = RHS;
6205 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6206 signedOperand = RHS;
6207 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006208 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006209 CheckTrivialUnsignedComparison(S, E);
6210 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006211 }
6212
John McCallcc7e5bf2010-05-06 08:58:33 +00006213 // Otherwise, calculate the effective range of the signed operand.
6214 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006215
John McCallcc7e5bf2010-05-06 08:58:33 +00006216 // Go ahead and analyze implicit conversions in the operands. Note
6217 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006218 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6219 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006220
John McCallcc7e5bf2010-05-06 08:58:33 +00006221 // If the signed range is non-negative, -Wsign-compare won't fire,
6222 // but we should still check for comparisons which are always true
6223 // or false.
6224 if (signedRange.NonNegative)
6225 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006226
6227 // For (in)equality comparisons, if the unsigned operand is a
6228 // constant which cannot collide with a overflowed signed operand,
6229 // then reinterpreting the signed operand as unsigned will not
6230 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006231 if (E->isEqualityOp()) {
6232 unsigned comparisonWidth = S.Context.getIntWidth(T);
6233 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006234
John McCallcc7e5bf2010-05-06 08:58:33 +00006235 // We should never be unable to prove that the unsigned operand is
6236 // non-negative.
6237 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6238
6239 if (unsignedRange.Width < comparisonWidth)
6240 return;
6241 }
6242
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006243 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6244 S.PDiag(diag::warn_mixed_sign_comparison)
6245 << LHS->getType() << RHS->getType()
6246 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006247}
6248
John McCall1f425642010-11-11 03:21:53 +00006249/// Analyzes an attempt to assign the given value to a bitfield.
6250///
6251/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006252static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6253 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006254 assert(Bitfield->isBitField());
6255 if (Bitfield->isInvalidDecl())
6256 return false;
6257
John McCalldeebbcf2010-11-11 05:33:51 +00006258 // White-list bool bitfields.
6259 if (Bitfield->getType()->isBooleanType())
6260 return false;
6261
Douglas Gregor789adec2011-02-04 13:09:01 +00006262 // Ignore value- or type-dependent expressions.
6263 if (Bitfield->getBitWidth()->isValueDependent() ||
6264 Bitfield->getBitWidth()->isTypeDependent() ||
6265 Init->isValueDependent() ||
6266 Init->isTypeDependent())
6267 return false;
6268
John McCall1f425642010-11-11 03:21:53 +00006269 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6270
Richard Smith5fab0c92011-12-28 19:48:30 +00006271 llvm::APSInt Value;
6272 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006273 return false;
6274
John McCall1f425642010-11-11 03:21:53 +00006275 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006276 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006277
6278 if (OriginalWidth <= FieldWidth)
6279 return false;
6280
Eli Friedmanc267a322012-01-26 23:11:39 +00006281 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006282 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006283 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006284
Eli Friedmanc267a322012-01-26 23:11:39 +00006285 // Check whether the stored value is equal to the original value.
6286 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006287 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006288 return false;
6289
Eli Friedmanc267a322012-01-26 23:11:39 +00006290 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006291 // therefore don't strictly fit into a signed bitfield of width 1.
6292 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006293 return false;
6294
John McCall1f425642010-11-11 03:21:53 +00006295 std::string PrettyValue = Value.toString(10);
6296 std::string PrettyTrunc = TruncatedValue.toString(10);
6297
6298 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6299 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6300 << Init->getSourceRange();
6301
6302 return true;
6303}
6304
John McCalld2a53122010-11-09 23:24:47 +00006305/// Analyze the given simple or compound assignment for warning-worthy
6306/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006307static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006308 // Just recurse on the LHS.
6309 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6310
6311 // We want to recurse on the RHS as normal unless we're assigning to
6312 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006313 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006314 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006315 E->getOperatorLoc())) {
6316 // Recurse, ignoring any implicit conversions on the RHS.
6317 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6318 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006319 }
6320 }
6321
6322 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6323}
6324
John McCall263a48b2010-01-04 23:31:57 +00006325/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006326static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006327 SourceLocation CContext, unsigned diag,
6328 bool pruneControlFlow = false) {
6329 if (pruneControlFlow) {
6330 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6331 S.PDiag(diag)
6332 << SourceType << T << E->getSourceRange()
6333 << SourceRange(CContext));
6334 return;
6335 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006336 S.Diag(E->getExprLoc(), diag)
6337 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6338}
6339
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006340/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006341static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006342 SourceLocation CContext, unsigned diag,
6343 bool pruneControlFlow = false) {
6344 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006345}
6346
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006347/// Diagnose an implicit cast from a literal expression. Does not warn when the
6348/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006349void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6350 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006351 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006352 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006353 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006354 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6355 T->hasUnsignedIntegerRepresentation());
6356 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006357 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006358 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006359 return;
6360
Eli Friedman07185912013-08-29 23:44:43 +00006361 // FIXME: Force the precision of the source value down so we don't print
6362 // digits which are usually useless (we don't really care here if we
6363 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6364 // would automatically print the shortest representation, but it's a bit
6365 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006366 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006367 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6368 precision = (precision * 59 + 195) / 196;
6369 Value.toString(PrettySourceValue, precision);
6370
David Blaikie9b88cc02012-05-15 17:18:27 +00006371 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006372 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6373 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6374 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006375 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006376
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006377 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006378 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6379 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006380}
6381
John McCall18a2c2c2010-11-09 22:22:12 +00006382std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6383 if (!Range.Width) return "0";
6384
6385 llvm::APSInt ValueInRange = Value;
6386 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006387 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006388 return ValueInRange.toString(10);
6389}
6390
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006391static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6392 if (!isa<ImplicitCastExpr>(Ex))
6393 return false;
6394
6395 Expr *InnerE = Ex->IgnoreParenImpCasts();
6396 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6397 const Type *Source =
6398 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6399 if (Target->isDependentType())
6400 return false;
6401
6402 const BuiltinType *FloatCandidateBT =
6403 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6404 const Type *BoolCandidateType = ToBool ? Target : Source;
6405
6406 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6407 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6408}
6409
6410void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6411 SourceLocation CC) {
6412 unsigned NumArgs = TheCall->getNumArgs();
6413 for (unsigned i = 0; i < NumArgs; ++i) {
6414 Expr *CurrA = TheCall->getArg(i);
6415 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6416 continue;
6417
6418 bool IsSwapped = ((i > 0) &&
6419 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6420 IsSwapped |= ((i < (NumArgs - 1)) &&
6421 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6422 if (IsSwapped) {
6423 // Warn on this floating-point to bool conversion.
6424 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6425 CurrA->getType(), CC,
6426 diag::warn_impcast_floating_point_to_bool);
6427 }
6428 }
6429}
6430
Richard Trieu5b993502014-10-15 03:42:06 +00006431static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6432 SourceLocation CC) {
6433 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6434 E->getExprLoc()))
6435 return;
6436
6437 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6438 const Expr::NullPointerConstantKind NullKind =
6439 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6440 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6441 return;
6442
6443 // Return if target type is a safe conversion.
6444 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6445 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6446 return;
6447
6448 SourceLocation Loc = E->getSourceRange().getBegin();
6449
6450 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6451 if (NullKind == Expr::NPCK_GNUNull) {
6452 if (Loc.isMacroID())
6453 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6454 }
6455
6456 // Only warn if the null and context location are in the same macro expansion.
6457 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6458 return;
6459
6460 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6461 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6462 << FixItHint::CreateReplacement(Loc,
6463 S.getFixItZeroLiteralForType(T, Loc));
6464}
6465
John McCallcc7e5bf2010-05-06 08:58:33 +00006466void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006467 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006468 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006469
John McCallcc7e5bf2010-05-06 08:58:33 +00006470 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6471 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6472 if (Source == Target) return;
6473 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006474
Chandler Carruthc22845a2011-07-26 05:40:03 +00006475 // If the conversion context location is invalid don't complain. We also
6476 // don't want to emit a warning if the issue occurs from the expansion of
6477 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6478 // delay this check as long as possible. Once we detect we are in that
6479 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006480 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006481 return;
6482
Richard Trieu021baa32011-09-23 20:10:00 +00006483 // Diagnose implicit casts to bool.
6484 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6485 if (isa<StringLiteral>(E))
6486 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006487 // and expressions, for instance, assert(0 && "error here"), are
6488 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006489 return DiagnoseImpCast(S, E, T, CC,
6490 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006491 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6492 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6493 // This covers the literal expressions that evaluate to Objective-C
6494 // objects.
6495 return DiagnoseImpCast(S, E, T, CC,
6496 diag::warn_impcast_objective_c_literal_to_bool);
6497 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006498 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6499 // Warn on pointer to bool conversion that is always true.
6500 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6501 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006502 }
Richard Trieu021baa32011-09-23 20:10:00 +00006503 }
John McCall263a48b2010-01-04 23:31:57 +00006504
6505 // Strip vector types.
6506 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006507 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006508 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006509 return;
John McCallacf0ee52010-10-08 02:01:28 +00006510 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006511 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006512
6513 // If the vector cast is cast between two vectors of the same size, it is
6514 // a bitcast, not a conversion.
6515 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6516 return;
John McCall263a48b2010-01-04 23:31:57 +00006517
6518 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6519 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6520 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006521 if (auto VecTy = dyn_cast<VectorType>(Target))
6522 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006523
6524 // Strip complex types.
6525 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006526 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006527 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006528 return;
6529
John McCallacf0ee52010-10-08 02:01:28 +00006530 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006531 }
John McCall263a48b2010-01-04 23:31:57 +00006532
6533 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6534 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6535 }
6536
6537 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6538 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6539
6540 // If the source is floating point...
6541 if (SourceBT && SourceBT->isFloatingPoint()) {
6542 // ...and the target is floating point...
6543 if (TargetBT && TargetBT->isFloatingPoint()) {
6544 // ...then warn if we're dropping FP rank.
6545
6546 // Builtin FP kinds are ordered by increasing FP rank.
6547 if (SourceBT->getKind() > TargetBT->getKind()) {
6548 // Don't warn about float constants that are precisely
6549 // representable in the target type.
6550 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006551 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006552 // Value might be a float, a float vector, or a float complex.
6553 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006554 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6555 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006556 return;
6557 }
6558
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006559 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006560 return;
6561
John McCallacf0ee52010-10-08 02:01:28 +00006562 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006563 }
6564 return;
6565 }
6566
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006567 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006568 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006569 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006570 return;
6571
Chandler Carruth22c7a792011-02-17 11:05:49 +00006572 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006573 // We also want to warn on, e.g., "int i = -1.234"
6574 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6575 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6576 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6577
Chandler Carruth016ef402011-04-10 08:36:24 +00006578 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6579 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006580 } else {
6581 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6582 }
6583 }
John McCall263a48b2010-01-04 23:31:57 +00006584
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006585 // If the target is bool, warn if expr is a function or method call.
6586 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6587 isa<CallExpr>(E)) {
6588 // Check last argument of function call to see if it is an
6589 // implicit cast from a type matching the type the result
6590 // is being cast to.
6591 CallExpr *CEx = cast<CallExpr>(E);
6592 unsigned NumArgs = CEx->getNumArgs();
6593 if (NumArgs > 0) {
6594 Expr *LastA = CEx->getArg(NumArgs - 1);
6595 Expr *InnerE = LastA->IgnoreParenImpCasts();
6596 const Type *InnerType =
6597 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6598 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6599 // Warn on this floating-point to bool conversion
6600 DiagnoseImpCast(S, E, T, CC,
6601 diag::warn_impcast_floating_point_to_bool);
6602 }
6603 }
6604 }
John McCall263a48b2010-01-04 23:31:57 +00006605 return;
6606 }
6607
Richard Trieu5b993502014-10-15 03:42:06 +00006608 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006609
David Blaikie9366d2b2012-06-19 21:19:06 +00006610 if (!Source->isIntegerType() || !Target->isIntegerType())
6611 return;
6612
David Blaikie7555b6a2012-05-15 16:56:36 +00006613 // TODO: remove this early return once the false positives for constant->bool
6614 // in templates, macros, etc, are reduced or removed.
6615 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6616 return;
6617
John McCallcc7e5bf2010-05-06 08:58:33 +00006618 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006619 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006620
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006621 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006622 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006623 // TODO: this should happen for bitfield stores, too.
6624 llvm::APSInt Value(32);
6625 if (E->isIntegerConstantExpr(Value, S.Context)) {
6626 if (S.SourceMgr.isInSystemMacro(CC))
6627 return;
6628
John McCall18a2c2c2010-11-09 22:22:12 +00006629 std::string PrettySourceValue = Value.toString(10);
6630 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006631
Ted Kremenek33ba9952011-10-22 02:37:33 +00006632 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6633 S.PDiag(diag::warn_impcast_integer_precision_constant)
6634 << PrettySourceValue << PrettyTargetValue
6635 << E->getType() << T << E->getSourceRange()
6636 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006637 return;
6638 }
6639
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006640 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6641 if (S.SourceMgr.isInSystemMacro(CC))
6642 return;
6643
David Blaikie9455da02012-04-12 22:40:54 +00006644 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006645 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6646 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006647 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006648 }
6649
6650 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6651 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6652 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006653
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006654 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006655 return;
6656
John McCallcc7e5bf2010-05-06 08:58:33 +00006657 unsigned DiagID = diag::warn_impcast_integer_sign;
6658
6659 // Traditionally, gcc has warned about this under -Wsign-compare.
6660 // We also want to warn about it in -Wconversion.
6661 // So if -Wconversion is off, use a completely identical diagnostic
6662 // in the sign-compare group.
6663 // The conditional-checking code will
6664 if (ICContext) {
6665 DiagID = diag::warn_impcast_integer_sign_conditional;
6666 *ICContext = true;
6667 }
6668
John McCallacf0ee52010-10-08 02:01:28 +00006669 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006670 }
6671
Douglas Gregora78f1932011-02-22 02:45:07 +00006672 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006673 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6674 // type, to give us better diagnostics.
6675 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006676 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006677 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6678 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6679 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6680 SourceType = S.Context.getTypeDeclType(Enum);
6681 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6682 }
6683 }
6684
Douglas Gregora78f1932011-02-22 02:45:07 +00006685 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6686 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006687 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6688 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006689 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006690 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006691 return;
6692
Douglas Gregor364f7db2011-03-12 00:14:31 +00006693 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006694 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006695 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006696
John McCall263a48b2010-01-04 23:31:57 +00006697 return;
6698}
6699
David Blaikie18e9ac72012-05-15 21:57:38 +00006700void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6701 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006702
6703void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006704 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006705 E = E->IgnoreParenImpCasts();
6706
6707 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006708 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006709
John McCallacf0ee52010-10-08 02:01:28 +00006710 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006711 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006712 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006713 return;
6714}
6715
David Blaikie18e9ac72012-05-15 21:57:38 +00006716void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6717 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006718 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006719
6720 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006721 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6722 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006723
6724 // If -Wconversion would have warned about either of the candidates
6725 // for a signedness conversion to the context type...
6726 if (!Suspicious) return;
6727
6728 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006729 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006730 return;
6731
John McCallcc7e5bf2010-05-06 08:58:33 +00006732 // ...then check whether it would have warned about either of the
6733 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006734 if (E->getType() == T) return;
6735
6736 Suspicious = false;
6737 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6738 E->getType(), CC, &Suspicious);
6739 if (!Suspicious)
6740 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006741 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006742}
6743
Richard Trieu65724892014-11-15 06:37:39 +00006744/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6745/// Input argument E is a logical expression.
6746static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6747 if (S.getLangOpts().Bool)
6748 return;
6749 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6750}
6751
John McCallcc7e5bf2010-05-06 08:58:33 +00006752/// AnalyzeImplicitConversions - Find and report any interesting
6753/// implicit conversions in the given expression. There are a couple
6754/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006755void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006756 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006757 Expr *E = OrigE->IgnoreParenImpCasts();
6758
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006759 if (E->isTypeDependent() || E->isValueDependent())
6760 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006761
John McCallcc7e5bf2010-05-06 08:58:33 +00006762 // For conditional operators, we analyze the arguments as if they
6763 // were being fed directly into the output.
6764 if (isa<ConditionalOperator>(E)) {
6765 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006766 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006767 return;
6768 }
6769
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006770 // Check implicit argument conversions for function calls.
6771 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6772 CheckImplicitArgumentConversions(S, Call, CC);
6773
John McCallcc7e5bf2010-05-06 08:58:33 +00006774 // Go ahead and check any implicit conversions we might have skipped.
6775 // The non-canonical typecheck is just an optimization;
6776 // CheckImplicitConversion will filter out dead implicit conversions.
6777 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006778 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006779
6780 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006781
6782 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006783 if (POE->getResultExpr())
6784 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006785 }
6786
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00006787 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
6788 if (OVE->getSourceExpr())
6789 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6790 return;
6791 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006792
John McCallcc7e5bf2010-05-06 08:58:33 +00006793 // Skip past explicit casts.
6794 if (isa<ExplicitCastExpr>(E)) {
6795 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006796 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006797 }
6798
John McCalld2a53122010-11-09 23:24:47 +00006799 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6800 // Do a somewhat different check with comparison operators.
6801 if (BO->isComparisonOp())
6802 return AnalyzeComparison(S, BO);
6803
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006804 // And with simple assignments.
6805 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006806 return AnalyzeAssignment(S, BO);
6807 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006808
6809 // These break the otherwise-useful invariant below. Fortunately,
6810 // we don't really need to recurse into them, because any internal
6811 // expressions should have been analyzed already when they were
6812 // built into statements.
6813 if (isa<StmtExpr>(E)) return;
6814
6815 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006816 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006817
6818 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006819 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006820 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006821 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006822 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006823 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006824 if (!ChildExpr)
6825 continue;
6826
Richard Trieu955231d2014-01-25 01:10:35 +00006827 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006828 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006829 // Ignore checking string literals that are in logical and operators.
6830 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006831 continue;
6832 AnalyzeImplicitConversions(S, ChildExpr, CC);
6833 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006834
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006835 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006836 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6837 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006838 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00006839
6840 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6841 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006842 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006843 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006844
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006845 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6846 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00006847 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006848}
6849
6850} // end anonymous namespace
6851
Richard Trieu3bb8b562014-02-26 02:36:06 +00006852enum {
6853 AddressOf,
6854 FunctionPointer,
6855 ArrayPointer
6856};
6857
Richard Trieuc1888e02014-06-28 23:25:37 +00006858// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6859// Returns true when emitting a warning about taking the address of a reference.
6860static bool CheckForReference(Sema &SemaRef, const Expr *E,
6861 PartialDiagnostic PD) {
6862 E = E->IgnoreParenImpCasts();
6863
6864 const FunctionDecl *FD = nullptr;
6865
6866 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6867 if (!DRE->getDecl()->getType()->isReferenceType())
6868 return false;
6869 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6870 if (!M->getMemberDecl()->getType()->isReferenceType())
6871 return false;
6872 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00006873 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00006874 return false;
6875 FD = Call->getDirectCallee();
6876 } else {
6877 return false;
6878 }
6879
6880 SemaRef.Diag(E->getExprLoc(), PD);
6881
6882 // If possible, point to location of function.
6883 if (FD) {
6884 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6885 }
6886
6887 return true;
6888}
6889
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006890// Returns true if the SourceLocation is expanded from any macro body.
6891// Returns false if the SourceLocation is invalid, is from not in a macro
6892// expansion, or is from expanded from a top-level macro argument.
6893static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6894 if (Loc.isInvalid())
6895 return false;
6896
6897 while (Loc.isMacroID()) {
6898 if (SM.isMacroBodyExpansion(Loc))
6899 return true;
6900 Loc = SM.getImmediateMacroCallerLoc(Loc);
6901 }
6902
6903 return false;
6904}
6905
Richard Trieu3bb8b562014-02-26 02:36:06 +00006906/// \brief Diagnose pointers that are always non-null.
6907/// \param E the expression containing the pointer
6908/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6909/// compared to a null pointer
6910/// \param IsEqual True when the comparison is equal to a null pointer
6911/// \param Range Extra SourceRange to highlight in the diagnostic
6912void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6913 Expr::NullPointerConstantKind NullKind,
6914 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006915 if (!E)
6916 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006917
6918 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006919 if (E->getExprLoc().isMacroID()) {
6920 const SourceManager &SM = getSourceManager();
6921 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6922 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006923 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006924 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006925 E = E->IgnoreImpCasts();
6926
6927 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6928
Richard Trieuf7432752014-06-06 21:39:26 +00006929 if (isa<CXXThisExpr>(E)) {
6930 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6931 : diag::warn_this_bool_conversion;
6932 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6933 return;
6934 }
6935
Richard Trieu3bb8b562014-02-26 02:36:06 +00006936 bool IsAddressOf = false;
6937
6938 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6939 if (UO->getOpcode() != UO_AddrOf)
6940 return;
6941 IsAddressOf = true;
6942 E = UO->getSubExpr();
6943 }
6944
Richard Trieuc1888e02014-06-28 23:25:37 +00006945 if (IsAddressOf) {
6946 unsigned DiagID = IsCompare
6947 ? diag::warn_address_of_reference_null_compare
6948 : diag::warn_address_of_reference_bool_conversion;
6949 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6950 << IsEqual;
6951 if (CheckForReference(*this, E, PD)) {
6952 return;
6953 }
6954 }
6955
Richard Trieu3bb8b562014-02-26 02:36:06 +00006956 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006957 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006958 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6959 D = R->getDecl();
6960 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6961 D = M->getMemberDecl();
6962 }
6963
6964 // Weak Decls can be null.
6965 if (!D || D->isWeak())
6966 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006967
6968 // Check for parameter decl with nonnull attribute
6969 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6970 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6971 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6972 unsigned NumArgs = FD->getNumParams();
6973 llvm::SmallBitVector AttrNonNull(NumArgs);
6974 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6975 if (!NonNull->args_size()) {
6976 AttrNonNull.set(0, NumArgs);
6977 break;
6978 }
6979 for (unsigned Val : NonNull->args()) {
6980 if (Val >= NumArgs)
6981 continue;
6982 AttrNonNull.set(Val);
6983 }
6984 }
6985 if (!AttrNonNull.empty())
6986 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00006987 if (FD->getParamDecl(i) == PV &&
6988 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006989 std::string Str;
6990 llvm::raw_string_ostream S(Str);
6991 E->printPretty(S, nullptr, getPrintingPolicy());
6992 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
6993 : diag::warn_cast_nonnull_to_bool;
6994 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
6995 << Range << IsEqual;
6996 return;
6997 }
6998 }
6999 }
7000
Richard Trieu3bb8b562014-02-26 02:36:06 +00007001 QualType T = D->getType();
7002 const bool IsArray = T->isArrayType();
7003 const bool IsFunction = T->isFunctionType();
7004
Richard Trieuc1888e02014-06-28 23:25:37 +00007005 // Address of function is used to silence the function warning.
7006 if (IsAddressOf && IsFunction) {
7007 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007008 }
7009
7010 // Found nothing.
7011 if (!IsAddressOf && !IsFunction && !IsArray)
7012 return;
7013
7014 // Pretty print the expression for the diagnostic.
7015 std::string Str;
7016 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007017 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007018
7019 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7020 : diag::warn_impcast_pointer_to_bool;
7021 unsigned DiagType;
7022 if (IsAddressOf)
7023 DiagType = AddressOf;
7024 else if (IsFunction)
7025 DiagType = FunctionPointer;
7026 else if (IsArray)
7027 DiagType = ArrayPointer;
7028 else
7029 llvm_unreachable("Could not determine diagnostic.");
7030 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7031 << Range << IsEqual;
7032
7033 if (!IsFunction)
7034 return;
7035
7036 // Suggest '&' to silence the function warning.
7037 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7038 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7039
7040 // Check to see if '()' fixit should be emitted.
7041 QualType ReturnType;
7042 UnresolvedSet<4> NonTemplateOverloads;
7043 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7044 if (ReturnType.isNull())
7045 return;
7046
7047 if (IsCompare) {
7048 // There are two cases here. If there is null constant, the only suggest
7049 // for a pointer return type. If the null is 0, then suggest if the return
7050 // type is a pointer or an integer type.
7051 if (!ReturnType->isPointerType()) {
7052 if (NullKind == Expr::NPCK_ZeroExpression ||
7053 NullKind == Expr::NPCK_ZeroLiteral) {
7054 if (!ReturnType->isIntegerType())
7055 return;
7056 } else {
7057 return;
7058 }
7059 }
7060 } else { // !IsCompare
7061 // For function to bool, only suggest if the function pointer has bool
7062 // return type.
7063 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7064 return;
7065 }
7066 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007067 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007068}
7069
7070
John McCallcc7e5bf2010-05-06 08:58:33 +00007071/// Diagnoses "dangerous" implicit conversions within the given
7072/// expression (which is a full expression). Implements -Wconversion
7073/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007074///
7075/// \param CC the "context" location of the implicit conversion, i.e.
7076/// the most location of the syntactic entity requiring the implicit
7077/// conversion
7078void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007079 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007080 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007081 return;
7082
7083 // Don't diagnose for value- or type-dependent expressions.
7084 if (E->isTypeDependent() || E->isValueDependent())
7085 return;
7086
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007087 // Check for array bounds violations in cases where the check isn't triggered
7088 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7089 // ArraySubscriptExpr is on the RHS of a variable initialization.
7090 CheckArrayAccess(E);
7091
John McCallacf0ee52010-10-08 02:01:28 +00007092 // This is not the right CC for (e.g.) a variable initialization.
7093 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007094}
7095
Richard Trieu65724892014-11-15 06:37:39 +00007096/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7097/// Input argument E is a logical expression.
7098void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7099 ::CheckBoolLikeConversion(*this, E, CC);
7100}
7101
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007102/// Diagnose when expression is an integer constant expression and its evaluation
7103/// results in integer overflow
7104void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007105 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7106 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007107}
7108
Richard Smithc406cb72013-01-17 01:17:56 +00007109namespace {
7110/// \brief Visitor for expressions which looks for unsequenced operations on the
7111/// same object.
7112class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007113 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7114
Richard Smithc406cb72013-01-17 01:17:56 +00007115 /// \brief A tree of sequenced regions within an expression. Two regions are
7116 /// unsequenced if one is an ancestor or a descendent of the other. When we
7117 /// finish processing an expression with sequencing, such as a comma
7118 /// expression, we fold its tree nodes into its parent, since they are
7119 /// unsequenced with respect to nodes we will visit later.
7120 class SequenceTree {
7121 struct Value {
7122 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7123 unsigned Parent : 31;
7124 bool Merged : 1;
7125 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007126 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007127
7128 public:
7129 /// \brief A region within an expression which may be sequenced with respect
7130 /// to some other region.
7131 class Seq {
7132 explicit Seq(unsigned N) : Index(N) {}
7133 unsigned Index;
7134 friend class SequenceTree;
7135 public:
7136 Seq() : Index(0) {}
7137 };
7138
7139 SequenceTree() { Values.push_back(Value(0)); }
7140 Seq root() const { return Seq(0); }
7141
7142 /// \brief Create a new sequence of operations, which is an unsequenced
7143 /// subset of \p Parent. This sequence of operations is sequenced with
7144 /// respect to other children of \p Parent.
7145 Seq allocate(Seq Parent) {
7146 Values.push_back(Value(Parent.Index));
7147 return Seq(Values.size() - 1);
7148 }
7149
7150 /// \brief Merge a sequence of operations into its parent.
7151 void merge(Seq S) {
7152 Values[S.Index].Merged = true;
7153 }
7154
7155 /// \brief Determine whether two operations are unsequenced. This operation
7156 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7157 /// should have been merged into its parent as appropriate.
7158 bool isUnsequenced(Seq Cur, Seq Old) {
7159 unsigned C = representative(Cur.Index);
7160 unsigned Target = representative(Old.Index);
7161 while (C >= Target) {
7162 if (C == Target)
7163 return true;
7164 C = Values[C].Parent;
7165 }
7166 return false;
7167 }
7168
7169 private:
7170 /// \brief Pick a representative for a sequence.
7171 unsigned representative(unsigned K) {
7172 if (Values[K].Merged)
7173 // Perform path compression as we go.
7174 return Values[K].Parent = representative(Values[K].Parent);
7175 return K;
7176 }
7177 };
7178
7179 /// An object for which we can track unsequenced uses.
7180 typedef NamedDecl *Object;
7181
7182 /// Different flavors of object usage which we track. We only track the
7183 /// least-sequenced usage of each kind.
7184 enum UsageKind {
7185 /// A read of an object. Multiple unsequenced reads are OK.
7186 UK_Use,
7187 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007188 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007189 UK_ModAsValue,
7190 /// A modification of an object which is not sequenced before the value
7191 /// computation of the expression, such as n++.
7192 UK_ModAsSideEffect,
7193
7194 UK_Count = UK_ModAsSideEffect + 1
7195 };
7196
7197 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007198 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007199 Expr *Use;
7200 SequenceTree::Seq Seq;
7201 };
7202
7203 struct UsageInfo {
7204 UsageInfo() : Diagnosed(false) {}
7205 Usage Uses[UK_Count];
7206 /// Have we issued a diagnostic for this variable already?
7207 bool Diagnosed;
7208 };
7209 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7210
7211 Sema &SemaRef;
7212 /// Sequenced regions within the expression.
7213 SequenceTree Tree;
7214 /// Declaration modifications and references which we have seen.
7215 UsageInfoMap UsageMap;
7216 /// The region we are currently within.
7217 SequenceTree::Seq Region;
7218 /// Filled in with declarations which were modified as a side-effect
7219 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007220 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007221 /// Expressions to check later. We defer checking these to reduce
7222 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007223 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007224
7225 /// RAII object wrapping the visitation of a sequenced subexpression of an
7226 /// expression. At the end of this process, the side-effects of the evaluation
7227 /// become sequenced with respect to the value computation of the result, so
7228 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7229 /// UK_ModAsValue.
7230 struct SequencedSubexpression {
7231 SequencedSubexpression(SequenceChecker &Self)
7232 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7233 Self.ModAsSideEffect = &ModAsSideEffect;
7234 }
7235 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007236 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7237 MI != ME; ++MI) {
7238 UsageInfo &U = Self.UsageMap[MI->first];
7239 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7240 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7241 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007242 }
7243 Self.ModAsSideEffect = OldModAsSideEffect;
7244 }
7245
7246 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007247 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7248 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007249 };
7250
Richard Smith40238f02013-06-20 22:21:56 +00007251 /// RAII object wrapping the visitation of a subexpression which we might
7252 /// choose to evaluate as a constant. If any subexpression is evaluated and
7253 /// found to be non-constant, this allows us to suppress the evaluation of
7254 /// the outer expression.
7255 class EvaluationTracker {
7256 public:
7257 EvaluationTracker(SequenceChecker &Self)
7258 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7259 Self.EvalTracker = this;
7260 }
7261 ~EvaluationTracker() {
7262 Self.EvalTracker = Prev;
7263 if (Prev)
7264 Prev->EvalOK &= EvalOK;
7265 }
7266
7267 bool evaluate(const Expr *E, bool &Result) {
7268 if (!EvalOK || E->isValueDependent())
7269 return false;
7270 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7271 return EvalOK;
7272 }
7273
7274 private:
7275 SequenceChecker &Self;
7276 EvaluationTracker *Prev;
7277 bool EvalOK;
7278 } *EvalTracker;
7279
Richard Smithc406cb72013-01-17 01:17:56 +00007280 /// \brief Find the object which is produced by the specified expression,
7281 /// if any.
7282 Object getObject(Expr *E, bool Mod) const {
7283 E = E->IgnoreParenCasts();
7284 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7285 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7286 return getObject(UO->getSubExpr(), Mod);
7287 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7288 if (BO->getOpcode() == BO_Comma)
7289 return getObject(BO->getRHS(), Mod);
7290 if (Mod && BO->isAssignmentOp())
7291 return getObject(BO->getLHS(), Mod);
7292 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7293 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7294 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7295 return ME->getMemberDecl();
7296 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7297 // FIXME: If this is a reference, map through to its value.
7298 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007299 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007300 }
7301
7302 /// \brief Note that an object was modified or used by an expression.
7303 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7304 Usage &U = UI.Uses[UK];
7305 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7306 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7307 ModAsSideEffect->push_back(std::make_pair(O, U));
7308 U.Use = Ref;
7309 U.Seq = Region;
7310 }
7311 }
7312 /// \brief Check whether a modification or use conflicts with a prior usage.
7313 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7314 bool IsModMod) {
7315 if (UI.Diagnosed)
7316 return;
7317
7318 const Usage &U = UI.Uses[OtherKind];
7319 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7320 return;
7321
7322 Expr *Mod = U.Use;
7323 Expr *ModOrUse = Ref;
7324 if (OtherKind == UK_Use)
7325 std::swap(Mod, ModOrUse);
7326
7327 SemaRef.Diag(Mod->getExprLoc(),
7328 IsModMod ? diag::warn_unsequenced_mod_mod
7329 : diag::warn_unsequenced_mod_use)
7330 << O << SourceRange(ModOrUse->getExprLoc());
7331 UI.Diagnosed = true;
7332 }
7333
7334 void notePreUse(Object O, Expr *Use) {
7335 UsageInfo &U = UsageMap[O];
7336 // Uses conflict with other modifications.
7337 checkUsage(O, U, Use, UK_ModAsValue, false);
7338 }
7339 void notePostUse(Object O, Expr *Use) {
7340 UsageInfo &U = UsageMap[O];
7341 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7342 addUsage(U, O, Use, UK_Use);
7343 }
7344
7345 void notePreMod(Object O, Expr *Mod) {
7346 UsageInfo &U = UsageMap[O];
7347 // Modifications conflict with other modifications and with uses.
7348 checkUsage(O, U, Mod, UK_ModAsValue, true);
7349 checkUsage(O, U, Mod, UK_Use, false);
7350 }
7351 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7352 UsageInfo &U = UsageMap[O];
7353 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7354 addUsage(U, O, Use, UK);
7355 }
7356
7357public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007358 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007359 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7360 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007361 Visit(E);
7362 }
7363
7364 void VisitStmt(Stmt *S) {
7365 // Skip all statements which aren't expressions for now.
7366 }
7367
7368 void VisitExpr(Expr *E) {
7369 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007370 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007371 }
7372
7373 void VisitCastExpr(CastExpr *E) {
7374 Object O = Object();
7375 if (E->getCastKind() == CK_LValueToRValue)
7376 O = getObject(E->getSubExpr(), false);
7377
7378 if (O)
7379 notePreUse(O, E);
7380 VisitExpr(E);
7381 if (O)
7382 notePostUse(O, E);
7383 }
7384
7385 void VisitBinComma(BinaryOperator *BO) {
7386 // C++11 [expr.comma]p1:
7387 // Every value computation and side effect associated with the left
7388 // expression is sequenced before every value computation and side
7389 // effect associated with the right expression.
7390 SequenceTree::Seq LHS = Tree.allocate(Region);
7391 SequenceTree::Seq RHS = Tree.allocate(Region);
7392 SequenceTree::Seq OldRegion = Region;
7393
7394 {
7395 SequencedSubexpression SeqLHS(*this);
7396 Region = LHS;
7397 Visit(BO->getLHS());
7398 }
7399
7400 Region = RHS;
7401 Visit(BO->getRHS());
7402
7403 Region = OldRegion;
7404
7405 // Forget that LHS and RHS are sequenced. They are both unsequenced
7406 // with respect to other stuff.
7407 Tree.merge(LHS);
7408 Tree.merge(RHS);
7409 }
7410
7411 void VisitBinAssign(BinaryOperator *BO) {
7412 // The modification is sequenced after the value computation of the LHS
7413 // and RHS, so check it before inspecting the operands and update the
7414 // map afterwards.
7415 Object O = getObject(BO->getLHS(), true);
7416 if (!O)
7417 return VisitExpr(BO);
7418
7419 notePreMod(O, BO);
7420
7421 // C++11 [expr.ass]p7:
7422 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7423 // only once.
7424 //
7425 // Therefore, for a compound assignment operator, O is considered used
7426 // everywhere except within the evaluation of E1 itself.
7427 if (isa<CompoundAssignOperator>(BO))
7428 notePreUse(O, BO);
7429
7430 Visit(BO->getLHS());
7431
7432 if (isa<CompoundAssignOperator>(BO))
7433 notePostUse(O, BO);
7434
7435 Visit(BO->getRHS());
7436
Richard Smith83e37bee2013-06-26 23:16:51 +00007437 // C++11 [expr.ass]p1:
7438 // the assignment is sequenced [...] before the value computation of the
7439 // assignment expression.
7440 // C11 6.5.16/3 has no such rule.
7441 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7442 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007443 }
7444 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7445 VisitBinAssign(CAO);
7446 }
7447
7448 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7449 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7450 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7451 Object O = getObject(UO->getSubExpr(), true);
7452 if (!O)
7453 return VisitExpr(UO);
7454
7455 notePreMod(O, UO);
7456 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007457 // C++11 [expr.pre.incr]p1:
7458 // the expression ++x is equivalent to x+=1
7459 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7460 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007461 }
7462
7463 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7464 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7465 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7466 Object O = getObject(UO->getSubExpr(), true);
7467 if (!O)
7468 return VisitExpr(UO);
7469
7470 notePreMod(O, UO);
7471 Visit(UO->getSubExpr());
7472 notePostMod(O, UO, UK_ModAsSideEffect);
7473 }
7474
7475 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7476 void VisitBinLOr(BinaryOperator *BO) {
7477 // The side-effects of the LHS of an '&&' are sequenced before the
7478 // value computation of the RHS, and hence before the value computation
7479 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7480 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007481 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007482 {
7483 SequencedSubexpression Sequenced(*this);
7484 Visit(BO->getLHS());
7485 }
7486
7487 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007488 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007489 if (!Result)
7490 Visit(BO->getRHS());
7491 } else {
7492 // Check for unsequenced operations in the RHS, treating it as an
7493 // entirely separate evaluation.
7494 //
7495 // FIXME: If there are operations in the RHS which are unsequenced
7496 // with respect to operations outside the RHS, and those operations
7497 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007498 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007499 }
Richard Smithc406cb72013-01-17 01:17:56 +00007500 }
7501 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007502 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007503 {
7504 SequencedSubexpression Sequenced(*this);
7505 Visit(BO->getLHS());
7506 }
7507
7508 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007509 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007510 if (Result)
7511 Visit(BO->getRHS());
7512 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007513 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007514 }
Richard Smithc406cb72013-01-17 01:17:56 +00007515 }
7516
7517 // Only visit the condition, unless we can be sure which subexpression will
7518 // be chosen.
7519 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007520 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007521 {
7522 SequencedSubexpression Sequenced(*this);
7523 Visit(CO->getCond());
7524 }
Richard Smithc406cb72013-01-17 01:17:56 +00007525
7526 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007527 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007528 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007529 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007530 WorkList.push_back(CO->getTrueExpr());
7531 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007532 }
Richard Smithc406cb72013-01-17 01:17:56 +00007533 }
7534
Richard Smithe3dbfe02013-06-30 10:40:20 +00007535 void VisitCallExpr(CallExpr *CE) {
7536 // C++11 [intro.execution]p15:
7537 // When calling a function [...], every value computation and side effect
7538 // associated with any argument expression, or with the postfix expression
7539 // designating the called function, is sequenced before execution of every
7540 // expression or statement in the body of the function [and thus before
7541 // the value computation of its result].
7542 SequencedSubexpression Sequenced(*this);
7543 Base::VisitCallExpr(CE);
7544
7545 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7546 }
7547
Richard Smithc406cb72013-01-17 01:17:56 +00007548 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007549 // This is a call, so all subexpressions are sequenced before the result.
7550 SequencedSubexpression Sequenced(*this);
7551
Richard Smithc406cb72013-01-17 01:17:56 +00007552 if (!CCE->isListInitialization())
7553 return VisitExpr(CCE);
7554
7555 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007556 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007557 SequenceTree::Seq Parent = Region;
7558 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7559 E = CCE->arg_end();
7560 I != E; ++I) {
7561 Region = Tree.allocate(Parent);
7562 Elts.push_back(Region);
7563 Visit(*I);
7564 }
7565
7566 // Forget that the initializers are sequenced.
7567 Region = Parent;
7568 for (unsigned I = 0; I < Elts.size(); ++I)
7569 Tree.merge(Elts[I]);
7570 }
7571
7572 void VisitInitListExpr(InitListExpr *ILE) {
7573 if (!SemaRef.getLangOpts().CPlusPlus11)
7574 return VisitExpr(ILE);
7575
7576 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007577 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007578 SequenceTree::Seq Parent = Region;
7579 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7580 Expr *E = ILE->getInit(I);
7581 if (!E) continue;
7582 Region = Tree.allocate(Parent);
7583 Elts.push_back(Region);
7584 Visit(E);
7585 }
7586
7587 // Forget that the initializers are sequenced.
7588 Region = Parent;
7589 for (unsigned I = 0; I < Elts.size(); ++I)
7590 Tree.merge(Elts[I]);
7591 }
7592};
7593}
7594
7595void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007596 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007597 WorkList.push_back(E);
7598 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007599 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007600 SequenceChecker(*this, Item, WorkList);
7601 }
Richard Smithc406cb72013-01-17 01:17:56 +00007602}
7603
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007604void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7605 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007606 CheckImplicitConversions(E, CheckLoc);
7607 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007608 if (!IsConstexpr && !E->isValueDependent())
7609 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007610}
7611
John McCall1f425642010-11-11 03:21:53 +00007612void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7613 FieldDecl *BitField,
7614 Expr *Init) {
7615 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7616}
7617
Mike Stump0c2ec772010-01-21 03:59:47 +00007618/// CheckParmsForFunctionDef - Check that the parameters of the given
7619/// function are appropriate for the definition of a function. This
7620/// takes care of any checks that cannot be performed on the
7621/// declaration itself, e.g., that the types of each of the function
7622/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007623bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7624 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007625 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007626 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007627 for (; P != PEnd; ++P) {
7628 ParmVarDecl *Param = *P;
7629
Mike Stump0c2ec772010-01-21 03:59:47 +00007630 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7631 // function declarator that is part of a function definition of
7632 // that function shall not have incomplete type.
7633 //
7634 // This is also C++ [dcl.fct]p6.
7635 if (!Param->isInvalidDecl() &&
7636 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007637 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007638 Param->setInvalidDecl();
7639 HasInvalidParm = true;
7640 }
7641
7642 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7643 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007644 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007645 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007646 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007647 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007648 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007649
7650 // C99 6.7.5.3p12:
7651 // If the function declarator is not part of a definition of that
7652 // function, parameters may have incomplete type and may use the [*]
7653 // notation in their sequences of declarator specifiers to specify
7654 // variable length array types.
7655 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007656 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007657 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007658 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007659 // information is added for it.
7660 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007661 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007662 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007663 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007664 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007665
7666 // MSVC destroys objects passed by value in the callee. Therefore a
7667 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007668 // object's destructor. However, we don't perform any direct access check
7669 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007670 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7671 .getCXXABI()
7672 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007673 if (!Param->isInvalidDecl()) {
7674 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7675 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7676 if (!ClassDecl->isInvalidDecl() &&
7677 !ClassDecl->hasIrrelevantDestructor() &&
7678 !ClassDecl->isDependentContext()) {
7679 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7680 MarkFunctionReferenced(Param->getLocation(), Destructor);
7681 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7682 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007683 }
7684 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007685 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007686 }
7687
7688 return HasInvalidParm;
7689}
John McCall2b5c1b22010-08-12 21:44:57 +00007690
7691/// CheckCastAlign - Implements -Wcast-align, which warns when a
7692/// pointer cast increases the alignment requirements.
7693void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7694 // This is actually a lot of work to potentially be doing on every
7695 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007696 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007697 return;
7698
7699 // Ignore dependent types.
7700 if (T->isDependentType() || Op->getType()->isDependentType())
7701 return;
7702
7703 // Require that the destination be a pointer type.
7704 const PointerType *DestPtr = T->getAs<PointerType>();
7705 if (!DestPtr) return;
7706
7707 // If the destination has alignment 1, we're done.
7708 QualType DestPointee = DestPtr->getPointeeType();
7709 if (DestPointee->isIncompleteType()) return;
7710 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7711 if (DestAlign.isOne()) return;
7712
7713 // Require that the source be a pointer type.
7714 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7715 if (!SrcPtr) return;
7716 QualType SrcPointee = SrcPtr->getPointeeType();
7717
7718 // Whitelist casts from cv void*. We already implicitly
7719 // whitelisted casts to cv void*, since they have alignment 1.
7720 // Also whitelist casts involving incomplete types, which implicitly
7721 // includes 'void'.
7722 if (SrcPointee->isIncompleteType()) return;
7723
7724 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7725 if (SrcAlign >= DestAlign) return;
7726
7727 Diag(TRange.getBegin(), diag::warn_cast_align)
7728 << Op->getType() << T
7729 << static_cast<unsigned>(SrcAlign.getQuantity())
7730 << static_cast<unsigned>(DestAlign.getQuantity())
7731 << TRange << Op->getSourceRange();
7732}
7733
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007734static const Type* getElementType(const Expr *BaseExpr) {
7735 const Type* EltType = BaseExpr->getType().getTypePtr();
7736 if (EltType->isAnyPointerType())
7737 return EltType->getPointeeType().getTypePtr();
7738 else if (EltType->isArrayType())
7739 return EltType->getBaseElementTypeUnsafe();
7740 return EltType;
7741}
7742
Chandler Carruth28389f02011-08-05 09:10:50 +00007743/// \brief Check whether this array fits the idiom of a size-one tail padded
7744/// array member of a struct.
7745///
7746/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7747/// commonly used to emulate flexible arrays in C89 code.
7748static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7749 const NamedDecl *ND) {
7750 if (Size != 1 || !ND) return false;
7751
7752 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7753 if (!FD) return false;
7754
7755 // Don't consider sizes resulting from macro expansions or template argument
7756 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007757
7758 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007759 while (TInfo) {
7760 TypeLoc TL = TInfo->getTypeLoc();
7761 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007762 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7763 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007764 TInfo = TDL->getTypeSourceInfo();
7765 continue;
7766 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007767 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7768 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007769 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7770 return false;
7771 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007772 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007773 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007774
7775 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007776 if (!RD) return false;
7777 if (RD->isUnion()) return false;
7778 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7779 if (!CRD->isStandardLayout()) return false;
7780 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007781
Benjamin Kramer8c543672011-08-06 03:04:42 +00007782 // See if this is the last field decl in the record.
7783 const Decl *D = FD;
7784 while ((D = D->getNextDeclInContext()))
7785 if (isa<FieldDecl>(D))
7786 return false;
7787 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007788}
7789
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007790void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007791 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007792 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007793 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007794 if (IndexExpr->isValueDependent())
7795 return;
7796
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007797 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007798 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007799 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007800 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007801 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007802 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007803
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007804 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007805 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007806 return;
Richard Smith13f67182011-12-16 19:31:14 +00007807 if (IndexNegated)
7808 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007809
Craig Topperc3ec1492014-05-26 06:22:03 +00007810 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007811 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7812 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007813 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007814 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007815
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007816 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007817 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007818 if (!size.isStrictlyPositive())
7819 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007820
7821 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007822 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007823 // Make sure we're comparing apples to apples when comparing index to size
7824 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7825 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007826 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007827 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007828 if (ptrarith_typesize != array_typesize) {
7829 // There's a cast to a different size type involved
7830 uint64_t ratio = array_typesize / ptrarith_typesize;
7831 // TODO: Be smarter about handling cases where array_typesize is not a
7832 // multiple of ptrarith_typesize
7833 if (ptrarith_typesize * ratio == array_typesize)
7834 size *= llvm::APInt(size.getBitWidth(), ratio);
7835 }
7836 }
7837
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007838 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007839 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007840 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007841 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007842
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007843 // For array subscripting the index must be less than size, but for pointer
7844 // arithmetic also allow the index (offset) to be equal to size since
7845 // computing the next address after the end of the array is legal and
7846 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007847 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007848 return;
7849
7850 // Also don't warn for arrays of size 1 which are members of some
7851 // structure. These are often used to approximate flexible arrays in C89
7852 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007853 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007854 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007855
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007856 // Suppress the warning if the subscript expression (as identified by the
7857 // ']' location) and the index expression are both from macro expansions
7858 // within a system header.
7859 if (ASE) {
7860 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7861 ASE->getRBracketLoc());
7862 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7863 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7864 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007865 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007866 return;
7867 }
7868 }
7869
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007870 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007871 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007872 DiagID = diag::warn_array_index_exceeds_bounds;
7873
7874 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7875 PDiag(DiagID) << index.toString(10, true)
7876 << size.toString(10, true)
7877 << (unsigned)size.getLimitedValue(~0U)
7878 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007879 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007880 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007881 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007882 DiagID = diag::warn_ptr_arith_precedes_bounds;
7883 if (index.isNegative()) index = -index;
7884 }
7885
7886 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7887 PDiag(DiagID) << index.toString(10, true)
7888 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007889 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007890
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007891 if (!ND) {
7892 // Try harder to find a NamedDecl to point at in the note.
7893 while (const ArraySubscriptExpr *ASE =
7894 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7895 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7896 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7897 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7898 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7899 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7900 }
7901
Chandler Carruth1af88f12011-02-17 21:10:52 +00007902 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007903 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7904 PDiag(diag::note_array_index_out_of_bounds)
7905 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007906}
7907
Ted Kremenekdf26df72011-03-01 18:41:00 +00007908void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007909 int AllowOnePastEnd = 0;
7910 while (expr) {
7911 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007912 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007913 case Stmt::ArraySubscriptExprClass: {
7914 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007915 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007916 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007917 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007918 }
7919 case Stmt::UnaryOperatorClass: {
7920 // Only unwrap the * and & unary operators
7921 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7922 expr = UO->getSubExpr();
7923 switch (UO->getOpcode()) {
7924 case UO_AddrOf:
7925 AllowOnePastEnd++;
7926 break;
7927 case UO_Deref:
7928 AllowOnePastEnd--;
7929 break;
7930 default:
7931 return;
7932 }
7933 break;
7934 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007935 case Stmt::ConditionalOperatorClass: {
7936 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7937 if (const Expr *lhs = cond->getLHS())
7938 CheckArrayAccess(lhs);
7939 if (const Expr *rhs = cond->getRHS())
7940 CheckArrayAccess(rhs);
7941 return;
7942 }
7943 default:
7944 return;
7945 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007946 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007947}
John McCall31168b02011-06-15 23:02:42 +00007948
7949//===--- CHECK: Objective-C retain cycles ----------------------------------//
7950
7951namespace {
7952 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007953 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007954 VarDecl *Variable;
7955 SourceRange Range;
7956 SourceLocation Loc;
7957 bool Indirect;
7958
7959 void setLocsFrom(Expr *e) {
7960 Loc = e->getExprLoc();
7961 Range = e->getSourceRange();
7962 }
7963 };
7964}
7965
7966/// Consider whether capturing the given variable can possibly lead to
7967/// a retain cycle.
7968static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007969 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007970 // lifetime. In MRR, it's captured strongly if the variable is
7971 // __block and has an appropriate type.
7972 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7973 return false;
7974
7975 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007976 if (ref)
7977 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007978 return true;
7979}
7980
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007981static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007982 while (true) {
7983 e = e->IgnoreParens();
7984 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7985 switch (cast->getCastKind()) {
7986 case CK_BitCast:
7987 case CK_LValueBitCast:
7988 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007989 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007990 e = cast->getSubExpr();
7991 continue;
7992
John McCall31168b02011-06-15 23:02:42 +00007993 default:
7994 return false;
7995 }
7996 }
7997
7998 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7999 ObjCIvarDecl *ivar = ref->getDecl();
8000 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8001 return false;
8002
8003 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008004 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008005 return false;
8006
8007 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8008 owner.Indirect = true;
8009 return true;
8010 }
8011
8012 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8013 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8014 if (!var) return false;
8015 return considerVariable(var, ref, owner);
8016 }
8017
John McCall31168b02011-06-15 23:02:42 +00008018 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8019 if (member->isArrow()) return false;
8020
8021 // Don't count this as an indirect ownership.
8022 e = member->getBase();
8023 continue;
8024 }
8025
John McCallfe96e0b2011-11-06 09:01:30 +00008026 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8027 // Only pay attention to pseudo-objects on property references.
8028 ObjCPropertyRefExpr *pre
8029 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8030 ->IgnoreParens());
8031 if (!pre) return false;
8032 if (pre->isImplicitProperty()) return false;
8033 ObjCPropertyDecl *property = pre->getExplicitProperty();
8034 if (!property->isRetaining() &&
8035 !(property->getPropertyIvarDecl() &&
8036 property->getPropertyIvarDecl()->getType()
8037 .getObjCLifetime() == Qualifiers::OCL_Strong))
8038 return false;
8039
8040 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008041 if (pre->isSuperReceiver()) {
8042 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8043 if (!owner.Variable)
8044 return false;
8045 owner.Loc = pre->getLocation();
8046 owner.Range = pre->getSourceRange();
8047 return true;
8048 }
John McCallfe96e0b2011-11-06 09:01:30 +00008049 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8050 ->getSourceExpr());
8051 continue;
8052 }
8053
John McCall31168b02011-06-15 23:02:42 +00008054 // Array ivars?
8055
8056 return false;
8057 }
8058}
8059
8060namespace {
8061 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8062 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8063 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008064 Context(Context), Variable(variable), Capturer(nullptr),
8065 VarWillBeReased(false) {}
8066 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008067 VarDecl *Variable;
8068 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008069 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008070
8071 void VisitDeclRefExpr(DeclRefExpr *ref) {
8072 if (ref->getDecl() == Variable && !Capturer)
8073 Capturer = ref;
8074 }
8075
John McCall31168b02011-06-15 23:02:42 +00008076 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8077 if (Capturer) return;
8078 Visit(ref->getBase());
8079 if (Capturer && ref->isFreeIvar())
8080 Capturer = ref;
8081 }
8082
8083 void VisitBlockExpr(BlockExpr *block) {
8084 // Look inside nested blocks
8085 if (block->getBlockDecl()->capturesVariable(Variable))
8086 Visit(block->getBlockDecl()->getBody());
8087 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008088
8089 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8090 if (Capturer) return;
8091 if (OVE->getSourceExpr())
8092 Visit(OVE->getSourceExpr());
8093 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008094 void VisitBinaryOperator(BinaryOperator *BinOp) {
8095 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8096 return;
8097 Expr *LHS = BinOp->getLHS();
8098 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8099 if (DRE->getDecl() != Variable)
8100 return;
8101 if (Expr *RHS = BinOp->getRHS()) {
8102 RHS = RHS->IgnoreParenCasts();
8103 llvm::APSInt Value;
8104 VarWillBeReased =
8105 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8106 }
8107 }
8108 }
John McCall31168b02011-06-15 23:02:42 +00008109 };
8110}
8111
8112/// Check whether the given argument is a block which captures a
8113/// variable.
8114static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8115 assert(owner.Variable && owner.Loc.isValid());
8116
8117 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008118
8119 // Look through [^{...} copy] and Block_copy(^{...}).
8120 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8121 Selector Cmd = ME->getSelector();
8122 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8123 e = ME->getInstanceReceiver();
8124 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008125 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008126 e = e->IgnoreParenCasts();
8127 }
8128 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8129 if (CE->getNumArgs() == 1) {
8130 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008131 if (Fn) {
8132 const IdentifierInfo *FnI = Fn->getIdentifier();
8133 if (FnI && FnI->isStr("_Block_copy")) {
8134 e = CE->getArg(0)->IgnoreParenCasts();
8135 }
8136 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008137 }
8138 }
8139
John McCall31168b02011-06-15 23:02:42 +00008140 BlockExpr *block = dyn_cast<BlockExpr>(e);
8141 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008142 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008143
8144 FindCaptureVisitor visitor(S.Context, owner.Variable);
8145 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008146 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008147}
8148
8149static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8150 RetainCycleOwner &owner) {
8151 assert(capturer);
8152 assert(owner.Variable && owner.Loc.isValid());
8153
8154 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8155 << owner.Variable << capturer->getSourceRange();
8156 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8157 << owner.Indirect << owner.Range;
8158}
8159
8160/// Check for a keyword selector that starts with the word 'add' or
8161/// 'set'.
8162static bool isSetterLikeSelector(Selector sel) {
8163 if (sel.isUnarySelector()) return false;
8164
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008165 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008166 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008167 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008168 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008169 else if (str.startswith("add")) {
8170 // Specially whitelist 'addOperationWithBlock:'.
8171 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8172 return false;
8173 str = str.substr(3);
8174 }
John McCall31168b02011-06-15 23:02:42 +00008175 else
8176 return false;
8177
8178 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008179 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008180}
8181
8182/// Check a message send to see if it's likely to cause a retain cycle.
8183void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8184 // Only check instance methods whose selector looks like a setter.
8185 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8186 return;
8187
8188 // Try to find a variable that the receiver is strongly owned by.
8189 RetainCycleOwner owner;
8190 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008191 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008192 return;
8193 } else {
8194 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8195 owner.Variable = getCurMethodDecl()->getSelfDecl();
8196 owner.Loc = msg->getSuperLoc();
8197 owner.Range = msg->getSuperLoc();
8198 }
8199
8200 // Check whether the receiver is captured by any of the arguments.
8201 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8202 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8203 return diagnoseRetainCycle(*this, capturer, owner);
8204}
8205
8206/// Check a property assign to see if it's likely to cause a retain cycle.
8207void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8208 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008209 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008210 return;
8211
8212 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8213 diagnoseRetainCycle(*this, capturer, owner);
8214}
8215
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008216void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8217 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008218 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008219 return;
8220
8221 // Because we don't have an expression for the variable, we have to set the
8222 // location explicitly here.
8223 Owner.Loc = Var->getLocation();
8224 Owner.Range = Var->getSourceRange();
8225
8226 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8227 diagnoseRetainCycle(*this, Capturer, Owner);
8228}
8229
Ted Kremenek9304da92012-12-21 08:04:28 +00008230static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8231 Expr *RHS, bool isProperty) {
8232 // Check if RHS is an Objective-C object literal, which also can get
8233 // immediately zapped in a weak reference. Note that we explicitly
8234 // allow ObjCStringLiterals, since those are designed to never really die.
8235 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008236
Ted Kremenek64873352012-12-21 22:46:35 +00008237 // This enum needs to match with the 'select' in
8238 // warn_objc_arc_literal_assign (off-by-1).
8239 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8240 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8241 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008242
8243 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008244 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008245 << (isProperty ? 0 : 1)
8246 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008247
8248 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008249}
8250
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008251static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8252 Qualifiers::ObjCLifetime LT,
8253 Expr *RHS, bool isProperty) {
8254 // Strip off any implicit cast added to get to the one ARC-specific.
8255 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8256 if (cast->getCastKind() == CK_ARCConsumeObject) {
8257 S.Diag(Loc, diag::warn_arc_retained_assign)
8258 << (LT == Qualifiers::OCL_ExplicitNone)
8259 << (isProperty ? 0 : 1)
8260 << RHS->getSourceRange();
8261 return true;
8262 }
8263 RHS = cast->getSubExpr();
8264 }
8265
8266 if (LT == Qualifiers::OCL_Weak &&
8267 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8268 return true;
8269
8270 return false;
8271}
8272
Ted Kremenekb36234d2012-12-21 08:04:20 +00008273bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8274 QualType LHS, Expr *RHS) {
8275 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8276
8277 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8278 return false;
8279
8280 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8281 return true;
8282
8283 return false;
8284}
8285
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008286void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8287 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008288 QualType LHSType;
8289 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008290 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008291 ObjCPropertyRefExpr *PRE
8292 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8293 if (PRE && !PRE->isImplicitProperty()) {
8294 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8295 if (PD)
8296 LHSType = PD->getType();
8297 }
8298
8299 if (LHSType.isNull())
8300 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008301
8302 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8303
8304 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008305 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008306 getCurFunction()->markSafeWeakUse(LHS);
8307 }
8308
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008309 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8310 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008311
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008312 // FIXME. Check for other life times.
8313 if (LT != Qualifiers::OCL_None)
8314 return;
8315
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008316 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008317 if (PRE->isImplicitProperty())
8318 return;
8319 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8320 if (!PD)
8321 return;
8322
Bill Wendling44426052012-12-20 19:22:21 +00008323 unsigned Attributes = PD->getPropertyAttributes();
8324 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008325 // when 'assign' attribute was not explicitly specified
8326 // by user, ignore it and rely on property type itself
8327 // for lifetime info.
8328 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8329 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8330 LHSType->isObjCRetainableType())
8331 return;
8332
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008333 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008334 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008335 Diag(Loc, diag::warn_arc_retained_property_assign)
8336 << RHS->getSourceRange();
8337 return;
8338 }
8339 RHS = cast->getSubExpr();
8340 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008341 }
Bill Wendling44426052012-12-20 19:22:21 +00008342 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008343 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8344 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008345 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008346 }
8347}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008348
8349//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8350
8351namespace {
8352bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8353 SourceLocation StmtLoc,
8354 const NullStmt *Body) {
8355 // Do not warn if the body is a macro that expands to nothing, e.g:
8356 //
8357 // #define CALL(x)
8358 // if (condition)
8359 // CALL(0);
8360 //
8361 if (Body->hasLeadingEmptyMacro())
8362 return false;
8363
8364 // Get line numbers of statement and body.
8365 bool StmtLineInvalid;
8366 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8367 &StmtLineInvalid);
8368 if (StmtLineInvalid)
8369 return false;
8370
8371 bool BodyLineInvalid;
8372 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8373 &BodyLineInvalid);
8374 if (BodyLineInvalid)
8375 return false;
8376
8377 // Warn if null statement and body are on the same line.
8378 if (StmtLine != BodyLine)
8379 return false;
8380
8381 return true;
8382}
8383} // Unnamed namespace
8384
8385void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8386 const Stmt *Body,
8387 unsigned DiagID) {
8388 // Since this is a syntactic check, don't emit diagnostic for template
8389 // instantiations, this just adds noise.
8390 if (CurrentInstantiationScope)
8391 return;
8392
8393 // The body should be a null statement.
8394 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8395 if (!NBody)
8396 return;
8397
8398 // Do the usual checks.
8399 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8400 return;
8401
8402 Diag(NBody->getSemiLoc(), DiagID);
8403 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8404}
8405
8406void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8407 const Stmt *PossibleBody) {
8408 assert(!CurrentInstantiationScope); // Ensured by caller
8409
8410 SourceLocation StmtLoc;
8411 const Stmt *Body;
8412 unsigned DiagID;
8413 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8414 StmtLoc = FS->getRParenLoc();
8415 Body = FS->getBody();
8416 DiagID = diag::warn_empty_for_body;
8417 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8418 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8419 Body = WS->getBody();
8420 DiagID = diag::warn_empty_while_body;
8421 } else
8422 return; // Neither `for' nor `while'.
8423
8424 // The body should be a null statement.
8425 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8426 if (!NBody)
8427 return;
8428
8429 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008430 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008431 return;
8432
8433 // Do the usual checks.
8434 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8435 return;
8436
8437 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8438 // noise level low, emit diagnostics only if for/while is followed by a
8439 // CompoundStmt, e.g.:
8440 // for (int i = 0; i < n; i++);
8441 // {
8442 // a(i);
8443 // }
8444 // or if for/while is followed by a statement with more indentation
8445 // than for/while itself:
8446 // for (int i = 0; i < n; i++);
8447 // a(i);
8448 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8449 if (!ProbableTypo) {
8450 bool BodyColInvalid;
8451 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8452 PossibleBody->getLocStart(),
8453 &BodyColInvalid);
8454 if (BodyColInvalid)
8455 return;
8456
8457 bool StmtColInvalid;
8458 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8459 S->getLocStart(),
8460 &StmtColInvalid);
8461 if (StmtColInvalid)
8462 return;
8463
8464 if (BodyCol > StmtCol)
8465 ProbableTypo = true;
8466 }
8467
8468 if (ProbableTypo) {
8469 Diag(NBody->getSemiLoc(), DiagID);
8470 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8471 }
8472}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008473
Richard Trieu36d0b2b2015-01-13 02:32:02 +00008474//===--- CHECK: Warn on self move with std::move. -------------------------===//
8475
8476/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8477void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8478 SourceLocation OpLoc) {
8479
8480 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8481 return;
8482
8483 if (!ActiveTemplateInstantiations.empty())
8484 return;
8485
8486 // Strip parens and casts away.
8487 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8488 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8489
8490 // Check for a call expression
8491 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8492 if (!CE || CE->getNumArgs() != 1)
8493 return;
8494
8495 // Check for a call to std::move
8496 const FunctionDecl *FD = CE->getDirectCallee();
8497 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8498 !FD->getIdentifier()->isStr("move"))
8499 return;
8500
8501 // Get argument from std::move
8502 RHSExpr = CE->getArg(0);
8503
8504 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8505 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8506
8507 // Two DeclRefExpr's, check that the decls are the same.
8508 if (LHSDeclRef && RHSDeclRef) {
8509 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8510 return;
8511 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8512 RHSDeclRef->getDecl()->getCanonicalDecl())
8513 return;
8514
8515 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8516 << LHSExpr->getSourceRange()
8517 << RHSExpr->getSourceRange();
8518 return;
8519 }
8520
8521 // Member variables require a different approach to check for self moves.
8522 // MemberExpr's are the same if every nested MemberExpr refers to the same
8523 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8524 // the base Expr's are CXXThisExpr's.
8525 const Expr *LHSBase = LHSExpr;
8526 const Expr *RHSBase = RHSExpr;
8527 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8528 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8529 if (!LHSME || !RHSME)
8530 return;
8531
8532 while (LHSME && RHSME) {
8533 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8534 RHSME->getMemberDecl()->getCanonicalDecl())
8535 return;
8536
8537 LHSBase = LHSME->getBase();
8538 RHSBase = RHSME->getBase();
8539 LHSME = dyn_cast<MemberExpr>(LHSBase);
8540 RHSME = dyn_cast<MemberExpr>(RHSBase);
8541 }
8542
8543 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8544 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8545 if (LHSDeclRef && RHSDeclRef) {
8546 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8547 return;
8548 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8549 RHSDeclRef->getDecl()->getCanonicalDecl())
8550 return;
8551
8552 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8553 << LHSExpr->getSourceRange()
8554 << RHSExpr->getSourceRange();
8555 return;
8556 }
8557
8558 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8559 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8560 << LHSExpr->getSourceRange()
8561 << RHSExpr->getSourceRange();
8562}
8563
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008564//===--- Layout compatibility ----------------------------------------------//
8565
8566namespace {
8567
8568bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8569
8570/// \brief Check if two enumeration types are layout-compatible.
8571bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8572 // C++11 [dcl.enum] p8:
8573 // Two enumeration types are layout-compatible if they have the same
8574 // underlying type.
8575 return ED1->isComplete() && ED2->isComplete() &&
8576 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8577}
8578
8579/// \brief Check if two fields are layout-compatible.
8580bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8581 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8582 return false;
8583
8584 if (Field1->isBitField() != Field2->isBitField())
8585 return false;
8586
8587 if (Field1->isBitField()) {
8588 // Make sure that the bit-fields are the same length.
8589 unsigned Bits1 = Field1->getBitWidthValue(C);
8590 unsigned Bits2 = Field2->getBitWidthValue(C);
8591
8592 if (Bits1 != Bits2)
8593 return false;
8594 }
8595
8596 return true;
8597}
8598
8599/// \brief Check if two standard-layout structs are layout-compatible.
8600/// (C++11 [class.mem] p17)
8601bool isLayoutCompatibleStruct(ASTContext &C,
8602 RecordDecl *RD1,
8603 RecordDecl *RD2) {
8604 // If both records are C++ classes, check that base classes match.
8605 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8606 // If one of records is a CXXRecordDecl we are in C++ mode,
8607 // thus the other one is a CXXRecordDecl, too.
8608 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8609 // Check number of base classes.
8610 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8611 return false;
8612
8613 // Check the base classes.
8614 for (CXXRecordDecl::base_class_const_iterator
8615 Base1 = D1CXX->bases_begin(),
8616 BaseEnd1 = D1CXX->bases_end(),
8617 Base2 = D2CXX->bases_begin();
8618 Base1 != BaseEnd1;
8619 ++Base1, ++Base2) {
8620 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8621 return false;
8622 }
8623 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8624 // If only RD2 is a C++ class, it should have zero base classes.
8625 if (D2CXX->getNumBases() > 0)
8626 return false;
8627 }
8628
8629 // Check the fields.
8630 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8631 Field2End = RD2->field_end(),
8632 Field1 = RD1->field_begin(),
8633 Field1End = RD1->field_end();
8634 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8635 if (!isLayoutCompatible(C, *Field1, *Field2))
8636 return false;
8637 }
8638 if (Field1 != Field1End || Field2 != Field2End)
8639 return false;
8640
8641 return true;
8642}
8643
8644/// \brief Check if two standard-layout unions are layout-compatible.
8645/// (C++11 [class.mem] p18)
8646bool isLayoutCompatibleUnion(ASTContext &C,
8647 RecordDecl *RD1,
8648 RecordDecl *RD2) {
8649 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008650 for (auto *Field2 : RD2->fields())
8651 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008652
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008653 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008654 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8655 I = UnmatchedFields.begin(),
8656 E = UnmatchedFields.end();
8657
8658 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008659 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008660 bool Result = UnmatchedFields.erase(*I);
8661 (void) Result;
8662 assert(Result);
8663 break;
8664 }
8665 }
8666 if (I == E)
8667 return false;
8668 }
8669
8670 return UnmatchedFields.empty();
8671}
8672
8673bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8674 if (RD1->isUnion() != RD2->isUnion())
8675 return false;
8676
8677 if (RD1->isUnion())
8678 return isLayoutCompatibleUnion(C, RD1, RD2);
8679 else
8680 return isLayoutCompatibleStruct(C, RD1, RD2);
8681}
8682
8683/// \brief Check if two types are layout-compatible in C++11 sense.
8684bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8685 if (T1.isNull() || T2.isNull())
8686 return false;
8687
8688 // C++11 [basic.types] p11:
8689 // If two types T1 and T2 are the same type, then T1 and T2 are
8690 // layout-compatible types.
8691 if (C.hasSameType(T1, T2))
8692 return true;
8693
8694 T1 = T1.getCanonicalType().getUnqualifiedType();
8695 T2 = T2.getCanonicalType().getUnqualifiedType();
8696
8697 const Type::TypeClass TC1 = T1->getTypeClass();
8698 const Type::TypeClass TC2 = T2->getTypeClass();
8699
8700 if (TC1 != TC2)
8701 return false;
8702
8703 if (TC1 == Type::Enum) {
8704 return isLayoutCompatible(C,
8705 cast<EnumType>(T1)->getDecl(),
8706 cast<EnumType>(T2)->getDecl());
8707 } else if (TC1 == Type::Record) {
8708 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8709 return false;
8710
8711 return isLayoutCompatible(C,
8712 cast<RecordType>(T1)->getDecl(),
8713 cast<RecordType>(T2)->getDecl());
8714 }
8715
8716 return false;
8717}
8718}
8719
8720//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8721
8722namespace {
8723/// \brief Given a type tag expression find the type tag itself.
8724///
8725/// \param TypeExpr Type tag expression, as it appears in user's code.
8726///
8727/// \param VD Declaration of an identifier that appears in a type tag.
8728///
8729/// \param MagicValue Type tag magic value.
8730bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8731 const ValueDecl **VD, uint64_t *MagicValue) {
8732 while(true) {
8733 if (!TypeExpr)
8734 return false;
8735
8736 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8737
8738 switch (TypeExpr->getStmtClass()) {
8739 case Stmt::UnaryOperatorClass: {
8740 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8741 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8742 TypeExpr = UO->getSubExpr();
8743 continue;
8744 }
8745 return false;
8746 }
8747
8748 case Stmt::DeclRefExprClass: {
8749 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8750 *VD = DRE->getDecl();
8751 return true;
8752 }
8753
8754 case Stmt::IntegerLiteralClass: {
8755 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8756 llvm::APInt MagicValueAPInt = IL->getValue();
8757 if (MagicValueAPInt.getActiveBits() <= 64) {
8758 *MagicValue = MagicValueAPInt.getZExtValue();
8759 return true;
8760 } else
8761 return false;
8762 }
8763
8764 case Stmt::BinaryConditionalOperatorClass:
8765 case Stmt::ConditionalOperatorClass: {
8766 const AbstractConditionalOperator *ACO =
8767 cast<AbstractConditionalOperator>(TypeExpr);
8768 bool Result;
8769 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8770 if (Result)
8771 TypeExpr = ACO->getTrueExpr();
8772 else
8773 TypeExpr = ACO->getFalseExpr();
8774 continue;
8775 }
8776 return false;
8777 }
8778
8779 case Stmt::BinaryOperatorClass: {
8780 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8781 if (BO->getOpcode() == BO_Comma) {
8782 TypeExpr = BO->getRHS();
8783 continue;
8784 }
8785 return false;
8786 }
8787
8788 default:
8789 return false;
8790 }
8791 }
8792}
8793
8794/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8795///
8796/// \param TypeExpr Expression that specifies a type tag.
8797///
8798/// \param MagicValues Registered magic values.
8799///
8800/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8801/// kind.
8802///
8803/// \param TypeInfo Information about the corresponding C type.
8804///
8805/// \returns true if the corresponding C type was found.
8806bool GetMatchingCType(
8807 const IdentifierInfo *ArgumentKind,
8808 const Expr *TypeExpr, const ASTContext &Ctx,
8809 const llvm::DenseMap<Sema::TypeTagMagicValue,
8810 Sema::TypeTagData> *MagicValues,
8811 bool &FoundWrongKind,
8812 Sema::TypeTagData &TypeInfo) {
8813 FoundWrongKind = false;
8814
8815 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008816 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008817
8818 uint64_t MagicValue;
8819
8820 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8821 return false;
8822
8823 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008824 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008825 if (I->getArgumentKind() != ArgumentKind) {
8826 FoundWrongKind = true;
8827 return false;
8828 }
8829 TypeInfo.Type = I->getMatchingCType();
8830 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8831 TypeInfo.MustBeNull = I->getMustBeNull();
8832 return true;
8833 }
8834 return false;
8835 }
8836
8837 if (!MagicValues)
8838 return false;
8839
8840 llvm::DenseMap<Sema::TypeTagMagicValue,
8841 Sema::TypeTagData>::const_iterator I =
8842 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8843 if (I == MagicValues->end())
8844 return false;
8845
8846 TypeInfo = I->second;
8847 return true;
8848}
8849} // unnamed namespace
8850
8851void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8852 uint64_t MagicValue, QualType Type,
8853 bool LayoutCompatible,
8854 bool MustBeNull) {
8855 if (!TypeTagForDatatypeMagicValues)
8856 TypeTagForDatatypeMagicValues.reset(
8857 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8858
8859 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8860 (*TypeTagForDatatypeMagicValues)[Magic] =
8861 TypeTagData(Type, LayoutCompatible, MustBeNull);
8862}
8863
8864namespace {
8865bool IsSameCharType(QualType T1, QualType T2) {
8866 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8867 if (!BT1)
8868 return false;
8869
8870 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8871 if (!BT2)
8872 return false;
8873
8874 BuiltinType::Kind T1Kind = BT1->getKind();
8875 BuiltinType::Kind T2Kind = BT2->getKind();
8876
8877 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8878 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8879 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8880 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8881}
8882} // unnamed namespace
8883
8884void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8885 const Expr * const *ExprArgs) {
8886 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8887 bool IsPointerAttr = Attr->getIsPointer();
8888
8889 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8890 bool FoundWrongKind;
8891 TypeTagData TypeInfo;
8892 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8893 TypeTagForDatatypeMagicValues.get(),
8894 FoundWrongKind, TypeInfo)) {
8895 if (FoundWrongKind)
8896 Diag(TypeTagExpr->getExprLoc(),
8897 diag::warn_type_tag_for_datatype_wrong_kind)
8898 << TypeTagExpr->getSourceRange();
8899 return;
8900 }
8901
8902 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8903 if (IsPointerAttr) {
8904 // Skip implicit cast of pointer to `void *' (as a function argument).
8905 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008906 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008907 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008908 ArgumentExpr = ICE->getSubExpr();
8909 }
8910 QualType ArgumentType = ArgumentExpr->getType();
8911
8912 // Passing a `void*' pointer shouldn't trigger a warning.
8913 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8914 return;
8915
8916 if (TypeInfo.MustBeNull) {
8917 // Type tag with matching void type requires a null pointer.
8918 if (!ArgumentExpr->isNullPointerConstant(Context,
8919 Expr::NPC_ValueDependentIsNotNull)) {
8920 Diag(ArgumentExpr->getExprLoc(),
8921 diag::warn_type_safety_null_pointer_required)
8922 << ArgumentKind->getName()
8923 << ArgumentExpr->getSourceRange()
8924 << TypeTagExpr->getSourceRange();
8925 }
8926 return;
8927 }
8928
8929 QualType RequiredType = TypeInfo.Type;
8930 if (IsPointerAttr)
8931 RequiredType = Context.getPointerType(RequiredType);
8932
8933 bool mismatch = false;
8934 if (!TypeInfo.LayoutCompatible) {
8935 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8936
8937 // C++11 [basic.fundamental] p1:
8938 // Plain char, signed char, and unsigned char are three distinct types.
8939 //
8940 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8941 // char' depending on the current char signedness mode.
8942 if (mismatch)
8943 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8944 RequiredType->getPointeeType())) ||
8945 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8946 mismatch = false;
8947 } else
8948 if (IsPointerAttr)
8949 mismatch = !isLayoutCompatible(Context,
8950 ArgumentType->getPointeeType(),
8951 RequiredType->getPointeeType());
8952 else
8953 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8954
8955 if (mismatch)
8956 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008957 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008958 << TypeInfo.LayoutCompatible << RequiredType
8959 << ArgumentExpr->getSourceRange()
8960 << TypeTagExpr->getSourceRange();
8961}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008962