blob: 884bd7ddbba68032c14f8eaaebb3ec014f4698b6 [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) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00003771 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3772 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
3773 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3774 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00003775 // In this case, the specifier is wrong and should be changed to match
3776 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00003777 EmitFormatDiagnostic(S.PDiag(diag)
3778 << AT.getRepresentativeTypeName(S.Context)
3779 << IntendedTy << IsEnum << E->getSourceRange(),
3780 E->getLocStart(),
3781 /*IsStringLocation*/ false, SpecRange,
3782 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00003783
3784 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003785 // The canonical type for formatting this value is different from the
3786 // actual type of the expression. (This occurs, for example, with Darwin's
3787 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3788 // should be printed as 'long' for 64-bit compatibility.)
3789 // Rather than emitting a normal format/argument mismatch, we want to
3790 // add a cast to the recommended type (and correct the format string
3791 // if necessary).
3792 SmallString<16> CastBuf;
3793 llvm::raw_svector_ostream CastFix(CastBuf);
3794 CastFix << "(";
3795 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3796 CastFix << ")";
3797
3798 SmallVector<FixItHint,4> Hints;
3799 if (!AT.matchesType(S.Context, IntendedTy))
3800 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3801
3802 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3803 // If there's already a cast present, just replace it.
3804 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3805 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3806
3807 } else if (!requiresParensToAddCast(E)) {
3808 // If the expression has high enough precedence,
3809 // just write the C-style cast.
3810 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3811 CastFix.str()));
3812 } else {
3813 // Otherwise, add parens around the expression as well as the cast.
3814 CastFix << "(";
3815 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3816 CastFix.str()));
3817
Alp Tokerb6cc5922014-05-03 03:45:55 +00003818 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003819 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3820 }
3821
Jordan Rose0e5badd2012-12-05 18:44:49 +00003822 if (ShouldNotPrintDirectly) {
3823 // The expression has a type that should not be printed directly.
3824 // We extract the name from the typedef because we don't want to show
3825 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003826 StringRef Name;
3827 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3828 Name = TypedefTy->getDecl()->getName();
3829 else
3830 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003831 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003832 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003833 << E->getSourceRange(),
3834 E->getLocStart(), /*IsStringLocation=*/false,
3835 SpecRange, Hints);
3836 } else {
3837 // In this case, the expression could be printed using a different
3838 // specifier, but we've decided that the specifier is probably correct
3839 // and we should cast instead. Just use the normal warning message.
3840 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003841 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3842 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003843 << E->getSourceRange(),
3844 E->getLocStart(), /*IsStringLocation*/false,
3845 SpecRange, Hints);
3846 }
Jordan Roseaee34382012-09-05 22:56:26 +00003847 }
Jordan Rose22b74712012-09-05 22:56:19 +00003848 } else {
3849 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3850 SpecifierLen);
3851 // Since the warning for passing non-POD types to variadic functions
3852 // was deferred until now, we emit a warning for non-POD
3853 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003854 switch (S.isValidVarArgType(ExprTy)) {
3855 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00003856 case Sema::VAK_ValidInCXX11: {
3857 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3858 if (match == analyze_printf::ArgType::NoMatchPedantic) {
3859 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3860 }
Richard Smithd7293d72013-08-05 18:49:43 +00003861
Seth Cantrellb4802962015-03-04 03:12:10 +00003862 EmitFormatDiagnostic(
3863 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
3864 << IsEnum << CSR << E->getSourceRange(),
3865 E->getLocStart(), /*IsStringLocation*/ false, CSR);
3866 break;
3867 }
Richard Smithd7293d72013-08-05 18:49:43 +00003868 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00003869 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00003870 EmitFormatDiagnostic(
3871 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003872 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003873 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003874 << CallType
3875 << AT.getRepresentativeTypeName(S.Context)
3876 << CSR
3877 << E->getSourceRange(),
3878 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003879 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003880 break;
3881
3882 case Sema::VAK_Invalid:
3883 if (ExprTy->isObjCObjectType())
3884 EmitFormatDiagnostic(
3885 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3886 << S.getLangOpts().CPlusPlus11
3887 << ExprTy
3888 << CallType
3889 << AT.getRepresentativeTypeName(S.Context)
3890 << CSR
3891 << E->getSourceRange(),
3892 E->getLocStart(), /*IsStringLocation*/false, CSR);
3893 else
3894 // FIXME: If this is an initializer list, suggest removing the braces
3895 // or inserting a cast to the target type.
3896 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3897 << isa<InitListExpr>(E) << ExprTy << CallType
3898 << AT.getRepresentativeTypeName(S.Context)
3899 << E->getSourceRange();
3900 break;
3901 }
3902
3903 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3904 "format string specifier index out of range");
3905 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003906 }
3907
Ted Kremenekab278de2010-01-28 23:39:18 +00003908 return true;
3909}
3910
Ted Kremenek02087932010-07-16 02:11:22 +00003911//===--- CHECK: Scanf format string checking ------------------------------===//
3912
3913namespace {
3914class CheckScanfHandler : public CheckFormatHandler {
3915public:
3916 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3917 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003918 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003919 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003920 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003921 Sema::VariadicCallType CallType,
3922 llvm::SmallBitVector &CheckedVarArgs)
3923 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3924 numDataArgs, beg, hasVAListArg,
3925 Args, formatIdx, inFunctionCall, CallType,
3926 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003927 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003928
3929 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3930 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003931 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003932
3933 bool HandleInvalidScanfConversionSpecifier(
3934 const analyze_scanf::ScanfSpecifier &FS,
3935 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003936 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003937
Craig Toppere14c0f82014-03-12 04:55:44 +00003938 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003939};
Ted Kremenek019d2242010-01-29 01:50:07 +00003940}
Ted Kremenekab278de2010-01-28 23:39:18 +00003941
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003942void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3943 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003944 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3945 getLocationOfByte(end), /*IsStringLocation*/true,
3946 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003947}
3948
Ted Kremenekce815422010-07-19 21:25:57 +00003949bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3950 const analyze_scanf::ScanfSpecifier &FS,
3951 const char *startSpecifier,
3952 unsigned specifierLen) {
3953
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003954 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003955 FS.getConversionSpecifier();
3956
3957 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3958 getLocationOfByte(CS.getStart()),
3959 startSpecifier, specifierLen,
3960 CS.getStart(), CS.getLength());
3961}
3962
Ted Kremenek02087932010-07-16 02:11:22 +00003963bool CheckScanfHandler::HandleScanfSpecifier(
3964 const analyze_scanf::ScanfSpecifier &FS,
3965 const char *startSpecifier,
3966 unsigned specifierLen) {
3967
3968 using namespace analyze_scanf;
3969 using namespace analyze_format_string;
3970
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003971 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003972
Ted Kremenek6cd69422010-07-19 22:01:06 +00003973 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3974 // be used to decide if we are using positional arguments consistently.
3975 if (FS.consumesDataArgument()) {
3976 if (atFirstArg) {
3977 atFirstArg = false;
3978 usesPositionalArgs = FS.usesPositionalArg();
3979 }
3980 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003981 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3982 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003983 return false;
3984 }
Ted Kremenek02087932010-07-16 02:11:22 +00003985 }
3986
3987 // Check if the field with is non-zero.
3988 const OptionalAmount &Amt = FS.getFieldWidth();
3989 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3990 if (Amt.getConstantAmount() == 0) {
3991 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3992 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003993 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3994 getLocationOfByte(Amt.getStart()),
3995 /*IsStringLocation*/true, R,
3996 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003997 }
3998 }
Seth Cantrellb4802962015-03-04 03:12:10 +00003999
Ted Kremenek02087932010-07-16 02:11:22 +00004000 if (!FS.consumesDataArgument()) {
4001 // FIXME: Technically specifying a precision or field width here
4002 // makes no sense. Worth issuing a warning at some point.
4003 return true;
4004 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004005
Ted Kremenek02087932010-07-16 02:11:22 +00004006 // Consume the argument.
4007 unsigned argIndex = FS.getArgIndex();
4008 if (argIndex < NumDataArgs) {
4009 // The check to see if the argIndex is valid will come later.
4010 // We set the bit here because we may exit early from this
4011 // function if we encounter some other error.
4012 CoveredArgs.set(argIndex);
4013 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004014
Ted Kremenek4407ea42010-07-20 20:04:47 +00004015 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004016 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004017 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4018 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004019 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004020 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004021 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004022 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4023 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004024
Jordan Rose92303592012-09-08 04:00:03 +00004025 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4026 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4027
Ted Kremenek02087932010-07-16 02:11:22 +00004028 // The remaining checks depend on the data arguments.
4029 if (HasVAListArg)
4030 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004031
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004032 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004033 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004034
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004035 // Check that the argument type matches the format specifier.
4036 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004037 if (!Ex)
4038 return true;
4039
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004040 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004041
4042 if (!AT.isValid()) {
4043 return true;
4044 }
4045
Seth Cantrellb4802962015-03-04 03:12:10 +00004046 analyze_format_string::ArgType::MatchKind match =
4047 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004048 if (match == analyze_format_string::ArgType::Match) {
4049 return true;
4050 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004051
Seth Cantrell79340072015-03-04 05:58:08 +00004052 ScanfSpecifier fixedFS = FS;
4053 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4054 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004055
Seth Cantrell79340072015-03-04 05:58:08 +00004056 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4057 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4058 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4059 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004060
Seth Cantrell79340072015-03-04 05:58:08 +00004061 if (success) {
4062 // Get the fix string from the fixed format specifier.
4063 SmallString<128> buf;
4064 llvm::raw_svector_ostream os(buf);
4065 fixedFS.toString(os);
4066
4067 EmitFormatDiagnostic(
4068 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4069 << Ex->getType() << false << Ex->getSourceRange(),
4070 Ex->getLocStart(),
4071 /*IsStringLocation*/ false,
4072 getSpecifierRange(startSpecifier, specifierLen),
4073 FixItHint::CreateReplacement(
4074 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4075 } else {
4076 EmitFormatDiagnostic(S.PDiag(diag)
4077 << AT.getRepresentativeTypeName(S.Context)
4078 << Ex->getType() << false << Ex->getSourceRange(),
4079 Ex->getLocStart(),
4080 /*IsStringLocation*/ false,
4081 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004082 }
4083
Ted Kremenek02087932010-07-16 02:11:22 +00004084 return true;
4085}
4086
4087void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004088 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004089 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004090 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004091 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004092 bool inFunctionCall, VariadicCallType CallType,
4093 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004094
Ted Kremenekab278de2010-01-28 23:39:18 +00004095 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004096 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004097 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004098 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004099 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4100 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004101 return;
4102 }
Ted Kremenek02087932010-07-16 02:11:22 +00004103
Ted Kremenekab278de2010-01-28 23:39:18 +00004104 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004105 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004106 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004107 // Account for cases where the string literal is truncated in a declaration.
4108 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4109 assert(T && "String literal not of constant array type!");
4110 size_t TypeSize = T->getSize().getZExtValue();
4111 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004112 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004113
4114 // Emit a warning if the string literal is truncated and does not contain an
4115 // embedded null character.
4116 if (TypeSize <= StrRef.size() &&
4117 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4118 CheckFormatHandler::EmitFormatDiagnostic(
4119 *this, inFunctionCall, Args[format_idx],
4120 PDiag(diag::warn_printf_format_string_not_null_terminated),
4121 FExpr->getLocStart(),
4122 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4123 return;
4124 }
4125
Ted Kremenekab278de2010-01-28 23:39:18 +00004126 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004127 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004128 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004129 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004130 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4131 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004132 return;
4133 }
Ted Kremenek02087932010-07-16 02:11:22 +00004134
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004135 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004136 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004137 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004138 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004139 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004140 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004141
Hans Wennborg23926bd2011-12-15 10:25:47 +00004142 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004143 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004144 Context.getTargetInfo(),
4145 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004146 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004147 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004148 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004149 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004150 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004151
Hans Wennborg23926bd2011-12-15 10:25:47 +00004152 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004153 getLangOpts(),
4154 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004155 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004156 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004157}
4158
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004159bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4160 // Str - The format string. NOTE: this is NOT null-terminated!
4161 StringRef StrRef = FExpr->getString();
4162 const char *Str = StrRef.data();
4163 // Account for cases where the string literal is truncated in a declaration.
4164 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4165 assert(T && "String literal not of constant array type!");
4166 size_t TypeSize = T->getSize().getZExtValue();
4167 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4168 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4169 getLangOpts(),
4170 Context.getTargetInfo());
4171}
4172
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004173//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4174
4175// Returns the related absolute value function that is larger, of 0 if one
4176// does not exist.
4177static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4178 switch (AbsFunction) {
4179 default:
4180 return 0;
4181
4182 case Builtin::BI__builtin_abs:
4183 return Builtin::BI__builtin_labs;
4184 case Builtin::BI__builtin_labs:
4185 return Builtin::BI__builtin_llabs;
4186 case Builtin::BI__builtin_llabs:
4187 return 0;
4188
4189 case Builtin::BI__builtin_fabsf:
4190 return Builtin::BI__builtin_fabs;
4191 case Builtin::BI__builtin_fabs:
4192 return Builtin::BI__builtin_fabsl;
4193 case Builtin::BI__builtin_fabsl:
4194 return 0;
4195
4196 case Builtin::BI__builtin_cabsf:
4197 return Builtin::BI__builtin_cabs;
4198 case Builtin::BI__builtin_cabs:
4199 return Builtin::BI__builtin_cabsl;
4200 case Builtin::BI__builtin_cabsl:
4201 return 0;
4202
4203 case Builtin::BIabs:
4204 return Builtin::BIlabs;
4205 case Builtin::BIlabs:
4206 return Builtin::BIllabs;
4207 case Builtin::BIllabs:
4208 return 0;
4209
4210 case Builtin::BIfabsf:
4211 return Builtin::BIfabs;
4212 case Builtin::BIfabs:
4213 return Builtin::BIfabsl;
4214 case Builtin::BIfabsl:
4215 return 0;
4216
4217 case Builtin::BIcabsf:
4218 return Builtin::BIcabs;
4219 case Builtin::BIcabs:
4220 return Builtin::BIcabsl;
4221 case Builtin::BIcabsl:
4222 return 0;
4223 }
4224}
4225
4226// Returns the argument type of the absolute value function.
4227static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4228 unsigned AbsType) {
4229 if (AbsType == 0)
4230 return QualType();
4231
4232 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4233 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4234 if (Error != ASTContext::GE_None)
4235 return QualType();
4236
4237 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4238 if (!FT)
4239 return QualType();
4240
4241 if (FT->getNumParams() != 1)
4242 return QualType();
4243
4244 return FT->getParamType(0);
4245}
4246
4247// Returns the best absolute value function, or zero, based on type and
4248// current absolute value function.
4249static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4250 unsigned AbsFunctionKind) {
4251 unsigned BestKind = 0;
4252 uint64_t ArgSize = Context.getTypeSize(ArgType);
4253 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4254 Kind = getLargerAbsoluteValueFunction(Kind)) {
4255 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4256 if (Context.getTypeSize(ParamType) >= ArgSize) {
4257 if (BestKind == 0)
4258 BestKind = Kind;
4259 else if (Context.hasSameType(ParamType, ArgType)) {
4260 BestKind = Kind;
4261 break;
4262 }
4263 }
4264 }
4265 return BestKind;
4266}
4267
4268enum AbsoluteValueKind {
4269 AVK_Integer,
4270 AVK_Floating,
4271 AVK_Complex
4272};
4273
4274static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4275 if (T->isIntegralOrEnumerationType())
4276 return AVK_Integer;
4277 if (T->isRealFloatingType())
4278 return AVK_Floating;
4279 if (T->isAnyComplexType())
4280 return AVK_Complex;
4281
4282 llvm_unreachable("Type not integer, floating, or complex");
4283}
4284
4285// Changes the absolute value function to a different type. Preserves whether
4286// the function is a builtin.
4287static unsigned changeAbsFunction(unsigned AbsKind,
4288 AbsoluteValueKind ValueKind) {
4289 switch (ValueKind) {
4290 case AVK_Integer:
4291 switch (AbsKind) {
4292 default:
4293 return 0;
4294 case Builtin::BI__builtin_fabsf:
4295 case Builtin::BI__builtin_fabs:
4296 case Builtin::BI__builtin_fabsl:
4297 case Builtin::BI__builtin_cabsf:
4298 case Builtin::BI__builtin_cabs:
4299 case Builtin::BI__builtin_cabsl:
4300 return Builtin::BI__builtin_abs;
4301 case Builtin::BIfabsf:
4302 case Builtin::BIfabs:
4303 case Builtin::BIfabsl:
4304 case Builtin::BIcabsf:
4305 case Builtin::BIcabs:
4306 case Builtin::BIcabsl:
4307 return Builtin::BIabs;
4308 }
4309 case AVK_Floating:
4310 switch (AbsKind) {
4311 default:
4312 return 0;
4313 case Builtin::BI__builtin_abs:
4314 case Builtin::BI__builtin_labs:
4315 case Builtin::BI__builtin_llabs:
4316 case Builtin::BI__builtin_cabsf:
4317 case Builtin::BI__builtin_cabs:
4318 case Builtin::BI__builtin_cabsl:
4319 return Builtin::BI__builtin_fabsf;
4320 case Builtin::BIabs:
4321 case Builtin::BIlabs:
4322 case Builtin::BIllabs:
4323 case Builtin::BIcabsf:
4324 case Builtin::BIcabs:
4325 case Builtin::BIcabsl:
4326 return Builtin::BIfabsf;
4327 }
4328 case AVK_Complex:
4329 switch (AbsKind) {
4330 default:
4331 return 0;
4332 case Builtin::BI__builtin_abs:
4333 case Builtin::BI__builtin_labs:
4334 case Builtin::BI__builtin_llabs:
4335 case Builtin::BI__builtin_fabsf:
4336 case Builtin::BI__builtin_fabs:
4337 case Builtin::BI__builtin_fabsl:
4338 return Builtin::BI__builtin_cabsf;
4339 case Builtin::BIabs:
4340 case Builtin::BIlabs:
4341 case Builtin::BIllabs:
4342 case Builtin::BIfabsf:
4343 case Builtin::BIfabs:
4344 case Builtin::BIfabsl:
4345 return Builtin::BIcabsf;
4346 }
4347 }
4348 llvm_unreachable("Unable to convert function");
4349}
4350
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004351static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004352 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4353 if (!FnInfo)
4354 return 0;
4355
4356 switch (FDecl->getBuiltinID()) {
4357 default:
4358 return 0;
4359 case Builtin::BI__builtin_abs:
4360 case Builtin::BI__builtin_fabs:
4361 case Builtin::BI__builtin_fabsf:
4362 case Builtin::BI__builtin_fabsl:
4363 case Builtin::BI__builtin_labs:
4364 case Builtin::BI__builtin_llabs:
4365 case Builtin::BI__builtin_cabs:
4366 case Builtin::BI__builtin_cabsf:
4367 case Builtin::BI__builtin_cabsl:
4368 case Builtin::BIabs:
4369 case Builtin::BIlabs:
4370 case Builtin::BIllabs:
4371 case Builtin::BIfabs:
4372 case Builtin::BIfabsf:
4373 case Builtin::BIfabsl:
4374 case Builtin::BIcabs:
4375 case Builtin::BIcabsf:
4376 case Builtin::BIcabsl:
4377 return FDecl->getBuiltinID();
4378 }
4379 llvm_unreachable("Unknown Builtin type");
4380}
4381
4382// If the replacement is valid, emit a note with replacement function.
4383// Additionally, suggest including the proper header if not already included.
4384static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004385 unsigned AbsKind, QualType ArgType) {
4386 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004387 const char *HeaderName = nullptr;
4388 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004389 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4390 FunctionName = "std::abs";
4391 if (ArgType->isIntegralOrEnumerationType()) {
4392 HeaderName = "cstdlib";
4393 } else if (ArgType->isRealFloatingType()) {
4394 HeaderName = "cmath";
4395 } else {
4396 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004397 }
Richard Trieubeffb832014-04-15 23:47:53 +00004398
4399 // Lookup all std::abs
4400 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004401 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004402 R.suppressDiagnostics();
4403 S.LookupQualifiedName(R, Std);
4404
4405 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004406 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004407 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4408 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4409 } else {
4410 FDecl = dyn_cast<FunctionDecl>(I);
4411 }
4412 if (!FDecl)
4413 continue;
4414
4415 // Found std::abs(), check that they are the right ones.
4416 if (FDecl->getNumParams() != 1)
4417 continue;
4418
4419 // Check that the parameter type can handle the argument.
4420 QualType ParamType = FDecl->getParamDecl(0)->getType();
4421 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4422 S.Context.getTypeSize(ArgType) <=
4423 S.Context.getTypeSize(ParamType)) {
4424 // Found a function, don't need the header hint.
4425 EmitHeaderHint = false;
4426 break;
4427 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004428 }
Richard Trieubeffb832014-04-15 23:47:53 +00004429 }
4430 } else {
4431 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4432 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4433
4434 if (HeaderName) {
4435 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4436 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4437 R.suppressDiagnostics();
4438 S.LookupName(R, S.getCurScope());
4439
4440 if (R.isSingleResult()) {
4441 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4442 if (FD && FD->getBuiltinID() == AbsKind) {
4443 EmitHeaderHint = false;
4444 } else {
4445 return;
4446 }
4447 } else if (!R.empty()) {
4448 return;
4449 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004450 }
4451 }
4452
4453 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004454 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004455
Richard Trieubeffb832014-04-15 23:47:53 +00004456 if (!HeaderName)
4457 return;
4458
4459 if (!EmitHeaderHint)
4460 return;
4461
Alp Toker5d96e0a2014-07-11 20:53:51 +00004462 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4463 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004464}
4465
4466static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4467 if (!FDecl)
4468 return false;
4469
4470 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4471 return false;
4472
4473 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4474
4475 while (ND && ND->isInlineNamespace()) {
4476 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004477 }
Richard Trieubeffb832014-04-15 23:47:53 +00004478
4479 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4480 return false;
4481
4482 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4483 return false;
4484
4485 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004486}
4487
4488// Warn when using the wrong abs() function.
4489void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4490 const FunctionDecl *FDecl,
4491 IdentifierInfo *FnInfo) {
4492 if (Call->getNumArgs() != 1)
4493 return;
4494
4495 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004496 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4497 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004498 return;
4499
4500 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4501 QualType ParamType = Call->getArg(0)->getType();
4502
Alp Toker5d96e0a2014-07-11 20:53:51 +00004503 // Unsigned types cannot be negative. Suggest removing the absolute value
4504 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004505 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004506 const char *FunctionName =
4507 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004508 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4509 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004510 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004511 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4512 return;
4513 }
4514
Richard Trieubeffb832014-04-15 23:47:53 +00004515 // std::abs has overloads which prevent most of the absolute value problems
4516 // from occurring.
4517 if (IsStdAbs)
4518 return;
4519
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004520 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4521 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4522
4523 // The argument and parameter are the same kind. Check if they are the right
4524 // size.
4525 if (ArgValueKind == ParamValueKind) {
4526 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4527 return;
4528
4529 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4530 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4531 << FDecl << ArgType << ParamType;
4532
4533 if (NewAbsKind == 0)
4534 return;
4535
4536 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004537 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004538 return;
4539 }
4540
4541 // ArgValueKind != ParamValueKind
4542 // The wrong type of absolute value function was used. Attempt to find the
4543 // proper one.
4544 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4545 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4546 if (NewAbsKind == 0)
4547 return;
4548
4549 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4550 << FDecl << ParamValueKind << ArgValueKind;
4551
4552 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004553 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004554 return;
4555}
4556
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004557//===--- CHECK: Standard memory functions ---------------------------------===//
4558
Nico Weber0e6daef2013-12-26 23:38:39 +00004559/// \brief Takes the expression passed to the size_t parameter of functions
4560/// such as memcmp, strncat, etc and warns if it's a comparison.
4561///
4562/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4563static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4564 IdentifierInfo *FnName,
4565 SourceLocation FnLoc,
4566 SourceLocation RParenLoc) {
4567 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4568 if (!Size)
4569 return false;
4570
4571 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4572 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4573 return false;
4574
Nico Weber0e6daef2013-12-26 23:38:39 +00004575 SourceRange SizeRange = Size->getSourceRange();
4576 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4577 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004578 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004579 << FnName << FixItHint::CreateInsertion(
4580 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004581 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004582 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004583 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004584 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4585 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004586
4587 return true;
4588}
4589
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004590/// \brief Determine whether the given type is or contains a dynamic class type
4591/// (e.g., whether it has a vtable).
4592static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4593 bool &IsContained) {
4594 // Look through array types while ignoring qualifiers.
4595 const Type *Ty = T->getBaseElementTypeUnsafe();
4596 IsContained = false;
4597
4598 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4599 RD = RD ? RD->getDefinition() : nullptr;
4600 if (!RD)
4601 return nullptr;
4602
4603 if (RD->isDynamicClass())
4604 return RD;
4605
4606 // Check all the fields. If any bases were dynamic, the class is dynamic.
4607 // It's impossible for a class to transitively contain itself by value, so
4608 // infinite recursion is impossible.
4609 for (auto *FD : RD->fields()) {
4610 bool SubContained;
4611 if (const CXXRecordDecl *ContainedRD =
4612 getContainedDynamicClass(FD->getType(), SubContained)) {
4613 IsContained = true;
4614 return ContainedRD;
4615 }
4616 }
4617
4618 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004619}
4620
Chandler Carruth889ed862011-06-21 23:04:20 +00004621/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004622/// otherwise returns NULL.
4623static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004624 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004625 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4626 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4627 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004628
Craig Topperc3ec1492014-05-26 06:22:03 +00004629 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004630}
4631
Chandler Carruth889ed862011-06-21 23:04:20 +00004632/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004633static QualType getSizeOfArgType(const Expr* E) {
4634 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4635 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4636 if (SizeOf->getKind() == clang::UETT_SizeOf)
4637 return SizeOf->getTypeOfArgument();
4638
4639 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004640}
4641
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004642/// \brief Check for dangerous or invalid arguments to memset().
4643///
Chandler Carruthac687262011-06-03 06:23:57 +00004644/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004645/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4646/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004647///
4648/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004649void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004650 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004651 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004652 assert(BId != 0);
4653
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004654 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004655 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004656 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004657 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004658 return;
4659
Anna Zaks22122702012-01-17 00:37:07 +00004660 unsigned LastArg = (BId == Builtin::BImemset ||
4661 BId == Builtin::BIstrndup ? 1 : 2);
4662 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004663 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004664
Nico Weber0e6daef2013-12-26 23:38:39 +00004665 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4666 Call->getLocStart(), Call->getRParenLoc()))
4667 return;
4668
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004669 // We have special checking when the length is a sizeof expression.
4670 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4671 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4672 llvm::FoldingSetNodeID SizeOfArgID;
4673
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004674 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4675 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004676 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004677
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004678 QualType DestTy = Dest->getType();
4679 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4680 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004681
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004682 // Never warn about void type pointers. This can be used to suppress
4683 // false positives.
4684 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004685 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004686
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004687 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4688 // actually comparing the expressions for equality. Because computing the
4689 // expression IDs can be expensive, we only do this if the diagnostic is
4690 // enabled.
4691 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004692 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4693 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004694 // We only compute IDs for expressions if the warning is enabled, and
4695 // cache the sizeof arg's ID.
4696 if (SizeOfArgID == llvm::FoldingSetNodeID())
4697 SizeOfArg->Profile(SizeOfArgID, Context, true);
4698 llvm::FoldingSetNodeID DestID;
4699 Dest->Profile(DestID, Context, true);
4700 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004701 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4702 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004703 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004704 StringRef ReadableName = FnName->getName();
4705
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004706 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004707 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004708 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004709 if (!PointeeTy->isIncompleteType() &&
4710 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004711 ActionIdx = 2; // If the pointee's size is sizeof(char),
4712 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004713
4714 // If the function is defined as a builtin macro, do not show macro
4715 // expansion.
4716 SourceLocation SL = SizeOfArg->getExprLoc();
4717 SourceRange DSR = Dest->getSourceRange();
4718 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004719 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004720
4721 if (SM.isMacroArgExpansion(SL)) {
4722 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4723 SL = SM.getSpellingLoc(SL);
4724 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4725 SM.getSpellingLoc(DSR.getEnd()));
4726 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4727 SM.getSpellingLoc(SSR.getEnd()));
4728 }
4729
Anna Zaksd08d9152012-05-30 23:14:52 +00004730 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004731 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004732 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004733 << PointeeTy
4734 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004735 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004736 << SSR);
4737 DiagRuntimeBehavior(SL, SizeOfArg,
4738 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4739 << ActionIdx
4740 << SSR);
4741
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004742 break;
4743 }
4744 }
4745
4746 // Also check for cases where the sizeof argument is the exact same
4747 // type as the memory argument, and where it points to a user-defined
4748 // record type.
4749 if (SizeOfArgTy != QualType()) {
4750 if (PointeeTy->isRecordType() &&
4751 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4752 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4753 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4754 << FnName << SizeOfArgTy << ArgIdx
4755 << PointeeTy << Dest->getSourceRange()
4756 << LenExpr->getSourceRange());
4757 break;
4758 }
Nico Weberc5e73862011-06-14 16:14:58 +00004759 }
4760
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004761 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004762 bool IsContained;
4763 if (const CXXRecordDecl *ContainedRD =
4764 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004765
4766 unsigned OperationType = 0;
4767 // "overwritten" if we're warning about the destination for any call
4768 // but memcmp; otherwise a verb appropriate to the call.
4769 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4770 if (BId == Builtin::BImemcpy)
4771 OperationType = 1;
4772 else if(BId == Builtin::BImemmove)
4773 OperationType = 2;
4774 else if (BId == Builtin::BImemcmp)
4775 OperationType = 3;
4776 }
4777
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004778 DiagRuntimeBehavior(
4779 Dest->getExprLoc(), Dest,
4780 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004781 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004782 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004783 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004784 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4785 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004786 DiagRuntimeBehavior(
4787 Dest->getExprLoc(), Dest,
4788 PDiag(diag::warn_arc_object_memaccess)
4789 << ArgIdx << FnName << PointeeTy
4790 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004791 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004792 continue;
John McCall31168b02011-06-15 23:02:42 +00004793
4794 DiagRuntimeBehavior(
4795 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004796 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004797 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4798 break;
4799 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004800 }
4801}
4802
Ted Kremenek6865f772011-08-18 20:55:45 +00004803// A little helper routine: ignore addition and subtraction of integer literals.
4804// This intentionally does not ignore all integer constant expressions because
4805// we don't want to remove sizeof().
4806static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4807 Ex = Ex->IgnoreParenCasts();
4808
4809 for (;;) {
4810 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4811 if (!BO || !BO->isAdditiveOp())
4812 break;
4813
4814 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4815 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4816
4817 if (isa<IntegerLiteral>(RHS))
4818 Ex = LHS;
4819 else if (isa<IntegerLiteral>(LHS))
4820 Ex = RHS;
4821 else
4822 break;
4823 }
4824
4825 return Ex;
4826}
4827
Anna Zaks13b08572012-08-08 21:42:23 +00004828static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4829 ASTContext &Context) {
4830 // Only handle constant-sized or VLAs, but not flexible members.
4831 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4832 // Only issue the FIXIT for arrays of size > 1.
4833 if (CAT->getSize().getSExtValue() <= 1)
4834 return false;
4835 } else if (!Ty->isVariableArrayType()) {
4836 return false;
4837 }
4838 return true;
4839}
4840
Ted Kremenek6865f772011-08-18 20:55:45 +00004841// Warn if the user has made the 'size' argument to strlcpy or strlcat
4842// be the size of the source, instead of the destination.
4843void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4844 IdentifierInfo *FnName) {
4845
4846 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004847 unsigned NumArgs = Call->getNumArgs();
4848 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004849 return;
4850
4851 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4852 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004853 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004854
4855 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4856 Call->getLocStart(), Call->getRParenLoc()))
4857 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004858
4859 // Look for 'strlcpy(dst, x, sizeof(x))'
4860 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4861 CompareWithSrc = Ex;
4862 else {
4863 // Look for 'strlcpy(dst, x, strlen(x))'
4864 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004865 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4866 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004867 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4868 }
4869 }
4870
4871 if (!CompareWithSrc)
4872 return;
4873
4874 // Determine if the argument to sizeof/strlen is equal to the source
4875 // argument. In principle there's all kinds of things you could do
4876 // here, for instance creating an == expression and evaluating it with
4877 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4878 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4879 if (!SrcArgDRE)
4880 return;
4881
4882 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4883 if (!CompareWithSrcDRE ||
4884 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4885 return;
4886
4887 const Expr *OriginalSizeArg = Call->getArg(2);
4888 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4889 << OriginalSizeArg->getSourceRange() << FnName;
4890
4891 // Output a FIXIT hint if the destination is an array (rather than a
4892 // pointer to an array). This could be enhanced to handle some
4893 // pointers if we know the actual size, like if DstArg is 'array+2'
4894 // we could say 'sizeof(array)-2'.
4895 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004896 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004897 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004898
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004899 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004900 llvm::raw_svector_ostream OS(sizeString);
4901 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004902 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004903 OS << ")";
4904
4905 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4906 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4907 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004908}
4909
Anna Zaks314cd092012-02-01 19:08:57 +00004910/// Check if two expressions refer to the same declaration.
4911static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4912 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4913 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4914 return D1->getDecl() == D2->getDecl();
4915 return false;
4916}
4917
4918static const Expr *getStrlenExprArg(const Expr *E) {
4919 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4920 const FunctionDecl *FD = CE->getDirectCallee();
4921 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004922 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004923 return CE->getArg(0)->IgnoreParenCasts();
4924 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004925 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004926}
4927
4928// Warn on anti-patterns as the 'size' argument to strncat.
4929// The correct size argument should look like following:
4930// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4931void Sema::CheckStrncatArguments(const CallExpr *CE,
4932 IdentifierInfo *FnName) {
4933 // Don't crash if the user has the wrong number of arguments.
4934 if (CE->getNumArgs() < 3)
4935 return;
4936 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4937 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4938 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4939
Nico Weber0e6daef2013-12-26 23:38:39 +00004940 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4941 CE->getRParenLoc()))
4942 return;
4943
Anna Zaks314cd092012-02-01 19:08:57 +00004944 // Identify common expressions, which are wrongly used as the size argument
4945 // to strncat and may lead to buffer overflows.
4946 unsigned PatternType = 0;
4947 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4948 // - sizeof(dst)
4949 if (referToTheSameDecl(SizeOfArg, DstArg))
4950 PatternType = 1;
4951 // - sizeof(src)
4952 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4953 PatternType = 2;
4954 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4955 if (BE->getOpcode() == BO_Sub) {
4956 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4957 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4958 // - sizeof(dst) - strlen(dst)
4959 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4960 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4961 PatternType = 1;
4962 // - sizeof(src) - (anything)
4963 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4964 PatternType = 2;
4965 }
4966 }
4967
4968 if (PatternType == 0)
4969 return;
4970
Anna Zaks5069aa32012-02-03 01:27:37 +00004971 // Generate the diagnostic.
4972 SourceLocation SL = LenArg->getLocStart();
4973 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004974 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004975
4976 // If the function is defined as a builtin macro, do not show macro expansion.
4977 if (SM.isMacroArgExpansion(SL)) {
4978 SL = SM.getSpellingLoc(SL);
4979 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4980 SM.getSpellingLoc(SR.getEnd()));
4981 }
4982
Anna Zaks13b08572012-08-08 21:42:23 +00004983 // Check if the destination is an array (rather than a pointer to an array).
4984 QualType DstTy = DstArg->getType();
4985 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4986 Context);
4987 if (!isKnownSizeArray) {
4988 if (PatternType == 1)
4989 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4990 else
4991 Diag(SL, diag::warn_strncat_src_size) << SR;
4992 return;
4993 }
4994
Anna Zaks314cd092012-02-01 19:08:57 +00004995 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004996 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004997 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004998 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004999
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005000 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005001 llvm::raw_svector_ostream OS(sizeString);
5002 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005003 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005004 OS << ") - ";
5005 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005006 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005007 OS << ") - 1";
5008
Anna Zaks5069aa32012-02-03 01:27:37 +00005009 Diag(SL, diag::note_strncat_wrong_size)
5010 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005011}
5012
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005013//===--- CHECK: Return Address of Stack Variable --------------------------===//
5014
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005015static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5016 Decl *ParentDecl);
5017static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5018 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005019
5020/// CheckReturnStackAddr - Check if a return statement returns the address
5021/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005022static void
5023CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5024 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005025
Craig Topperc3ec1492014-05-26 06:22:03 +00005026 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005027 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005028
5029 // Perform checking for returned stack addresses, local blocks,
5030 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005031 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005032 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005033 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005034 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005035 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005036 }
5037
Craig Topperc3ec1492014-05-26 06:22:03 +00005038 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005039 return; // Nothing suspicious was found.
5040
5041 SourceLocation diagLoc;
5042 SourceRange diagRange;
5043 if (refVars.empty()) {
5044 diagLoc = stackE->getLocStart();
5045 diagRange = stackE->getSourceRange();
5046 } else {
5047 // We followed through a reference variable. 'stackE' contains the
5048 // problematic expression but we will warn at the return statement pointing
5049 // at the reference variable. We will later display the "trail" of
5050 // reference variables using notes.
5051 diagLoc = refVars[0]->getLocStart();
5052 diagRange = refVars[0]->getSourceRange();
5053 }
5054
5055 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005056 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005057 : diag::warn_ret_stack_addr)
5058 << DR->getDecl()->getDeclName() << diagRange;
5059 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005060 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005061 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005062 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005063 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005064 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5065 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005066 << diagRange;
5067 }
5068
5069 // Display the "trail" of reference variables that we followed until we
5070 // found the problematic expression using notes.
5071 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5072 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5073 // If this var binds to another reference var, show the range of the next
5074 // var, otherwise the var binds to the problematic expression, in which case
5075 // show the range of the expression.
5076 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5077 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005078 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5079 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005080 }
5081}
5082
5083/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5084/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005085/// to a location on the stack, a local block, an address of a label, or a
5086/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005087/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005088/// encounter a subexpression that (1) clearly does not lead to one of the
5089/// above problematic expressions (2) is something we cannot determine leads to
5090/// a problematic expression based on such local checking.
5091///
5092/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5093/// the expression that they point to. Such variables are added to the
5094/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005095///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005096/// EvalAddr processes expressions that are pointers that are used as
5097/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005098/// At the base case of the recursion is a check for the above problematic
5099/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005100///
5101/// This implementation handles:
5102///
5103/// * pointer-to-pointer casts
5104/// * implicit conversions from array references to pointers
5105/// * taking the address of fields
5106/// * arbitrary interplay between "&" and "*" operators
5107/// * pointer arithmetic from an address of a stack variable
5108/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005109static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5110 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005111 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005112 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005113
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005114 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005115 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005116 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005117 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005118 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005119
Peter Collingbourne91147592011-04-15 00:35:48 +00005120 E = E->IgnoreParens();
5121
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005122 // Our "symbolic interpreter" is just a dispatch off the currently
5123 // viewed AST node. We then recursively traverse the AST by calling
5124 // EvalAddr and EvalVal appropriately.
5125 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005126 case Stmt::DeclRefExprClass: {
5127 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5128
Richard Smith40f08eb2014-01-30 22:05:38 +00005129 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005130 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005131 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005132
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005133 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5134 // If this is a reference variable, follow through to the expression that
5135 // it points to.
5136 if (V->hasLocalStorage() &&
5137 V->getType()->isReferenceType() && V->hasInit()) {
5138 // Add the reference variable to the "trail".
5139 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005140 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005141 }
5142
Craig Topperc3ec1492014-05-26 06:22:03 +00005143 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005144 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005145
Chris Lattner934edb22007-12-28 05:31:15 +00005146 case Stmt::UnaryOperatorClass: {
5147 // The only unary operator that make sense to handle here
5148 // is AddrOf. All others don't make sense as pointers.
5149 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005150
John McCalle3027922010-08-25 11:45:40 +00005151 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005152 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005153 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005154 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005155 }
Mike Stump11289f42009-09-09 15:08:12 +00005156
Chris Lattner934edb22007-12-28 05:31:15 +00005157 case Stmt::BinaryOperatorClass: {
5158 // Handle pointer arithmetic. All other binary operators are not valid
5159 // in this context.
5160 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005161 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005162
John McCalle3027922010-08-25 11:45:40 +00005163 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005164 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005165
Chris Lattner934edb22007-12-28 05:31:15 +00005166 Expr *Base = B->getLHS();
5167
5168 // Determine which argument is the real pointer base. It could be
5169 // the RHS argument instead of the LHS.
5170 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005171
Chris Lattner934edb22007-12-28 05:31:15 +00005172 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005173 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005174 }
Steve Naroff2752a172008-09-10 19:17:48 +00005175
Chris Lattner934edb22007-12-28 05:31:15 +00005176 // For conditional operators we need to see if either the LHS or RHS are
5177 // valid DeclRefExpr*s. If one of them is valid, we return it.
5178 case Stmt::ConditionalOperatorClass: {
5179 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005180
Chris Lattner934edb22007-12-28 05:31:15 +00005181 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005182 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5183 if (Expr *LHSExpr = C->getLHS()) {
5184 // In C++, we can have a throw-expression, which has 'void' type.
5185 if (!LHSExpr->getType()->isVoidType())
5186 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005187 return LHS;
5188 }
Chris Lattner934edb22007-12-28 05:31:15 +00005189
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005190 // In C++, we can have a throw-expression, which has 'void' type.
5191 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005192 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005193
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005194 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005195 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005196
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005197 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005198 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005199 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005200 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005201
5202 case Stmt::AddrLabelExprClass:
5203 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005204
John McCall28fc7092011-11-10 05:35:25 +00005205 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005206 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5207 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005208
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005209 // For casts, we need to handle conversions from arrays to
5210 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005211 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005212 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005213 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005214 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005215 case Stmt::CXXStaticCastExprClass:
5216 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005217 case Stmt::CXXConstCastExprClass:
5218 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005219 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5220 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005221 case CK_LValueToRValue:
5222 case CK_NoOp:
5223 case CK_BaseToDerived:
5224 case CK_DerivedToBase:
5225 case CK_UncheckedDerivedToBase:
5226 case CK_Dynamic:
5227 case CK_CPointerToObjCPointerCast:
5228 case CK_BlockPointerToObjCPointerCast:
5229 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005230 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005231
5232 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005233 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005234
Richard Trieudadefde2014-07-02 04:39:38 +00005235 case CK_BitCast:
5236 if (SubExpr->getType()->isAnyPointerType() ||
5237 SubExpr->getType()->isBlockPointerType() ||
5238 SubExpr->getType()->isObjCQualifiedIdType())
5239 return EvalAddr(SubExpr, refVars, ParentDecl);
5240 else
5241 return nullptr;
5242
Eli Friedman8195ad72012-02-23 23:04:32 +00005243 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005244 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005245 }
Chris Lattner934edb22007-12-28 05:31:15 +00005246 }
Mike Stump11289f42009-09-09 15:08:12 +00005247
Douglas Gregorfe314812011-06-21 17:03:29 +00005248 case Stmt::MaterializeTemporaryExprClass:
5249 if (Expr *Result = EvalAddr(
5250 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005251 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005252 return Result;
5253
5254 return E;
5255
Chris Lattner934edb22007-12-28 05:31:15 +00005256 // Everything else: we simply don't reason about them.
5257 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005258 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005259 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005260}
Mike Stump11289f42009-09-09 15:08:12 +00005261
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005262
5263/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5264/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005265static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5266 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005267do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005268 // We should only be called for evaluating non-pointer expressions, or
5269 // expressions with a pointer type that are not used as references but instead
5270 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005271
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005272 // Our "symbolic interpreter" is just a dispatch off the currently
5273 // viewed AST node. We then recursively traverse the AST by calling
5274 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005275
5276 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005277 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005278 case Stmt::ImplicitCastExprClass: {
5279 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005280 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005281 E = IE->getSubExpr();
5282 continue;
5283 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005284 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005285 }
5286
John McCall28fc7092011-11-10 05:35:25 +00005287 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005288 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005289
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005290 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005291 // When we hit a DeclRefExpr we are looking at code that refers to a
5292 // variable's name. If it's not a reference variable we check if it has
5293 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005294 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005295
Richard Smith40f08eb2014-01-30 22:05:38 +00005296 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005297 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005298 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005299
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005300 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5301 // Check if it refers to itself, e.g. "int& i = i;".
5302 if (V == ParentDecl)
5303 return DR;
5304
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005305 if (V->hasLocalStorage()) {
5306 if (!V->getType()->isReferenceType())
5307 return DR;
5308
5309 // Reference variable, follow through to the expression that
5310 // it points to.
5311 if (V->hasInit()) {
5312 // Add the reference variable to the "trail".
5313 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005314 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005315 }
5316 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005317 }
Mike Stump11289f42009-09-09 15:08:12 +00005318
Craig Topperc3ec1492014-05-26 06:22:03 +00005319 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005320 }
Mike Stump11289f42009-09-09 15:08:12 +00005321
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005322 case Stmt::UnaryOperatorClass: {
5323 // The only unary operator that make sense to handle here
5324 // is Deref. All others don't resolve to a "name." This includes
5325 // handling all sorts of rvalues passed to a unary operator.
5326 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005327
John McCalle3027922010-08-25 11:45:40 +00005328 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005329 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005330
Craig Topperc3ec1492014-05-26 06:22:03 +00005331 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005332 }
Mike Stump11289f42009-09-09 15:08:12 +00005333
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005334 case Stmt::ArraySubscriptExprClass: {
5335 // Array subscripts are potential references to data on the stack. We
5336 // retrieve the DeclRefExpr* for the array variable if it indeed
5337 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005338 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005339 }
Mike Stump11289f42009-09-09 15:08:12 +00005340
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005341 case Stmt::ConditionalOperatorClass: {
5342 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005343 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005344 ConditionalOperator *C = cast<ConditionalOperator>(E);
5345
Anders Carlsson801c5c72007-11-30 19:04:31 +00005346 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005347 if (Expr *LHSExpr = C->getLHS()) {
5348 // In C++, we can have a throw-expression, which has 'void' type.
5349 if (!LHSExpr->getType()->isVoidType())
5350 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5351 return LHS;
5352 }
5353
5354 // In C++, we can have a throw-expression, which has 'void' type.
5355 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005356 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005357
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005358 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005359 }
Mike Stump11289f42009-09-09 15:08:12 +00005360
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005361 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005362 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005363 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005364
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005365 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005366 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005367 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005368
5369 // Check whether the member type is itself a reference, in which case
5370 // we're not going to refer to the member, but to what the member refers to.
5371 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005372 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005373
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005374 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005375 }
Mike Stump11289f42009-09-09 15:08:12 +00005376
Douglas Gregorfe314812011-06-21 17:03:29 +00005377 case Stmt::MaterializeTemporaryExprClass:
5378 if (Expr *Result = EvalVal(
5379 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005380 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005381 return Result;
5382
5383 return E;
5384
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005385 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005386 // Check that we don't return or take the address of a reference to a
5387 // temporary. This is only useful in C++.
5388 if (!E->isTypeDependent() && E->isRValue())
5389 return E;
5390
5391 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005392 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005393 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005394} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005395}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005396
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005397void
5398Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5399 SourceLocation ReturnLoc,
5400 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005401 const AttrVec *Attrs,
5402 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005403 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5404
5405 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005406 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5407 CheckNonNullExpr(*this, RetValExp))
5408 Diag(ReturnLoc, diag::warn_null_ret)
5409 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005410
5411 // C++11 [basic.stc.dynamic.allocation]p4:
5412 // If an allocation function declared with a non-throwing
5413 // exception-specification fails to allocate storage, it shall return
5414 // a null pointer. Any other allocation function that fails to allocate
5415 // storage shall indicate failure only by throwing an exception [...]
5416 if (FD) {
5417 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5418 if (Op == OO_New || Op == OO_Array_New) {
5419 const FunctionProtoType *Proto
5420 = FD->getType()->castAs<FunctionProtoType>();
5421 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5422 CheckNonNullExpr(*this, RetValExp))
5423 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5424 << FD << getLangOpts().CPlusPlus11;
5425 }
5426 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005427}
5428
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005429//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5430
5431/// Check for comparisons of floating point operands using != and ==.
5432/// Issue a warning if these are no self-comparisons, as they are not likely
5433/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005434void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005435 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5436 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005437
5438 // Special case: check for x == x (which is OK).
5439 // Do not emit warnings for such cases.
5440 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5441 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5442 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005443 return;
Mike Stump11289f42009-09-09 15:08:12 +00005444
5445
Ted Kremenekeda40e22007-11-29 00:59:04 +00005446 // Special case: check for comparisons against literals that can be exactly
5447 // represented by APFloat. In such cases, do not emit a warning. This
5448 // is a heuristic: often comparison against such literals are used to
5449 // detect if a value in a variable has not changed. This clearly can
5450 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005451 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5452 if (FLL->isExact())
5453 return;
5454 } else
5455 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5456 if (FLR->isExact())
5457 return;
Mike Stump11289f42009-09-09 15:08:12 +00005458
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005459 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005460 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005461 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005462 return;
Mike Stump11289f42009-09-09 15:08:12 +00005463
David Blaikie1f4ff152012-07-16 20:47:22 +00005464 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005465 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005466 return;
Mike Stump11289f42009-09-09 15:08:12 +00005467
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005468 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005469 Diag(Loc, diag::warn_floatingpoint_eq)
5470 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005471}
John McCallca01b222010-01-04 23:21:16 +00005472
John McCall70aa5392010-01-06 05:24:50 +00005473//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5474//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005475
John McCall70aa5392010-01-06 05:24:50 +00005476namespace {
John McCallca01b222010-01-04 23:21:16 +00005477
John McCall70aa5392010-01-06 05:24:50 +00005478/// Structure recording the 'active' range of an integer-valued
5479/// expression.
5480struct IntRange {
5481 /// The number of bits active in the int.
5482 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005483
John McCall70aa5392010-01-06 05:24:50 +00005484 /// True if the int is known not to have negative values.
5485 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005486
John McCall70aa5392010-01-06 05:24:50 +00005487 IntRange(unsigned Width, bool NonNegative)
5488 : Width(Width), NonNegative(NonNegative)
5489 {}
John McCallca01b222010-01-04 23:21:16 +00005490
John McCall817d4af2010-11-10 23:38:19 +00005491 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005492 static IntRange forBoolType() {
5493 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005494 }
5495
John McCall817d4af2010-11-10 23:38:19 +00005496 /// Returns the range of an opaque value of the given integral type.
5497 static IntRange forValueOfType(ASTContext &C, QualType T) {
5498 return forValueOfCanonicalType(C,
5499 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005500 }
5501
John McCall817d4af2010-11-10 23:38:19 +00005502 /// Returns the range of an opaque value of a canonical integral type.
5503 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005504 assert(T->isCanonicalUnqualified());
5505
5506 if (const VectorType *VT = dyn_cast<VectorType>(T))
5507 T = VT->getElementType().getTypePtr();
5508 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5509 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005510 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5511 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005512
David Majnemer6a426652013-06-07 22:07:20 +00005513 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005514 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005515 EnumDecl *Enum = ET->getDecl();
5516 if (!Enum->isCompleteDefinition())
5517 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005518
David Majnemer6a426652013-06-07 22:07:20 +00005519 unsigned NumPositive = Enum->getNumPositiveBits();
5520 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005521
David Majnemer6a426652013-06-07 22:07:20 +00005522 if (NumNegative == 0)
5523 return IntRange(NumPositive, true/*NonNegative*/);
5524 else
5525 return IntRange(std::max(NumPositive + 1, NumNegative),
5526 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005527 }
John McCall70aa5392010-01-06 05:24:50 +00005528
5529 const BuiltinType *BT = cast<BuiltinType>(T);
5530 assert(BT->isInteger());
5531
5532 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5533 }
5534
John McCall817d4af2010-11-10 23:38:19 +00005535 /// Returns the "target" range of a canonical integral type, i.e.
5536 /// the range of values expressible in the type.
5537 ///
5538 /// This matches forValueOfCanonicalType except that enums have the
5539 /// full range of their type, not the range of their enumerators.
5540 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5541 assert(T->isCanonicalUnqualified());
5542
5543 if (const VectorType *VT = dyn_cast<VectorType>(T))
5544 T = VT->getElementType().getTypePtr();
5545 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5546 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005547 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5548 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005549 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005550 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005551
5552 const BuiltinType *BT = cast<BuiltinType>(T);
5553 assert(BT->isInteger());
5554
5555 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5556 }
5557
5558 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005559 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005560 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005561 L.NonNegative && R.NonNegative);
5562 }
5563
John McCall817d4af2010-11-10 23:38:19 +00005564 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005565 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005566 return IntRange(std::min(L.Width, R.Width),
5567 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005568 }
5569};
5570
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005571static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5572 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005573 if (value.isSigned() && value.isNegative())
5574 return IntRange(value.getMinSignedBits(), false);
5575
5576 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005577 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005578
5579 // isNonNegative() just checks the sign bit without considering
5580 // signedness.
5581 return IntRange(value.getActiveBits(), true);
5582}
5583
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005584static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5585 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005586 if (result.isInt())
5587 return GetValueRange(C, result.getInt(), MaxWidth);
5588
5589 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005590 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5591 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5592 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5593 R = IntRange::join(R, El);
5594 }
John McCall70aa5392010-01-06 05:24:50 +00005595 return R;
5596 }
5597
5598 if (result.isComplexInt()) {
5599 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5600 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5601 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005602 }
5603
5604 // This can happen with lossless casts to intptr_t of "based" lvalues.
5605 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005606 // FIXME: The only reason we need to pass the type in here is to get
5607 // the sign right on this one case. It would be nice if APValue
5608 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005609 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005610 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005611}
John McCall70aa5392010-01-06 05:24:50 +00005612
Eli Friedmane6d33952013-07-08 20:20:06 +00005613static QualType GetExprType(Expr *E) {
5614 QualType Ty = E->getType();
5615 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5616 Ty = AtomicRHS->getValueType();
5617 return Ty;
5618}
5619
John McCall70aa5392010-01-06 05:24:50 +00005620/// Pseudo-evaluate the given integer expression, estimating the
5621/// range of values it might take.
5622///
5623/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005624static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005625 E = E->IgnoreParens();
5626
5627 // Try a full evaluation first.
5628 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005629 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005630 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005631
5632 // I think we only want to look through implicit casts here; if the
5633 // user has an explicit widening cast, we should treat the value as
5634 // being of the new, wider type.
5635 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005636 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005637 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5638
Eli Friedmane6d33952013-07-08 20:20:06 +00005639 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005640
John McCalle3027922010-08-25 11:45:40 +00005641 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005642
John McCall70aa5392010-01-06 05:24:50 +00005643 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005644 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005645 return OutputTypeRange;
5646
5647 IntRange SubRange
5648 = GetExprRange(C, CE->getSubExpr(),
5649 std::min(MaxWidth, OutputTypeRange.Width));
5650
5651 // Bail out if the subexpr's range is as wide as the cast type.
5652 if (SubRange.Width >= OutputTypeRange.Width)
5653 return OutputTypeRange;
5654
5655 // Otherwise, we take the smaller width, and we're non-negative if
5656 // either the output type or the subexpr is.
5657 return IntRange(SubRange.Width,
5658 SubRange.NonNegative || OutputTypeRange.NonNegative);
5659 }
5660
5661 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5662 // If we can fold the condition, just take that operand.
5663 bool CondResult;
5664 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5665 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5666 : CO->getFalseExpr(),
5667 MaxWidth);
5668
5669 // Otherwise, conservatively merge.
5670 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5671 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5672 return IntRange::join(L, R);
5673 }
5674
5675 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5676 switch (BO->getOpcode()) {
5677
5678 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005679 case BO_LAnd:
5680 case BO_LOr:
5681 case BO_LT:
5682 case BO_GT:
5683 case BO_LE:
5684 case BO_GE:
5685 case BO_EQ:
5686 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005687 return IntRange::forBoolType();
5688
John McCallc3688382011-07-13 06:35:24 +00005689 // The type of the assignments is the type of the LHS, so the RHS
5690 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005691 case BO_MulAssign:
5692 case BO_DivAssign:
5693 case BO_RemAssign:
5694 case BO_AddAssign:
5695 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005696 case BO_XorAssign:
5697 case BO_OrAssign:
5698 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005699 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005700
John McCallc3688382011-07-13 06:35:24 +00005701 // Simple assignments just pass through the RHS, which will have
5702 // been coerced to the LHS type.
5703 case BO_Assign:
5704 // TODO: bitfields?
5705 return GetExprRange(C, BO->getRHS(), MaxWidth);
5706
John McCall70aa5392010-01-06 05:24:50 +00005707 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005708 case BO_PtrMemD:
5709 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005710 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005711
John McCall2ce81ad2010-01-06 22:07:33 +00005712 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005713 case BO_And:
5714 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005715 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5716 GetExprRange(C, BO->getRHS(), MaxWidth));
5717
John McCall70aa5392010-01-06 05:24:50 +00005718 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005719 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005720 // ...except that we want to treat '1 << (blah)' as logically
5721 // positive. It's an important idiom.
5722 if (IntegerLiteral *I
5723 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5724 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005725 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005726 return IntRange(R.Width, /*NonNegative*/ true);
5727 }
5728 }
5729 // fallthrough
5730
John McCalle3027922010-08-25 11:45:40 +00005731 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005732 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005733
John McCall2ce81ad2010-01-06 22:07:33 +00005734 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005735 case BO_Shr:
5736 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005737 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5738
5739 // If the shift amount is a positive constant, drop the width by
5740 // that much.
5741 llvm::APSInt shift;
5742 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5743 shift.isNonNegative()) {
5744 unsigned zext = shift.getZExtValue();
5745 if (zext >= L.Width)
5746 L.Width = (L.NonNegative ? 0 : 1);
5747 else
5748 L.Width -= zext;
5749 }
5750
5751 return L;
5752 }
5753
5754 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005755 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005756 return GetExprRange(C, BO->getRHS(), MaxWidth);
5757
John McCall2ce81ad2010-01-06 22:07:33 +00005758 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005759 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005760 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005761 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005762 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005763
John McCall51431812011-07-14 22:39:48 +00005764 // The width of a division result is mostly determined by the size
5765 // of the LHS.
5766 case BO_Div: {
5767 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005768 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005769 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5770
5771 // If the divisor is constant, use that.
5772 llvm::APSInt divisor;
5773 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5774 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5775 if (log2 >= L.Width)
5776 L.Width = (L.NonNegative ? 0 : 1);
5777 else
5778 L.Width = std::min(L.Width - log2, MaxWidth);
5779 return L;
5780 }
5781
5782 // Otherwise, just use the LHS's width.
5783 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5784 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5785 }
5786
5787 // The result of a remainder can't be larger than the result of
5788 // either side.
5789 case BO_Rem: {
5790 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005791 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005792 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5793 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5794
5795 IntRange meet = IntRange::meet(L, R);
5796 meet.Width = std::min(meet.Width, MaxWidth);
5797 return meet;
5798 }
5799
5800 // The default behavior is okay for these.
5801 case BO_Mul:
5802 case BO_Add:
5803 case BO_Xor:
5804 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005805 break;
5806 }
5807
John McCall51431812011-07-14 22:39:48 +00005808 // The default case is to treat the operation as if it were closed
5809 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005810 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5811 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5812 return IntRange::join(L, R);
5813 }
5814
5815 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5816 switch (UO->getOpcode()) {
5817 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005818 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005819 return IntRange::forBoolType();
5820
5821 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005822 case UO_Deref:
5823 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005824 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005825
5826 default:
5827 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5828 }
5829 }
5830
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005831 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5832 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5833
John McCalld25db7e2013-05-06 21:39:12 +00005834 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005835 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005836 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005837
Eli Friedmane6d33952013-07-08 20:20:06 +00005838 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005839}
John McCall263a48b2010-01-04 23:31:57 +00005840
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005841static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005842 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005843}
5844
John McCall263a48b2010-01-04 23:31:57 +00005845/// Checks whether the given value, which currently has the given
5846/// source semantics, has the same value when coerced through the
5847/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005848static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5849 const llvm::fltSemantics &Src,
5850 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005851 llvm::APFloat truncated = value;
5852
5853 bool ignored;
5854 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5855 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5856
5857 return truncated.bitwiseIsEqual(value);
5858}
5859
5860/// Checks whether the given value, which currently has the given
5861/// source semantics, has the same value when coerced through the
5862/// target semantics.
5863///
5864/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005865static bool IsSameFloatAfterCast(const APValue &value,
5866 const llvm::fltSemantics &Src,
5867 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005868 if (value.isFloat())
5869 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5870
5871 if (value.isVector()) {
5872 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5873 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5874 return false;
5875 return true;
5876 }
5877
5878 assert(value.isComplexFloat());
5879 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5880 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5881}
5882
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005883static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005884
Ted Kremenek6274be42010-09-23 21:43:44 +00005885static bool IsZero(Sema &S, Expr *E) {
5886 // Suppress cases where we are comparing against an enum constant.
5887 if (const DeclRefExpr *DR =
5888 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5889 if (isa<EnumConstantDecl>(DR->getDecl()))
5890 return false;
5891
5892 // Suppress cases where the '0' value is expanded from a macro.
5893 if (E->getLocStart().isMacroID())
5894 return false;
5895
John McCallcc7e5bf2010-05-06 08:58:33 +00005896 llvm::APSInt Value;
5897 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5898}
5899
John McCall2551c1b2010-10-06 00:25:24 +00005900static bool HasEnumType(Expr *E) {
5901 // Strip off implicit integral promotions.
5902 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005903 if (ICE->getCastKind() != CK_IntegralCast &&
5904 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005905 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005906 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005907 }
5908
5909 return E->getType()->isEnumeralType();
5910}
5911
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005912static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005913 // Disable warning in template instantiations.
5914 if (!S.ActiveTemplateInstantiations.empty())
5915 return;
5916
John McCalle3027922010-08-25 11:45:40 +00005917 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005918 if (E->isValueDependent())
5919 return;
5920
John McCalle3027922010-08-25 11:45:40 +00005921 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005922 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005923 << "< 0" << "false" << HasEnumType(E->getLHS())
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_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005926 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005927 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005928 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005929 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005930 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005931 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005932 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005933 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005934 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005935 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005936 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5937 }
5938}
5939
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005940static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005941 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005942 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005943 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005944 // Disable warning in template instantiations.
5945 if (!S.ActiveTemplateInstantiations.empty())
5946 return;
5947
Richard Trieu0f097742014-04-04 04:13:47 +00005948 // TODO: Investigate using GetExprRange() to get tighter bounds
5949 // on the bit ranges.
5950 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005951 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5952 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005953 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5954 unsigned OtherWidth = OtherRange.Width;
5955
5956 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5957
Richard Trieu560910c2012-11-14 22:50:24 +00005958 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005959 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005960 return;
5961
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005962 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005963 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005964
Richard Trieu0f097742014-04-04 04:13:47 +00005965 // Used for diagnostic printout.
5966 enum {
5967 LiteralConstant = 0,
5968 CXXBoolLiteralTrue,
5969 CXXBoolLiteralFalse
5970 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005971
Richard Trieu0f097742014-04-04 04:13:47 +00005972 if (!OtherIsBooleanType) {
5973 QualType ConstantT = Constant->getType();
5974 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005975
Richard Trieu0f097742014-04-04 04:13:47 +00005976 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5977 return;
5978 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5979 "comparison with non-integer type");
5980
5981 bool ConstantSigned = ConstantT->isSignedIntegerType();
5982 bool CommonSigned = CommonT->isSignedIntegerType();
5983
5984 bool EqualityOnly = false;
5985
5986 if (CommonSigned) {
5987 // The common type is signed, therefore no signed to unsigned conversion.
5988 if (!OtherRange.NonNegative) {
5989 // Check that the constant is representable in type OtherT.
5990 if (ConstantSigned) {
5991 if (OtherWidth >= Value.getMinSignedBits())
5992 return;
5993 } else { // !ConstantSigned
5994 if (OtherWidth >= Value.getActiveBits() + 1)
5995 return;
5996 }
5997 } else { // !OtherSigned
5998 // Check that the constant is representable in type OtherT.
5999 // Negative values are out of range.
6000 if (ConstantSigned) {
6001 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6002 return;
6003 } else { // !ConstantSigned
6004 if (OtherWidth >= Value.getActiveBits())
6005 return;
6006 }
Richard Trieu560910c2012-11-14 22:50:24 +00006007 }
Richard Trieu0f097742014-04-04 04:13:47 +00006008 } else { // !CommonSigned
6009 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006010 if (OtherWidth >= Value.getActiveBits())
6011 return;
Craig Toppercf360162014-06-18 05:13:11 +00006012 } else { // OtherSigned
6013 assert(!ConstantSigned &&
6014 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006015 // Check to see if the constant is representable in OtherT.
6016 if (OtherWidth > Value.getActiveBits())
6017 return;
6018 // Check to see if the constant is equivalent to a negative value
6019 // cast to CommonT.
6020 if (S.Context.getIntWidth(ConstantT) ==
6021 S.Context.getIntWidth(CommonT) &&
6022 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6023 return;
6024 // The constant value rests between values that OtherT can represent
6025 // after conversion. Relational comparison still works, but equality
6026 // comparisons will be tautological.
6027 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006028 }
6029 }
Richard Trieu0f097742014-04-04 04:13:47 +00006030
6031 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6032
6033 if (op == BO_EQ || op == BO_NE) {
6034 IsTrue = op == BO_NE;
6035 } else if (EqualityOnly) {
6036 return;
6037 } else if (RhsConstant) {
6038 if (op == BO_GT || op == BO_GE)
6039 IsTrue = !PositiveConstant;
6040 else // op == BO_LT || op == BO_LE
6041 IsTrue = PositiveConstant;
6042 } else {
6043 if (op == BO_LT || op == BO_LE)
6044 IsTrue = !PositiveConstant;
6045 else // op == BO_GT || op == BO_GE
6046 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006047 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006048 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006049 // Other isKnownToHaveBooleanValue
6050 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6051 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6052 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6053
6054 static const struct LinkedConditions {
6055 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6056 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6057 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6058 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6059 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6060 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6061
6062 } TruthTable = {
6063 // Constant on LHS. | Constant on RHS. |
6064 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6065 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6066 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6067 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6068 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6069 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6070 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6071 };
6072
6073 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6074
6075 enum ConstantValue ConstVal = Zero;
6076 if (Value.isUnsigned() || Value.isNonNegative()) {
6077 if (Value == 0) {
6078 LiteralOrBoolConstant =
6079 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6080 ConstVal = Zero;
6081 } else if (Value == 1) {
6082 LiteralOrBoolConstant =
6083 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6084 ConstVal = One;
6085 } else {
6086 LiteralOrBoolConstant = LiteralConstant;
6087 ConstVal = GT_One;
6088 }
6089 } else {
6090 ConstVal = LT_Zero;
6091 }
6092
6093 CompareBoolWithConstantResult CmpRes;
6094
6095 switch (op) {
6096 case BO_LT:
6097 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6098 break;
6099 case BO_GT:
6100 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6101 break;
6102 case BO_LE:
6103 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6104 break;
6105 case BO_GE:
6106 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6107 break;
6108 case BO_EQ:
6109 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6110 break;
6111 case BO_NE:
6112 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6113 break;
6114 default:
6115 CmpRes = Unkwn;
6116 break;
6117 }
6118
6119 if (CmpRes == AFals) {
6120 IsTrue = false;
6121 } else if (CmpRes == ATrue) {
6122 IsTrue = true;
6123 } else {
6124 return;
6125 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006126 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006127
6128 // If this is a comparison to an enum constant, include that
6129 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006130 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006131 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6132 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6133
6134 SmallString<64> PrettySourceValue;
6135 llvm::raw_svector_ostream OS(PrettySourceValue);
6136 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006137 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006138 else
6139 OS << Value;
6140
Richard Trieu0f097742014-04-04 04:13:47 +00006141 S.DiagRuntimeBehavior(
6142 E->getOperatorLoc(), E,
6143 S.PDiag(diag::warn_out_of_range_compare)
6144 << OS.str() << LiteralOrBoolConstant
6145 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6146 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006147}
6148
John McCallcc7e5bf2010-05-06 08:58:33 +00006149/// Analyze the operands of the given comparison. Implements the
6150/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006151static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006152 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6153 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006154}
John McCall263a48b2010-01-04 23:31:57 +00006155
John McCallca01b222010-01-04 23:21:16 +00006156/// \brief Implements -Wsign-compare.
6157///
Richard Trieu82402a02011-09-15 21:56:47 +00006158/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006159static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006160 // The type the comparison is being performed in.
6161 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006162
6163 // Only analyze comparison operators where both sides have been converted to
6164 // the same type.
6165 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6166 return AnalyzeImpConvsInComparison(S, E);
6167
6168 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006169 if (E->isValueDependent())
6170 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006171
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006172 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6173 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006174
6175 bool IsComparisonConstant = false;
6176
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006177 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006178 // of 'true' or 'false'.
6179 if (T->isIntegralType(S.Context)) {
6180 llvm::APSInt RHSValue;
6181 bool IsRHSIntegralLiteral =
6182 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6183 llvm::APSInt LHSValue;
6184 bool IsLHSIntegralLiteral =
6185 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6186 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6187 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6188 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6189 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6190 else
6191 IsComparisonConstant =
6192 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006193 } else if (!T->hasUnsignedIntegerRepresentation())
6194 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006195
John McCallcc7e5bf2010-05-06 08:58:33 +00006196 // We don't do anything special if this isn't an unsigned integral
6197 // comparison: we're only interested in integral comparisons, and
6198 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006199 //
6200 // We also don't care about value-dependent expressions or expressions
6201 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006202 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006203 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006204
John McCallcc7e5bf2010-05-06 08:58:33 +00006205 // Check to see if one of the (unmodified) operands is of different
6206 // signedness.
6207 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006208 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6209 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006210 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006211 signedOperand = LHS;
6212 unsignedOperand = RHS;
6213 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6214 signedOperand = RHS;
6215 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006216 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006217 CheckTrivialUnsignedComparison(S, E);
6218 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006219 }
6220
John McCallcc7e5bf2010-05-06 08:58:33 +00006221 // Otherwise, calculate the effective range of the signed operand.
6222 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006223
John McCallcc7e5bf2010-05-06 08:58:33 +00006224 // Go ahead and analyze implicit conversions in the operands. Note
6225 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006226 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6227 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006228
John McCallcc7e5bf2010-05-06 08:58:33 +00006229 // If the signed range is non-negative, -Wsign-compare won't fire,
6230 // but we should still check for comparisons which are always true
6231 // or false.
6232 if (signedRange.NonNegative)
6233 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006234
6235 // For (in)equality comparisons, if the unsigned operand is a
6236 // constant which cannot collide with a overflowed signed operand,
6237 // then reinterpreting the signed operand as unsigned will not
6238 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006239 if (E->isEqualityOp()) {
6240 unsigned comparisonWidth = S.Context.getIntWidth(T);
6241 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006242
John McCallcc7e5bf2010-05-06 08:58:33 +00006243 // We should never be unable to prove that the unsigned operand is
6244 // non-negative.
6245 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6246
6247 if (unsignedRange.Width < comparisonWidth)
6248 return;
6249 }
6250
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006251 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6252 S.PDiag(diag::warn_mixed_sign_comparison)
6253 << LHS->getType() << RHS->getType()
6254 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006255}
6256
John McCall1f425642010-11-11 03:21:53 +00006257/// Analyzes an attempt to assign the given value to a bitfield.
6258///
6259/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006260static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6261 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006262 assert(Bitfield->isBitField());
6263 if (Bitfield->isInvalidDecl())
6264 return false;
6265
John McCalldeebbcf2010-11-11 05:33:51 +00006266 // White-list bool bitfields.
6267 if (Bitfield->getType()->isBooleanType())
6268 return false;
6269
Douglas Gregor789adec2011-02-04 13:09:01 +00006270 // Ignore value- or type-dependent expressions.
6271 if (Bitfield->getBitWidth()->isValueDependent() ||
6272 Bitfield->getBitWidth()->isTypeDependent() ||
6273 Init->isValueDependent() ||
6274 Init->isTypeDependent())
6275 return false;
6276
John McCall1f425642010-11-11 03:21:53 +00006277 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6278
Richard Smith5fab0c92011-12-28 19:48:30 +00006279 llvm::APSInt Value;
6280 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006281 return false;
6282
John McCall1f425642010-11-11 03:21:53 +00006283 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006284 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006285
6286 if (OriginalWidth <= FieldWidth)
6287 return false;
6288
Eli Friedmanc267a322012-01-26 23:11:39 +00006289 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006290 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006291 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006292
Eli Friedmanc267a322012-01-26 23:11:39 +00006293 // Check whether the stored value is equal to the original value.
6294 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006295 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006296 return false;
6297
Eli Friedmanc267a322012-01-26 23:11:39 +00006298 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006299 // therefore don't strictly fit into a signed bitfield of width 1.
6300 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006301 return false;
6302
John McCall1f425642010-11-11 03:21:53 +00006303 std::string PrettyValue = Value.toString(10);
6304 std::string PrettyTrunc = TruncatedValue.toString(10);
6305
6306 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6307 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6308 << Init->getSourceRange();
6309
6310 return true;
6311}
6312
John McCalld2a53122010-11-09 23:24:47 +00006313/// Analyze the given simple or compound assignment for warning-worthy
6314/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006315static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006316 // Just recurse on the LHS.
6317 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6318
6319 // We want to recurse on the RHS as normal unless we're assigning to
6320 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006321 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006322 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006323 E->getOperatorLoc())) {
6324 // Recurse, ignoring any implicit conversions on the RHS.
6325 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6326 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006327 }
6328 }
6329
6330 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6331}
6332
John McCall263a48b2010-01-04 23:31:57 +00006333/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006334static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006335 SourceLocation CContext, unsigned diag,
6336 bool pruneControlFlow = false) {
6337 if (pruneControlFlow) {
6338 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6339 S.PDiag(diag)
6340 << SourceType << T << E->getSourceRange()
6341 << SourceRange(CContext));
6342 return;
6343 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006344 S.Diag(E->getExprLoc(), diag)
6345 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6346}
6347
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006348/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006349static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006350 SourceLocation CContext, unsigned diag,
6351 bool pruneControlFlow = false) {
6352 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006353}
6354
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006355/// Diagnose an implicit cast from a literal expression. Does not warn when the
6356/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006357void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6358 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006359 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006360 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006361 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006362 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6363 T->hasUnsignedIntegerRepresentation());
6364 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006365 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006366 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006367 return;
6368
Eli Friedman07185912013-08-29 23:44:43 +00006369 // FIXME: Force the precision of the source value down so we don't print
6370 // digits which are usually useless (we don't really care here if we
6371 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6372 // would automatically print the shortest representation, but it's a bit
6373 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006374 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006375 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6376 precision = (precision * 59 + 195) / 196;
6377 Value.toString(PrettySourceValue, precision);
6378
David Blaikie9b88cc02012-05-15 17:18:27 +00006379 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006380 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6381 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6382 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006383 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006384
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006385 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006386 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6387 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006388}
6389
John McCall18a2c2c2010-11-09 22:22:12 +00006390std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6391 if (!Range.Width) return "0";
6392
6393 llvm::APSInt ValueInRange = Value;
6394 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006395 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006396 return ValueInRange.toString(10);
6397}
6398
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006399static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6400 if (!isa<ImplicitCastExpr>(Ex))
6401 return false;
6402
6403 Expr *InnerE = Ex->IgnoreParenImpCasts();
6404 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6405 const Type *Source =
6406 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6407 if (Target->isDependentType())
6408 return false;
6409
6410 const BuiltinType *FloatCandidateBT =
6411 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6412 const Type *BoolCandidateType = ToBool ? Target : Source;
6413
6414 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6415 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6416}
6417
6418void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6419 SourceLocation CC) {
6420 unsigned NumArgs = TheCall->getNumArgs();
6421 for (unsigned i = 0; i < NumArgs; ++i) {
6422 Expr *CurrA = TheCall->getArg(i);
6423 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6424 continue;
6425
6426 bool IsSwapped = ((i > 0) &&
6427 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6428 IsSwapped |= ((i < (NumArgs - 1)) &&
6429 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6430 if (IsSwapped) {
6431 // Warn on this floating-point to bool conversion.
6432 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6433 CurrA->getType(), CC,
6434 diag::warn_impcast_floating_point_to_bool);
6435 }
6436 }
6437}
6438
Richard Trieu5b993502014-10-15 03:42:06 +00006439static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6440 SourceLocation CC) {
6441 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6442 E->getExprLoc()))
6443 return;
6444
6445 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6446 const Expr::NullPointerConstantKind NullKind =
6447 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6448 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6449 return;
6450
6451 // Return if target type is a safe conversion.
6452 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6453 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6454 return;
6455
6456 SourceLocation Loc = E->getSourceRange().getBegin();
6457
6458 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6459 if (NullKind == Expr::NPCK_GNUNull) {
6460 if (Loc.isMacroID())
6461 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6462 }
6463
6464 // Only warn if the null and context location are in the same macro expansion.
6465 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6466 return;
6467
6468 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6469 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6470 << FixItHint::CreateReplacement(Loc,
6471 S.getFixItZeroLiteralForType(T, Loc));
6472}
6473
John McCallcc7e5bf2010-05-06 08:58:33 +00006474void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006475 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006476 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006477
John McCallcc7e5bf2010-05-06 08:58:33 +00006478 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6479 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6480 if (Source == Target) return;
6481 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006482
Chandler Carruthc22845a2011-07-26 05:40:03 +00006483 // If the conversion context location is invalid don't complain. We also
6484 // don't want to emit a warning if the issue occurs from the expansion of
6485 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6486 // delay this check as long as possible. Once we detect we are in that
6487 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006488 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006489 return;
6490
Richard Trieu021baa32011-09-23 20:10:00 +00006491 // Diagnose implicit casts to bool.
6492 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6493 if (isa<StringLiteral>(E))
6494 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006495 // and expressions, for instance, assert(0 && "error here"), are
6496 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006497 return DiagnoseImpCast(S, E, T, CC,
6498 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006499 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6500 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6501 // This covers the literal expressions that evaluate to Objective-C
6502 // objects.
6503 return DiagnoseImpCast(S, E, T, CC,
6504 diag::warn_impcast_objective_c_literal_to_bool);
6505 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006506 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6507 // Warn on pointer to bool conversion that is always true.
6508 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6509 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006510 }
Richard Trieu021baa32011-09-23 20:10:00 +00006511 }
John McCall263a48b2010-01-04 23:31:57 +00006512
6513 // Strip vector types.
6514 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006515 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006516 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006517 return;
John McCallacf0ee52010-10-08 02:01:28 +00006518 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006519 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006520
6521 // If the vector cast is cast between two vectors of the same size, it is
6522 // a bitcast, not a conversion.
6523 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6524 return;
John McCall263a48b2010-01-04 23:31:57 +00006525
6526 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6527 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6528 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006529 if (auto VecTy = dyn_cast<VectorType>(Target))
6530 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006531
6532 // Strip complex types.
6533 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006534 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006535 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006536 return;
6537
John McCallacf0ee52010-10-08 02:01:28 +00006538 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006539 }
John McCall263a48b2010-01-04 23:31:57 +00006540
6541 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6542 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6543 }
6544
6545 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6546 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6547
6548 // If the source is floating point...
6549 if (SourceBT && SourceBT->isFloatingPoint()) {
6550 // ...and the target is floating point...
6551 if (TargetBT && TargetBT->isFloatingPoint()) {
6552 // ...then warn if we're dropping FP rank.
6553
6554 // Builtin FP kinds are ordered by increasing FP rank.
6555 if (SourceBT->getKind() > TargetBT->getKind()) {
6556 // Don't warn about float constants that are precisely
6557 // representable in the target type.
6558 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006559 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006560 // Value might be a float, a float vector, or a float complex.
6561 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006562 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6563 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006564 return;
6565 }
6566
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006567 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006568 return;
6569
John McCallacf0ee52010-10-08 02:01:28 +00006570 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006571 }
6572 return;
6573 }
6574
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006575 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006576 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006577 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006578 return;
6579
Chandler Carruth22c7a792011-02-17 11:05:49 +00006580 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006581 // We also want to warn on, e.g., "int i = -1.234"
6582 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6583 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6584 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6585
Chandler Carruth016ef402011-04-10 08:36:24 +00006586 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6587 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006588 } else {
6589 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6590 }
6591 }
John McCall263a48b2010-01-04 23:31:57 +00006592
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006593 // If the target is bool, warn if expr is a function or method call.
6594 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6595 isa<CallExpr>(E)) {
6596 // Check last argument of function call to see if it is an
6597 // implicit cast from a type matching the type the result
6598 // is being cast to.
6599 CallExpr *CEx = cast<CallExpr>(E);
6600 unsigned NumArgs = CEx->getNumArgs();
6601 if (NumArgs > 0) {
6602 Expr *LastA = CEx->getArg(NumArgs - 1);
6603 Expr *InnerE = LastA->IgnoreParenImpCasts();
6604 const Type *InnerType =
6605 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6606 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6607 // Warn on this floating-point to bool conversion
6608 DiagnoseImpCast(S, E, T, CC,
6609 diag::warn_impcast_floating_point_to_bool);
6610 }
6611 }
6612 }
John McCall263a48b2010-01-04 23:31:57 +00006613 return;
6614 }
6615
Richard Trieu5b993502014-10-15 03:42:06 +00006616 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006617
David Blaikie9366d2b2012-06-19 21:19:06 +00006618 if (!Source->isIntegerType() || !Target->isIntegerType())
6619 return;
6620
David Blaikie7555b6a2012-05-15 16:56:36 +00006621 // TODO: remove this early return once the false positives for constant->bool
6622 // in templates, macros, etc, are reduced or removed.
6623 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6624 return;
6625
John McCallcc7e5bf2010-05-06 08:58:33 +00006626 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006627 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006628
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006629 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006630 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006631 // TODO: this should happen for bitfield stores, too.
6632 llvm::APSInt Value(32);
6633 if (E->isIntegerConstantExpr(Value, S.Context)) {
6634 if (S.SourceMgr.isInSystemMacro(CC))
6635 return;
6636
John McCall18a2c2c2010-11-09 22:22:12 +00006637 std::string PrettySourceValue = Value.toString(10);
6638 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006639
Ted Kremenek33ba9952011-10-22 02:37:33 +00006640 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6641 S.PDiag(diag::warn_impcast_integer_precision_constant)
6642 << PrettySourceValue << PrettyTargetValue
6643 << E->getType() << T << E->getSourceRange()
6644 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006645 return;
6646 }
6647
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006648 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6649 if (S.SourceMgr.isInSystemMacro(CC))
6650 return;
6651
David Blaikie9455da02012-04-12 22:40:54 +00006652 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006653 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6654 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006655 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006656 }
6657
6658 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6659 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6660 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006661
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006662 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006663 return;
6664
John McCallcc7e5bf2010-05-06 08:58:33 +00006665 unsigned DiagID = diag::warn_impcast_integer_sign;
6666
6667 // Traditionally, gcc has warned about this under -Wsign-compare.
6668 // We also want to warn about it in -Wconversion.
6669 // So if -Wconversion is off, use a completely identical diagnostic
6670 // in the sign-compare group.
6671 // The conditional-checking code will
6672 if (ICContext) {
6673 DiagID = diag::warn_impcast_integer_sign_conditional;
6674 *ICContext = true;
6675 }
6676
John McCallacf0ee52010-10-08 02:01:28 +00006677 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006678 }
6679
Douglas Gregora78f1932011-02-22 02:45:07 +00006680 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006681 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6682 // type, to give us better diagnostics.
6683 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006684 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006685 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6686 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6687 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6688 SourceType = S.Context.getTypeDeclType(Enum);
6689 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6690 }
6691 }
6692
Douglas Gregora78f1932011-02-22 02:45:07 +00006693 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6694 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006695 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6696 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006697 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006698 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006699 return;
6700
Douglas Gregor364f7db2011-03-12 00:14:31 +00006701 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006702 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006703 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006704
John McCall263a48b2010-01-04 23:31:57 +00006705 return;
6706}
6707
David Blaikie18e9ac72012-05-15 21:57:38 +00006708void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6709 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006710
6711void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006712 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006713 E = E->IgnoreParenImpCasts();
6714
6715 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006716 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006717
John McCallacf0ee52010-10-08 02:01:28 +00006718 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006719 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006720 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006721 return;
6722}
6723
David Blaikie18e9ac72012-05-15 21:57:38 +00006724void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6725 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006726 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006727
6728 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006729 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6730 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006731
6732 // If -Wconversion would have warned about either of the candidates
6733 // for a signedness conversion to the context type...
6734 if (!Suspicious) return;
6735
6736 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006737 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006738 return;
6739
John McCallcc7e5bf2010-05-06 08:58:33 +00006740 // ...then check whether it would have warned about either of the
6741 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006742 if (E->getType() == T) return;
6743
6744 Suspicious = false;
6745 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6746 E->getType(), CC, &Suspicious);
6747 if (!Suspicious)
6748 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006749 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006750}
6751
Richard Trieu65724892014-11-15 06:37:39 +00006752/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6753/// Input argument E is a logical expression.
6754static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6755 if (S.getLangOpts().Bool)
6756 return;
6757 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6758}
6759
John McCallcc7e5bf2010-05-06 08:58:33 +00006760/// AnalyzeImplicitConversions - Find and report any interesting
6761/// implicit conversions in the given expression. There are a couple
6762/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006763void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006764 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006765 Expr *E = OrigE->IgnoreParenImpCasts();
6766
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006767 if (E->isTypeDependent() || E->isValueDependent())
6768 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006769
John McCallcc7e5bf2010-05-06 08:58:33 +00006770 // For conditional operators, we analyze the arguments as if they
6771 // were being fed directly into the output.
6772 if (isa<ConditionalOperator>(E)) {
6773 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006774 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006775 return;
6776 }
6777
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006778 // Check implicit argument conversions for function calls.
6779 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6780 CheckImplicitArgumentConversions(S, Call, CC);
6781
John McCallcc7e5bf2010-05-06 08:58:33 +00006782 // Go ahead and check any implicit conversions we might have skipped.
6783 // The non-canonical typecheck is just an optimization;
6784 // CheckImplicitConversion will filter out dead implicit conversions.
6785 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006786 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006787
6788 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006789
6790 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006791 if (POE->getResultExpr())
6792 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006793 }
6794
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00006795 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
6796 if (OVE->getSourceExpr())
6797 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6798 return;
6799 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006800
John McCallcc7e5bf2010-05-06 08:58:33 +00006801 // Skip past explicit casts.
6802 if (isa<ExplicitCastExpr>(E)) {
6803 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006804 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006805 }
6806
John McCalld2a53122010-11-09 23:24:47 +00006807 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6808 // Do a somewhat different check with comparison operators.
6809 if (BO->isComparisonOp())
6810 return AnalyzeComparison(S, BO);
6811
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006812 // And with simple assignments.
6813 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006814 return AnalyzeAssignment(S, BO);
6815 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006816
6817 // These break the otherwise-useful invariant below. Fortunately,
6818 // we don't really need to recurse into them, because any internal
6819 // expressions should have been analyzed already when they were
6820 // built into statements.
6821 if (isa<StmtExpr>(E)) return;
6822
6823 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006824 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006825
6826 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006827 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006828 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006829 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006830 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006831 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006832 if (!ChildExpr)
6833 continue;
6834
Richard Trieu955231d2014-01-25 01:10:35 +00006835 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006836 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006837 // Ignore checking string literals that are in logical and operators.
6838 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006839 continue;
6840 AnalyzeImplicitConversions(S, ChildExpr, CC);
6841 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006842
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006843 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006844 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6845 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006846 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00006847
6848 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6849 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006850 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006851 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006852
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006853 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6854 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00006855 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006856}
6857
6858} // end anonymous namespace
6859
Richard Trieu3bb8b562014-02-26 02:36:06 +00006860enum {
6861 AddressOf,
6862 FunctionPointer,
6863 ArrayPointer
6864};
6865
Richard Trieuc1888e02014-06-28 23:25:37 +00006866// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6867// Returns true when emitting a warning about taking the address of a reference.
6868static bool CheckForReference(Sema &SemaRef, const Expr *E,
6869 PartialDiagnostic PD) {
6870 E = E->IgnoreParenImpCasts();
6871
6872 const FunctionDecl *FD = nullptr;
6873
6874 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6875 if (!DRE->getDecl()->getType()->isReferenceType())
6876 return false;
6877 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6878 if (!M->getMemberDecl()->getType()->isReferenceType())
6879 return false;
6880 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00006881 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00006882 return false;
6883 FD = Call->getDirectCallee();
6884 } else {
6885 return false;
6886 }
6887
6888 SemaRef.Diag(E->getExprLoc(), PD);
6889
6890 // If possible, point to location of function.
6891 if (FD) {
6892 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6893 }
6894
6895 return true;
6896}
6897
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006898// Returns true if the SourceLocation is expanded from any macro body.
6899// Returns false if the SourceLocation is invalid, is from not in a macro
6900// expansion, or is from expanded from a top-level macro argument.
6901static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6902 if (Loc.isInvalid())
6903 return false;
6904
6905 while (Loc.isMacroID()) {
6906 if (SM.isMacroBodyExpansion(Loc))
6907 return true;
6908 Loc = SM.getImmediateMacroCallerLoc(Loc);
6909 }
6910
6911 return false;
6912}
6913
Richard Trieu3bb8b562014-02-26 02:36:06 +00006914/// \brief Diagnose pointers that are always non-null.
6915/// \param E the expression containing the pointer
6916/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6917/// compared to a null pointer
6918/// \param IsEqual True when the comparison is equal to a null pointer
6919/// \param Range Extra SourceRange to highlight in the diagnostic
6920void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6921 Expr::NullPointerConstantKind NullKind,
6922 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006923 if (!E)
6924 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006925
6926 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006927 if (E->getExprLoc().isMacroID()) {
6928 const SourceManager &SM = getSourceManager();
6929 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6930 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006931 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006932 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006933 E = E->IgnoreImpCasts();
6934
6935 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6936
Richard Trieuf7432752014-06-06 21:39:26 +00006937 if (isa<CXXThisExpr>(E)) {
6938 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6939 : diag::warn_this_bool_conversion;
6940 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6941 return;
6942 }
6943
Richard Trieu3bb8b562014-02-26 02:36:06 +00006944 bool IsAddressOf = false;
6945
6946 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6947 if (UO->getOpcode() != UO_AddrOf)
6948 return;
6949 IsAddressOf = true;
6950 E = UO->getSubExpr();
6951 }
6952
Richard Trieuc1888e02014-06-28 23:25:37 +00006953 if (IsAddressOf) {
6954 unsigned DiagID = IsCompare
6955 ? diag::warn_address_of_reference_null_compare
6956 : diag::warn_address_of_reference_bool_conversion;
6957 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6958 << IsEqual;
6959 if (CheckForReference(*this, E, PD)) {
6960 return;
6961 }
6962 }
6963
Richard Trieu3bb8b562014-02-26 02:36:06 +00006964 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006965 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006966 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6967 D = R->getDecl();
6968 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6969 D = M->getMemberDecl();
6970 }
6971
6972 // Weak Decls can be null.
6973 if (!D || D->isWeak())
6974 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006975
6976 // Check for parameter decl with nonnull attribute
6977 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6978 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6979 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6980 unsigned NumArgs = FD->getNumParams();
6981 llvm::SmallBitVector AttrNonNull(NumArgs);
6982 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6983 if (!NonNull->args_size()) {
6984 AttrNonNull.set(0, NumArgs);
6985 break;
6986 }
6987 for (unsigned Val : NonNull->args()) {
6988 if (Val >= NumArgs)
6989 continue;
6990 AttrNonNull.set(Val);
6991 }
6992 }
6993 if (!AttrNonNull.empty())
6994 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00006995 if (FD->getParamDecl(i) == PV &&
6996 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006997 std::string Str;
6998 llvm::raw_string_ostream S(Str);
6999 E->printPretty(S, nullptr, getPrintingPolicy());
7000 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7001 : diag::warn_cast_nonnull_to_bool;
7002 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7003 << Range << IsEqual;
7004 return;
7005 }
7006 }
7007 }
7008
Richard Trieu3bb8b562014-02-26 02:36:06 +00007009 QualType T = D->getType();
7010 const bool IsArray = T->isArrayType();
7011 const bool IsFunction = T->isFunctionType();
7012
Richard Trieuc1888e02014-06-28 23:25:37 +00007013 // Address of function is used to silence the function warning.
7014 if (IsAddressOf && IsFunction) {
7015 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007016 }
7017
7018 // Found nothing.
7019 if (!IsAddressOf && !IsFunction && !IsArray)
7020 return;
7021
7022 // Pretty print the expression for the diagnostic.
7023 std::string Str;
7024 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007025 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007026
7027 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7028 : diag::warn_impcast_pointer_to_bool;
7029 unsigned DiagType;
7030 if (IsAddressOf)
7031 DiagType = AddressOf;
7032 else if (IsFunction)
7033 DiagType = FunctionPointer;
7034 else if (IsArray)
7035 DiagType = ArrayPointer;
7036 else
7037 llvm_unreachable("Could not determine diagnostic.");
7038 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7039 << Range << IsEqual;
7040
7041 if (!IsFunction)
7042 return;
7043
7044 // Suggest '&' to silence the function warning.
7045 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7046 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7047
7048 // Check to see if '()' fixit should be emitted.
7049 QualType ReturnType;
7050 UnresolvedSet<4> NonTemplateOverloads;
7051 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7052 if (ReturnType.isNull())
7053 return;
7054
7055 if (IsCompare) {
7056 // There are two cases here. If there is null constant, the only suggest
7057 // for a pointer return type. If the null is 0, then suggest if the return
7058 // type is a pointer or an integer type.
7059 if (!ReturnType->isPointerType()) {
7060 if (NullKind == Expr::NPCK_ZeroExpression ||
7061 NullKind == Expr::NPCK_ZeroLiteral) {
7062 if (!ReturnType->isIntegerType())
7063 return;
7064 } else {
7065 return;
7066 }
7067 }
7068 } else { // !IsCompare
7069 // For function to bool, only suggest if the function pointer has bool
7070 // return type.
7071 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7072 return;
7073 }
7074 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007075 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007076}
7077
7078
John McCallcc7e5bf2010-05-06 08:58:33 +00007079/// Diagnoses "dangerous" implicit conversions within the given
7080/// expression (which is a full expression). Implements -Wconversion
7081/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007082///
7083/// \param CC the "context" location of the implicit conversion, i.e.
7084/// the most location of the syntactic entity requiring the implicit
7085/// conversion
7086void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007087 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007088 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007089 return;
7090
7091 // Don't diagnose for value- or type-dependent expressions.
7092 if (E->isTypeDependent() || E->isValueDependent())
7093 return;
7094
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007095 // Check for array bounds violations in cases where the check isn't triggered
7096 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7097 // ArraySubscriptExpr is on the RHS of a variable initialization.
7098 CheckArrayAccess(E);
7099
John McCallacf0ee52010-10-08 02:01:28 +00007100 // This is not the right CC for (e.g.) a variable initialization.
7101 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007102}
7103
Richard Trieu65724892014-11-15 06:37:39 +00007104/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7105/// Input argument E is a logical expression.
7106void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7107 ::CheckBoolLikeConversion(*this, E, CC);
7108}
7109
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007110/// Diagnose when expression is an integer constant expression and its evaluation
7111/// results in integer overflow
7112void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007113 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7114 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007115}
7116
Richard Smithc406cb72013-01-17 01:17:56 +00007117namespace {
7118/// \brief Visitor for expressions which looks for unsequenced operations on the
7119/// same object.
7120class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007121 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7122
Richard Smithc406cb72013-01-17 01:17:56 +00007123 /// \brief A tree of sequenced regions within an expression. Two regions are
7124 /// unsequenced if one is an ancestor or a descendent of the other. When we
7125 /// finish processing an expression with sequencing, such as a comma
7126 /// expression, we fold its tree nodes into its parent, since they are
7127 /// unsequenced with respect to nodes we will visit later.
7128 class SequenceTree {
7129 struct Value {
7130 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7131 unsigned Parent : 31;
7132 bool Merged : 1;
7133 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007134 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007135
7136 public:
7137 /// \brief A region within an expression which may be sequenced with respect
7138 /// to some other region.
7139 class Seq {
7140 explicit Seq(unsigned N) : Index(N) {}
7141 unsigned Index;
7142 friend class SequenceTree;
7143 public:
7144 Seq() : Index(0) {}
7145 };
7146
7147 SequenceTree() { Values.push_back(Value(0)); }
7148 Seq root() const { return Seq(0); }
7149
7150 /// \brief Create a new sequence of operations, which is an unsequenced
7151 /// subset of \p Parent. This sequence of operations is sequenced with
7152 /// respect to other children of \p Parent.
7153 Seq allocate(Seq Parent) {
7154 Values.push_back(Value(Parent.Index));
7155 return Seq(Values.size() - 1);
7156 }
7157
7158 /// \brief Merge a sequence of operations into its parent.
7159 void merge(Seq S) {
7160 Values[S.Index].Merged = true;
7161 }
7162
7163 /// \brief Determine whether two operations are unsequenced. This operation
7164 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7165 /// should have been merged into its parent as appropriate.
7166 bool isUnsequenced(Seq Cur, Seq Old) {
7167 unsigned C = representative(Cur.Index);
7168 unsigned Target = representative(Old.Index);
7169 while (C >= Target) {
7170 if (C == Target)
7171 return true;
7172 C = Values[C].Parent;
7173 }
7174 return false;
7175 }
7176
7177 private:
7178 /// \brief Pick a representative for a sequence.
7179 unsigned representative(unsigned K) {
7180 if (Values[K].Merged)
7181 // Perform path compression as we go.
7182 return Values[K].Parent = representative(Values[K].Parent);
7183 return K;
7184 }
7185 };
7186
7187 /// An object for which we can track unsequenced uses.
7188 typedef NamedDecl *Object;
7189
7190 /// Different flavors of object usage which we track. We only track the
7191 /// least-sequenced usage of each kind.
7192 enum UsageKind {
7193 /// A read of an object. Multiple unsequenced reads are OK.
7194 UK_Use,
7195 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007196 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007197 UK_ModAsValue,
7198 /// A modification of an object which is not sequenced before the value
7199 /// computation of the expression, such as n++.
7200 UK_ModAsSideEffect,
7201
7202 UK_Count = UK_ModAsSideEffect + 1
7203 };
7204
7205 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007206 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007207 Expr *Use;
7208 SequenceTree::Seq Seq;
7209 };
7210
7211 struct UsageInfo {
7212 UsageInfo() : Diagnosed(false) {}
7213 Usage Uses[UK_Count];
7214 /// Have we issued a diagnostic for this variable already?
7215 bool Diagnosed;
7216 };
7217 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7218
7219 Sema &SemaRef;
7220 /// Sequenced regions within the expression.
7221 SequenceTree Tree;
7222 /// Declaration modifications and references which we have seen.
7223 UsageInfoMap UsageMap;
7224 /// The region we are currently within.
7225 SequenceTree::Seq Region;
7226 /// Filled in with declarations which were modified as a side-effect
7227 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007228 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007229 /// Expressions to check later. We defer checking these to reduce
7230 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007231 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007232
7233 /// RAII object wrapping the visitation of a sequenced subexpression of an
7234 /// expression. At the end of this process, the side-effects of the evaluation
7235 /// become sequenced with respect to the value computation of the result, so
7236 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7237 /// UK_ModAsValue.
7238 struct SequencedSubexpression {
7239 SequencedSubexpression(SequenceChecker &Self)
7240 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7241 Self.ModAsSideEffect = &ModAsSideEffect;
7242 }
7243 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007244 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7245 MI != ME; ++MI) {
7246 UsageInfo &U = Self.UsageMap[MI->first];
7247 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7248 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7249 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007250 }
7251 Self.ModAsSideEffect = OldModAsSideEffect;
7252 }
7253
7254 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007255 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7256 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007257 };
7258
Richard Smith40238f02013-06-20 22:21:56 +00007259 /// RAII object wrapping the visitation of a subexpression which we might
7260 /// choose to evaluate as a constant. If any subexpression is evaluated and
7261 /// found to be non-constant, this allows us to suppress the evaluation of
7262 /// the outer expression.
7263 class EvaluationTracker {
7264 public:
7265 EvaluationTracker(SequenceChecker &Self)
7266 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7267 Self.EvalTracker = this;
7268 }
7269 ~EvaluationTracker() {
7270 Self.EvalTracker = Prev;
7271 if (Prev)
7272 Prev->EvalOK &= EvalOK;
7273 }
7274
7275 bool evaluate(const Expr *E, bool &Result) {
7276 if (!EvalOK || E->isValueDependent())
7277 return false;
7278 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7279 return EvalOK;
7280 }
7281
7282 private:
7283 SequenceChecker &Self;
7284 EvaluationTracker *Prev;
7285 bool EvalOK;
7286 } *EvalTracker;
7287
Richard Smithc406cb72013-01-17 01:17:56 +00007288 /// \brief Find the object which is produced by the specified expression,
7289 /// if any.
7290 Object getObject(Expr *E, bool Mod) const {
7291 E = E->IgnoreParenCasts();
7292 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7293 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7294 return getObject(UO->getSubExpr(), Mod);
7295 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7296 if (BO->getOpcode() == BO_Comma)
7297 return getObject(BO->getRHS(), Mod);
7298 if (Mod && BO->isAssignmentOp())
7299 return getObject(BO->getLHS(), Mod);
7300 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7301 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7302 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7303 return ME->getMemberDecl();
7304 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7305 // FIXME: If this is a reference, map through to its value.
7306 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007307 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007308 }
7309
7310 /// \brief Note that an object was modified or used by an expression.
7311 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7312 Usage &U = UI.Uses[UK];
7313 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7314 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7315 ModAsSideEffect->push_back(std::make_pair(O, U));
7316 U.Use = Ref;
7317 U.Seq = Region;
7318 }
7319 }
7320 /// \brief Check whether a modification or use conflicts with a prior usage.
7321 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7322 bool IsModMod) {
7323 if (UI.Diagnosed)
7324 return;
7325
7326 const Usage &U = UI.Uses[OtherKind];
7327 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7328 return;
7329
7330 Expr *Mod = U.Use;
7331 Expr *ModOrUse = Ref;
7332 if (OtherKind == UK_Use)
7333 std::swap(Mod, ModOrUse);
7334
7335 SemaRef.Diag(Mod->getExprLoc(),
7336 IsModMod ? diag::warn_unsequenced_mod_mod
7337 : diag::warn_unsequenced_mod_use)
7338 << O << SourceRange(ModOrUse->getExprLoc());
7339 UI.Diagnosed = true;
7340 }
7341
7342 void notePreUse(Object O, Expr *Use) {
7343 UsageInfo &U = UsageMap[O];
7344 // Uses conflict with other modifications.
7345 checkUsage(O, U, Use, UK_ModAsValue, false);
7346 }
7347 void notePostUse(Object O, Expr *Use) {
7348 UsageInfo &U = UsageMap[O];
7349 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7350 addUsage(U, O, Use, UK_Use);
7351 }
7352
7353 void notePreMod(Object O, Expr *Mod) {
7354 UsageInfo &U = UsageMap[O];
7355 // Modifications conflict with other modifications and with uses.
7356 checkUsage(O, U, Mod, UK_ModAsValue, true);
7357 checkUsage(O, U, Mod, UK_Use, false);
7358 }
7359 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7360 UsageInfo &U = UsageMap[O];
7361 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7362 addUsage(U, O, Use, UK);
7363 }
7364
7365public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007366 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007367 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7368 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007369 Visit(E);
7370 }
7371
7372 void VisitStmt(Stmt *S) {
7373 // Skip all statements which aren't expressions for now.
7374 }
7375
7376 void VisitExpr(Expr *E) {
7377 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007378 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007379 }
7380
7381 void VisitCastExpr(CastExpr *E) {
7382 Object O = Object();
7383 if (E->getCastKind() == CK_LValueToRValue)
7384 O = getObject(E->getSubExpr(), false);
7385
7386 if (O)
7387 notePreUse(O, E);
7388 VisitExpr(E);
7389 if (O)
7390 notePostUse(O, E);
7391 }
7392
7393 void VisitBinComma(BinaryOperator *BO) {
7394 // C++11 [expr.comma]p1:
7395 // Every value computation and side effect associated with the left
7396 // expression is sequenced before every value computation and side
7397 // effect associated with the right expression.
7398 SequenceTree::Seq LHS = Tree.allocate(Region);
7399 SequenceTree::Seq RHS = Tree.allocate(Region);
7400 SequenceTree::Seq OldRegion = Region;
7401
7402 {
7403 SequencedSubexpression SeqLHS(*this);
7404 Region = LHS;
7405 Visit(BO->getLHS());
7406 }
7407
7408 Region = RHS;
7409 Visit(BO->getRHS());
7410
7411 Region = OldRegion;
7412
7413 // Forget that LHS and RHS are sequenced. They are both unsequenced
7414 // with respect to other stuff.
7415 Tree.merge(LHS);
7416 Tree.merge(RHS);
7417 }
7418
7419 void VisitBinAssign(BinaryOperator *BO) {
7420 // The modification is sequenced after the value computation of the LHS
7421 // and RHS, so check it before inspecting the operands and update the
7422 // map afterwards.
7423 Object O = getObject(BO->getLHS(), true);
7424 if (!O)
7425 return VisitExpr(BO);
7426
7427 notePreMod(O, BO);
7428
7429 // C++11 [expr.ass]p7:
7430 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7431 // only once.
7432 //
7433 // Therefore, for a compound assignment operator, O is considered used
7434 // everywhere except within the evaluation of E1 itself.
7435 if (isa<CompoundAssignOperator>(BO))
7436 notePreUse(O, BO);
7437
7438 Visit(BO->getLHS());
7439
7440 if (isa<CompoundAssignOperator>(BO))
7441 notePostUse(O, BO);
7442
7443 Visit(BO->getRHS());
7444
Richard Smith83e37bee2013-06-26 23:16:51 +00007445 // C++11 [expr.ass]p1:
7446 // the assignment is sequenced [...] before the value computation of the
7447 // assignment expression.
7448 // C11 6.5.16/3 has no such rule.
7449 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7450 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007451 }
7452 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7453 VisitBinAssign(CAO);
7454 }
7455
7456 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7457 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7458 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7459 Object O = getObject(UO->getSubExpr(), true);
7460 if (!O)
7461 return VisitExpr(UO);
7462
7463 notePreMod(O, UO);
7464 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007465 // C++11 [expr.pre.incr]p1:
7466 // the expression ++x is equivalent to x+=1
7467 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7468 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007469 }
7470
7471 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7472 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7473 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7474 Object O = getObject(UO->getSubExpr(), true);
7475 if (!O)
7476 return VisitExpr(UO);
7477
7478 notePreMod(O, UO);
7479 Visit(UO->getSubExpr());
7480 notePostMod(O, UO, UK_ModAsSideEffect);
7481 }
7482
7483 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7484 void VisitBinLOr(BinaryOperator *BO) {
7485 // The side-effects of the LHS of an '&&' are sequenced before the
7486 // value computation of the RHS, and hence before the value computation
7487 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7488 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007489 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007490 {
7491 SequencedSubexpression Sequenced(*this);
7492 Visit(BO->getLHS());
7493 }
7494
7495 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007496 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007497 if (!Result)
7498 Visit(BO->getRHS());
7499 } else {
7500 // Check for unsequenced operations in the RHS, treating it as an
7501 // entirely separate evaluation.
7502 //
7503 // FIXME: If there are operations in the RHS which are unsequenced
7504 // with respect to operations outside the RHS, and those operations
7505 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007506 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007507 }
Richard Smithc406cb72013-01-17 01:17:56 +00007508 }
7509 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007510 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007511 {
7512 SequencedSubexpression Sequenced(*this);
7513 Visit(BO->getLHS());
7514 }
7515
7516 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007517 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007518 if (Result)
7519 Visit(BO->getRHS());
7520 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007521 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007522 }
Richard Smithc406cb72013-01-17 01:17:56 +00007523 }
7524
7525 // Only visit the condition, unless we can be sure which subexpression will
7526 // be chosen.
7527 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007528 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007529 {
7530 SequencedSubexpression Sequenced(*this);
7531 Visit(CO->getCond());
7532 }
Richard Smithc406cb72013-01-17 01:17:56 +00007533
7534 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007535 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007536 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007537 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007538 WorkList.push_back(CO->getTrueExpr());
7539 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007540 }
Richard Smithc406cb72013-01-17 01:17:56 +00007541 }
7542
Richard Smithe3dbfe02013-06-30 10:40:20 +00007543 void VisitCallExpr(CallExpr *CE) {
7544 // C++11 [intro.execution]p15:
7545 // When calling a function [...], every value computation and side effect
7546 // associated with any argument expression, or with the postfix expression
7547 // designating the called function, is sequenced before execution of every
7548 // expression or statement in the body of the function [and thus before
7549 // the value computation of its result].
7550 SequencedSubexpression Sequenced(*this);
7551 Base::VisitCallExpr(CE);
7552
7553 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7554 }
7555
Richard Smithc406cb72013-01-17 01:17:56 +00007556 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007557 // This is a call, so all subexpressions are sequenced before the result.
7558 SequencedSubexpression Sequenced(*this);
7559
Richard Smithc406cb72013-01-17 01:17:56 +00007560 if (!CCE->isListInitialization())
7561 return VisitExpr(CCE);
7562
7563 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007564 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007565 SequenceTree::Seq Parent = Region;
7566 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7567 E = CCE->arg_end();
7568 I != E; ++I) {
7569 Region = Tree.allocate(Parent);
7570 Elts.push_back(Region);
7571 Visit(*I);
7572 }
7573
7574 // Forget that the initializers are sequenced.
7575 Region = Parent;
7576 for (unsigned I = 0; I < Elts.size(); ++I)
7577 Tree.merge(Elts[I]);
7578 }
7579
7580 void VisitInitListExpr(InitListExpr *ILE) {
7581 if (!SemaRef.getLangOpts().CPlusPlus11)
7582 return VisitExpr(ILE);
7583
7584 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007585 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007586 SequenceTree::Seq Parent = Region;
7587 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7588 Expr *E = ILE->getInit(I);
7589 if (!E) continue;
7590 Region = Tree.allocate(Parent);
7591 Elts.push_back(Region);
7592 Visit(E);
7593 }
7594
7595 // Forget that the initializers are sequenced.
7596 Region = Parent;
7597 for (unsigned I = 0; I < Elts.size(); ++I)
7598 Tree.merge(Elts[I]);
7599 }
7600};
7601}
7602
7603void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007604 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007605 WorkList.push_back(E);
7606 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007607 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007608 SequenceChecker(*this, Item, WorkList);
7609 }
Richard Smithc406cb72013-01-17 01:17:56 +00007610}
7611
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007612void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7613 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007614 CheckImplicitConversions(E, CheckLoc);
7615 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007616 if (!IsConstexpr && !E->isValueDependent())
7617 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007618}
7619
John McCall1f425642010-11-11 03:21:53 +00007620void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7621 FieldDecl *BitField,
7622 Expr *Init) {
7623 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7624}
7625
Mike Stump0c2ec772010-01-21 03:59:47 +00007626/// CheckParmsForFunctionDef - Check that the parameters of the given
7627/// function are appropriate for the definition of a function. This
7628/// takes care of any checks that cannot be performed on the
7629/// declaration itself, e.g., that the types of each of the function
7630/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007631bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7632 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007633 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007634 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007635 for (; P != PEnd; ++P) {
7636 ParmVarDecl *Param = *P;
7637
Mike Stump0c2ec772010-01-21 03:59:47 +00007638 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7639 // function declarator that is part of a function definition of
7640 // that function shall not have incomplete type.
7641 //
7642 // This is also C++ [dcl.fct]p6.
7643 if (!Param->isInvalidDecl() &&
7644 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007645 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007646 Param->setInvalidDecl();
7647 HasInvalidParm = true;
7648 }
7649
7650 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7651 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007652 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007653 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007654 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007655 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007656 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007657
7658 // C99 6.7.5.3p12:
7659 // If the function declarator is not part of a definition of that
7660 // function, parameters may have incomplete type and may use the [*]
7661 // notation in their sequences of declarator specifiers to specify
7662 // variable length array types.
7663 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007664 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007665 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007666 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007667 // information is added for it.
7668 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007669 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007670 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007671 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007672 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007673
7674 // MSVC destroys objects passed by value in the callee. Therefore a
7675 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007676 // object's destructor. However, we don't perform any direct access check
7677 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007678 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7679 .getCXXABI()
7680 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007681 if (!Param->isInvalidDecl()) {
7682 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7683 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7684 if (!ClassDecl->isInvalidDecl() &&
7685 !ClassDecl->hasIrrelevantDestructor() &&
7686 !ClassDecl->isDependentContext()) {
7687 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7688 MarkFunctionReferenced(Param->getLocation(), Destructor);
7689 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7690 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007691 }
7692 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007693 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007694 }
7695
7696 return HasInvalidParm;
7697}
John McCall2b5c1b22010-08-12 21:44:57 +00007698
7699/// CheckCastAlign - Implements -Wcast-align, which warns when a
7700/// pointer cast increases the alignment requirements.
7701void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7702 // This is actually a lot of work to potentially be doing on every
7703 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007704 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007705 return;
7706
7707 // Ignore dependent types.
7708 if (T->isDependentType() || Op->getType()->isDependentType())
7709 return;
7710
7711 // Require that the destination be a pointer type.
7712 const PointerType *DestPtr = T->getAs<PointerType>();
7713 if (!DestPtr) return;
7714
7715 // If the destination has alignment 1, we're done.
7716 QualType DestPointee = DestPtr->getPointeeType();
7717 if (DestPointee->isIncompleteType()) return;
7718 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7719 if (DestAlign.isOne()) return;
7720
7721 // Require that the source be a pointer type.
7722 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7723 if (!SrcPtr) return;
7724 QualType SrcPointee = SrcPtr->getPointeeType();
7725
7726 // Whitelist casts from cv void*. We already implicitly
7727 // whitelisted casts to cv void*, since they have alignment 1.
7728 // Also whitelist casts involving incomplete types, which implicitly
7729 // includes 'void'.
7730 if (SrcPointee->isIncompleteType()) return;
7731
7732 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7733 if (SrcAlign >= DestAlign) return;
7734
7735 Diag(TRange.getBegin(), diag::warn_cast_align)
7736 << Op->getType() << T
7737 << static_cast<unsigned>(SrcAlign.getQuantity())
7738 << static_cast<unsigned>(DestAlign.getQuantity())
7739 << TRange << Op->getSourceRange();
7740}
7741
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007742static const Type* getElementType(const Expr *BaseExpr) {
7743 const Type* EltType = BaseExpr->getType().getTypePtr();
7744 if (EltType->isAnyPointerType())
7745 return EltType->getPointeeType().getTypePtr();
7746 else if (EltType->isArrayType())
7747 return EltType->getBaseElementTypeUnsafe();
7748 return EltType;
7749}
7750
Chandler Carruth28389f02011-08-05 09:10:50 +00007751/// \brief Check whether this array fits the idiom of a size-one tail padded
7752/// array member of a struct.
7753///
7754/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7755/// commonly used to emulate flexible arrays in C89 code.
7756static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7757 const NamedDecl *ND) {
7758 if (Size != 1 || !ND) return false;
7759
7760 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7761 if (!FD) return false;
7762
7763 // Don't consider sizes resulting from macro expansions or template argument
7764 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007765
7766 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007767 while (TInfo) {
7768 TypeLoc TL = TInfo->getTypeLoc();
7769 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007770 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7771 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007772 TInfo = TDL->getTypeSourceInfo();
7773 continue;
7774 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007775 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7776 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007777 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7778 return false;
7779 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007780 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007781 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007782
7783 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007784 if (!RD) return false;
7785 if (RD->isUnion()) return false;
7786 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7787 if (!CRD->isStandardLayout()) return false;
7788 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007789
Benjamin Kramer8c543672011-08-06 03:04:42 +00007790 // See if this is the last field decl in the record.
7791 const Decl *D = FD;
7792 while ((D = D->getNextDeclInContext()))
7793 if (isa<FieldDecl>(D))
7794 return false;
7795 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007796}
7797
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007798void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007799 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007800 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007801 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007802 if (IndexExpr->isValueDependent())
7803 return;
7804
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007805 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007806 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007807 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007808 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007809 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007810 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007811
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007812 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007813 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007814 return;
Richard Smith13f67182011-12-16 19:31:14 +00007815 if (IndexNegated)
7816 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007817
Craig Topperc3ec1492014-05-26 06:22:03 +00007818 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007819 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7820 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007821 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007822 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007823
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007824 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007825 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007826 if (!size.isStrictlyPositive())
7827 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007828
7829 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007830 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007831 // Make sure we're comparing apples to apples when comparing index to size
7832 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7833 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007834 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007835 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007836 if (ptrarith_typesize != array_typesize) {
7837 // There's a cast to a different size type involved
7838 uint64_t ratio = array_typesize / ptrarith_typesize;
7839 // TODO: Be smarter about handling cases where array_typesize is not a
7840 // multiple of ptrarith_typesize
7841 if (ptrarith_typesize * ratio == array_typesize)
7842 size *= llvm::APInt(size.getBitWidth(), ratio);
7843 }
7844 }
7845
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007846 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007847 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007848 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007849 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007850
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007851 // For array subscripting the index must be less than size, but for pointer
7852 // arithmetic also allow the index (offset) to be equal to size since
7853 // computing the next address after the end of the array is legal and
7854 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007855 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007856 return;
7857
7858 // Also don't warn for arrays of size 1 which are members of some
7859 // structure. These are often used to approximate flexible arrays in C89
7860 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007861 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007862 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007863
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007864 // Suppress the warning if the subscript expression (as identified by the
7865 // ']' location) and the index expression are both from macro expansions
7866 // within a system header.
7867 if (ASE) {
7868 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7869 ASE->getRBracketLoc());
7870 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7871 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7872 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007873 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007874 return;
7875 }
7876 }
7877
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007878 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007879 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007880 DiagID = diag::warn_array_index_exceeds_bounds;
7881
7882 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7883 PDiag(DiagID) << index.toString(10, true)
7884 << size.toString(10, true)
7885 << (unsigned)size.getLimitedValue(~0U)
7886 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007887 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007888 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007889 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007890 DiagID = diag::warn_ptr_arith_precedes_bounds;
7891 if (index.isNegative()) index = -index;
7892 }
7893
7894 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7895 PDiag(DiagID) << index.toString(10, true)
7896 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007897 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007898
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007899 if (!ND) {
7900 // Try harder to find a NamedDecl to point at in the note.
7901 while (const ArraySubscriptExpr *ASE =
7902 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7903 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7904 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7905 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7906 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7907 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7908 }
7909
Chandler Carruth1af88f12011-02-17 21:10:52 +00007910 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007911 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7912 PDiag(diag::note_array_index_out_of_bounds)
7913 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007914}
7915
Ted Kremenekdf26df72011-03-01 18:41:00 +00007916void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007917 int AllowOnePastEnd = 0;
7918 while (expr) {
7919 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007920 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007921 case Stmt::ArraySubscriptExprClass: {
7922 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007923 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007924 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007925 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007926 }
7927 case Stmt::UnaryOperatorClass: {
7928 // Only unwrap the * and & unary operators
7929 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7930 expr = UO->getSubExpr();
7931 switch (UO->getOpcode()) {
7932 case UO_AddrOf:
7933 AllowOnePastEnd++;
7934 break;
7935 case UO_Deref:
7936 AllowOnePastEnd--;
7937 break;
7938 default:
7939 return;
7940 }
7941 break;
7942 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007943 case Stmt::ConditionalOperatorClass: {
7944 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7945 if (const Expr *lhs = cond->getLHS())
7946 CheckArrayAccess(lhs);
7947 if (const Expr *rhs = cond->getRHS())
7948 CheckArrayAccess(rhs);
7949 return;
7950 }
7951 default:
7952 return;
7953 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007954 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007955}
John McCall31168b02011-06-15 23:02:42 +00007956
7957//===--- CHECK: Objective-C retain cycles ----------------------------------//
7958
7959namespace {
7960 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007961 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007962 VarDecl *Variable;
7963 SourceRange Range;
7964 SourceLocation Loc;
7965 bool Indirect;
7966
7967 void setLocsFrom(Expr *e) {
7968 Loc = e->getExprLoc();
7969 Range = e->getSourceRange();
7970 }
7971 };
7972}
7973
7974/// Consider whether capturing the given variable can possibly lead to
7975/// a retain cycle.
7976static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007977 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007978 // lifetime. In MRR, it's captured strongly if the variable is
7979 // __block and has an appropriate type.
7980 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7981 return false;
7982
7983 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007984 if (ref)
7985 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007986 return true;
7987}
7988
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007989static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007990 while (true) {
7991 e = e->IgnoreParens();
7992 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7993 switch (cast->getCastKind()) {
7994 case CK_BitCast:
7995 case CK_LValueBitCast:
7996 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007997 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007998 e = cast->getSubExpr();
7999 continue;
8000
John McCall31168b02011-06-15 23:02:42 +00008001 default:
8002 return false;
8003 }
8004 }
8005
8006 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8007 ObjCIvarDecl *ivar = ref->getDecl();
8008 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8009 return false;
8010
8011 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008012 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008013 return false;
8014
8015 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8016 owner.Indirect = true;
8017 return true;
8018 }
8019
8020 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8021 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8022 if (!var) return false;
8023 return considerVariable(var, ref, owner);
8024 }
8025
John McCall31168b02011-06-15 23:02:42 +00008026 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8027 if (member->isArrow()) return false;
8028
8029 // Don't count this as an indirect ownership.
8030 e = member->getBase();
8031 continue;
8032 }
8033
John McCallfe96e0b2011-11-06 09:01:30 +00008034 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8035 // Only pay attention to pseudo-objects on property references.
8036 ObjCPropertyRefExpr *pre
8037 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8038 ->IgnoreParens());
8039 if (!pre) return false;
8040 if (pre->isImplicitProperty()) return false;
8041 ObjCPropertyDecl *property = pre->getExplicitProperty();
8042 if (!property->isRetaining() &&
8043 !(property->getPropertyIvarDecl() &&
8044 property->getPropertyIvarDecl()->getType()
8045 .getObjCLifetime() == Qualifiers::OCL_Strong))
8046 return false;
8047
8048 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008049 if (pre->isSuperReceiver()) {
8050 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8051 if (!owner.Variable)
8052 return false;
8053 owner.Loc = pre->getLocation();
8054 owner.Range = pre->getSourceRange();
8055 return true;
8056 }
John McCallfe96e0b2011-11-06 09:01:30 +00008057 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8058 ->getSourceExpr());
8059 continue;
8060 }
8061
John McCall31168b02011-06-15 23:02:42 +00008062 // Array ivars?
8063
8064 return false;
8065 }
8066}
8067
8068namespace {
8069 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8070 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8071 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008072 Context(Context), Variable(variable), Capturer(nullptr),
8073 VarWillBeReased(false) {}
8074 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008075 VarDecl *Variable;
8076 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008077 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008078
8079 void VisitDeclRefExpr(DeclRefExpr *ref) {
8080 if (ref->getDecl() == Variable && !Capturer)
8081 Capturer = ref;
8082 }
8083
John McCall31168b02011-06-15 23:02:42 +00008084 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8085 if (Capturer) return;
8086 Visit(ref->getBase());
8087 if (Capturer && ref->isFreeIvar())
8088 Capturer = ref;
8089 }
8090
8091 void VisitBlockExpr(BlockExpr *block) {
8092 // Look inside nested blocks
8093 if (block->getBlockDecl()->capturesVariable(Variable))
8094 Visit(block->getBlockDecl()->getBody());
8095 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008096
8097 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8098 if (Capturer) return;
8099 if (OVE->getSourceExpr())
8100 Visit(OVE->getSourceExpr());
8101 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008102 void VisitBinaryOperator(BinaryOperator *BinOp) {
8103 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8104 return;
8105 Expr *LHS = BinOp->getLHS();
8106 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8107 if (DRE->getDecl() != Variable)
8108 return;
8109 if (Expr *RHS = BinOp->getRHS()) {
8110 RHS = RHS->IgnoreParenCasts();
8111 llvm::APSInt Value;
8112 VarWillBeReased =
8113 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8114 }
8115 }
8116 }
John McCall31168b02011-06-15 23:02:42 +00008117 };
8118}
8119
8120/// Check whether the given argument is a block which captures a
8121/// variable.
8122static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8123 assert(owner.Variable && owner.Loc.isValid());
8124
8125 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008126
8127 // Look through [^{...} copy] and Block_copy(^{...}).
8128 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8129 Selector Cmd = ME->getSelector();
8130 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8131 e = ME->getInstanceReceiver();
8132 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008133 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008134 e = e->IgnoreParenCasts();
8135 }
8136 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8137 if (CE->getNumArgs() == 1) {
8138 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008139 if (Fn) {
8140 const IdentifierInfo *FnI = Fn->getIdentifier();
8141 if (FnI && FnI->isStr("_Block_copy")) {
8142 e = CE->getArg(0)->IgnoreParenCasts();
8143 }
8144 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008145 }
8146 }
8147
John McCall31168b02011-06-15 23:02:42 +00008148 BlockExpr *block = dyn_cast<BlockExpr>(e);
8149 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008150 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008151
8152 FindCaptureVisitor visitor(S.Context, owner.Variable);
8153 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008154 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008155}
8156
8157static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8158 RetainCycleOwner &owner) {
8159 assert(capturer);
8160 assert(owner.Variable && owner.Loc.isValid());
8161
8162 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8163 << owner.Variable << capturer->getSourceRange();
8164 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8165 << owner.Indirect << owner.Range;
8166}
8167
8168/// Check for a keyword selector that starts with the word 'add' or
8169/// 'set'.
8170static bool isSetterLikeSelector(Selector sel) {
8171 if (sel.isUnarySelector()) return false;
8172
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008173 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008174 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008175 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008176 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008177 else if (str.startswith("add")) {
8178 // Specially whitelist 'addOperationWithBlock:'.
8179 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8180 return false;
8181 str = str.substr(3);
8182 }
John McCall31168b02011-06-15 23:02:42 +00008183 else
8184 return false;
8185
8186 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008187 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008188}
8189
8190/// Check a message send to see if it's likely to cause a retain cycle.
8191void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8192 // Only check instance methods whose selector looks like a setter.
8193 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8194 return;
8195
8196 // Try to find a variable that the receiver is strongly owned by.
8197 RetainCycleOwner owner;
8198 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008199 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008200 return;
8201 } else {
8202 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8203 owner.Variable = getCurMethodDecl()->getSelfDecl();
8204 owner.Loc = msg->getSuperLoc();
8205 owner.Range = msg->getSuperLoc();
8206 }
8207
8208 // Check whether the receiver is captured by any of the arguments.
8209 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8210 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8211 return diagnoseRetainCycle(*this, capturer, owner);
8212}
8213
8214/// Check a property assign to see if it's likely to cause a retain cycle.
8215void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8216 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008217 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008218 return;
8219
8220 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8221 diagnoseRetainCycle(*this, capturer, owner);
8222}
8223
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008224void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8225 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008226 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008227 return;
8228
8229 // Because we don't have an expression for the variable, we have to set the
8230 // location explicitly here.
8231 Owner.Loc = Var->getLocation();
8232 Owner.Range = Var->getSourceRange();
8233
8234 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8235 diagnoseRetainCycle(*this, Capturer, Owner);
8236}
8237
Ted Kremenek9304da92012-12-21 08:04:28 +00008238static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8239 Expr *RHS, bool isProperty) {
8240 // Check if RHS is an Objective-C object literal, which also can get
8241 // immediately zapped in a weak reference. Note that we explicitly
8242 // allow ObjCStringLiterals, since those are designed to never really die.
8243 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008244
Ted Kremenek64873352012-12-21 22:46:35 +00008245 // This enum needs to match with the 'select' in
8246 // warn_objc_arc_literal_assign (off-by-1).
8247 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8248 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8249 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008250
8251 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008252 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008253 << (isProperty ? 0 : 1)
8254 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008255
8256 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008257}
8258
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008259static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8260 Qualifiers::ObjCLifetime LT,
8261 Expr *RHS, bool isProperty) {
8262 // Strip off any implicit cast added to get to the one ARC-specific.
8263 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8264 if (cast->getCastKind() == CK_ARCConsumeObject) {
8265 S.Diag(Loc, diag::warn_arc_retained_assign)
8266 << (LT == Qualifiers::OCL_ExplicitNone)
8267 << (isProperty ? 0 : 1)
8268 << RHS->getSourceRange();
8269 return true;
8270 }
8271 RHS = cast->getSubExpr();
8272 }
8273
8274 if (LT == Qualifiers::OCL_Weak &&
8275 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8276 return true;
8277
8278 return false;
8279}
8280
Ted Kremenekb36234d2012-12-21 08:04:20 +00008281bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8282 QualType LHS, Expr *RHS) {
8283 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8284
8285 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8286 return false;
8287
8288 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8289 return true;
8290
8291 return false;
8292}
8293
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008294void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8295 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008296 QualType LHSType;
8297 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008298 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008299 ObjCPropertyRefExpr *PRE
8300 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8301 if (PRE && !PRE->isImplicitProperty()) {
8302 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8303 if (PD)
8304 LHSType = PD->getType();
8305 }
8306
8307 if (LHSType.isNull())
8308 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008309
8310 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8311
8312 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008313 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008314 getCurFunction()->markSafeWeakUse(LHS);
8315 }
8316
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008317 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8318 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008319
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008320 // FIXME. Check for other life times.
8321 if (LT != Qualifiers::OCL_None)
8322 return;
8323
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008324 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008325 if (PRE->isImplicitProperty())
8326 return;
8327 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8328 if (!PD)
8329 return;
8330
Bill Wendling44426052012-12-20 19:22:21 +00008331 unsigned Attributes = PD->getPropertyAttributes();
8332 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008333 // when 'assign' attribute was not explicitly specified
8334 // by user, ignore it and rely on property type itself
8335 // for lifetime info.
8336 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8337 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8338 LHSType->isObjCRetainableType())
8339 return;
8340
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008341 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008342 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008343 Diag(Loc, diag::warn_arc_retained_property_assign)
8344 << RHS->getSourceRange();
8345 return;
8346 }
8347 RHS = cast->getSubExpr();
8348 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008349 }
Bill Wendling44426052012-12-20 19:22:21 +00008350 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008351 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8352 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008353 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008354 }
8355}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008356
8357//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8358
8359namespace {
8360bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8361 SourceLocation StmtLoc,
8362 const NullStmt *Body) {
8363 // Do not warn if the body is a macro that expands to nothing, e.g:
8364 //
8365 // #define CALL(x)
8366 // if (condition)
8367 // CALL(0);
8368 //
8369 if (Body->hasLeadingEmptyMacro())
8370 return false;
8371
8372 // Get line numbers of statement and body.
8373 bool StmtLineInvalid;
8374 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8375 &StmtLineInvalid);
8376 if (StmtLineInvalid)
8377 return false;
8378
8379 bool BodyLineInvalid;
8380 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8381 &BodyLineInvalid);
8382 if (BodyLineInvalid)
8383 return false;
8384
8385 // Warn if null statement and body are on the same line.
8386 if (StmtLine != BodyLine)
8387 return false;
8388
8389 return true;
8390}
8391} // Unnamed namespace
8392
8393void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8394 const Stmt *Body,
8395 unsigned DiagID) {
8396 // Since this is a syntactic check, don't emit diagnostic for template
8397 // instantiations, this just adds noise.
8398 if (CurrentInstantiationScope)
8399 return;
8400
8401 // The body should be a null statement.
8402 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8403 if (!NBody)
8404 return;
8405
8406 // Do the usual checks.
8407 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8408 return;
8409
8410 Diag(NBody->getSemiLoc(), DiagID);
8411 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8412}
8413
8414void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8415 const Stmt *PossibleBody) {
8416 assert(!CurrentInstantiationScope); // Ensured by caller
8417
8418 SourceLocation StmtLoc;
8419 const Stmt *Body;
8420 unsigned DiagID;
8421 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8422 StmtLoc = FS->getRParenLoc();
8423 Body = FS->getBody();
8424 DiagID = diag::warn_empty_for_body;
8425 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8426 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8427 Body = WS->getBody();
8428 DiagID = diag::warn_empty_while_body;
8429 } else
8430 return; // Neither `for' nor `while'.
8431
8432 // The body should be a null statement.
8433 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8434 if (!NBody)
8435 return;
8436
8437 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008438 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008439 return;
8440
8441 // Do the usual checks.
8442 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8443 return;
8444
8445 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8446 // noise level low, emit diagnostics only if for/while is followed by a
8447 // CompoundStmt, e.g.:
8448 // for (int i = 0; i < n; i++);
8449 // {
8450 // a(i);
8451 // }
8452 // or if for/while is followed by a statement with more indentation
8453 // than for/while itself:
8454 // for (int i = 0; i < n; i++);
8455 // a(i);
8456 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8457 if (!ProbableTypo) {
8458 bool BodyColInvalid;
8459 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8460 PossibleBody->getLocStart(),
8461 &BodyColInvalid);
8462 if (BodyColInvalid)
8463 return;
8464
8465 bool StmtColInvalid;
8466 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8467 S->getLocStart(),
8468 &StmtColInvalid);
8469 if (StmtColInvalid)
8470 return;
8471
8472 if (BodyCol > StmtCol)
8473 ProbableTypo = true;
8474 }
8475
8476 if (ProbableTypo) {
8477 Diag(NBody->getSemiLoc(), DiagID);
8478 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8479 }
8480}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008481
Richard Trieu36d0b2b2015-01-13 02:32:02 +00008482//===--- CHECK: Warn on self move with std::move. -------------------------===//
8483
8484/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8485void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8486 SourceLocation OpLoc) {
8487
8488 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8489 return;
8490
8491 if (!ActiveTemplateInstantiations.empty())
8492 return;
8493
8494 // Strip parens and casts away.
8495 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8496 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8497
8498 // Check for a call expression
8499 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8500 if (!CE || CE->getNumArgs() != 1)
8501 return;
8502
8503 // Check for a call to std::move
8504 const FunctionDecl *FD = CE->getDirectCallee();
8505 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8506 !FD->getIdentifier()->isStr("move"))
8507 return;
8508
8509 // Get argument from std::move
8510 RHSExpr = CE->getArg(0);
8511
8512 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8513 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8514
8515 // Two DeclRefExpr's, check that the decls are the same.
8516 if (LHSDeclRef && RHSDeclRef) {
8517 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8518 return;
8519 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8520 RHSDeclRef->getDecl()->getCanonicalDecl())
8521 return;
8522
8523 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8524 << LHSExpr->getSourceRange()
8525 << RHSExpr->getSourceRange();
8526 return;
8527 }
8528
8529 // Member variables require a different approach to check for self moves.
8530 // MemberExpr's are the same if every nested MemberExpr refers to the same
8531 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8532 // the base Expr's are CXXThisExpr's.
8533 const Expr *LHSBase = LHSExpr;
8534 const Expr *RHSBase = RHSExpr;
8535 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8536 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8537 if (!LHSME || !RHSME)
8538 return;
8539
8540 while (LHSME && RHSME) {
8541 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8542 RHSME->getMemberDecl()->getCanonicalDecl())
8543 return;
8544
8545 LHSBase = LHSME->getBase();
8546 RHSBase = RHSME->getBase();
8547 LHSME = dyn_cast<MemberExpr>(LHSBase);
8548 RHSME = dyn_cast<MemberExpr>(RHSBase);
8549 }
8550
8551 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8552 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8553 if (LHSDeclRef && RHSDeclRef) {
8554 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8555 return;
8556 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8557 RHSDeclRef->getDecl()->getCanonicalDecl())
8558 return;
8559
8560 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8561 << LHSExpr->getSourceRange()
8562 << RHSExpr->getSourceRange();
8563 return;
8564 }
8565
8566 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8567 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8568 << LHSExpr->getSourceRange()
8569 << RHSExpr->getSourceRange();
8570}
8571
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008572//===--- Layout compatibility ----------------------------------------------//
8573
8574namespace {
8575
8576bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8577
8578/// \brief Check if two enumeration types are layout-compatible.
8579bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8580 // C++11 [dcl.enum] p8:
8581 // Two enumeration types are layout-compatible if they have the same
8582 // underlying type.
8583 return ED1->isComplete() && ED2->isComplete() &&
8584 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8585}
8586
8587/// \brief Check if two fields are layout-compatible.
8588bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8589 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8590 return false;
8591
8592 if (Field1->isBitField() != Field2->isBitField())
8593 return false;
8594
8595 if (Field1->isBitField()) {
8596 // Make sure that the bit-fields are the same length.
8597 unsigned Bits1 = Field1->getBitWidthValue(C);
8598 unsigned Bits2 = Field2->getBitWidthValue(C);
8599
8600 if (Bits1 != Bits2)
8601 return false;
8602 }
8603
8604 return true;
8605}
8606
8607/// \brief Check if two standard-layout structs are layout-compatible.
8608/// (C++11 [class.mem] p17)
8609bool isLayoutCompatibleStruct(ASTContext &C,
8610 RecordDecl *RD1,
8611 RecordDecl *RD2) {
8612 // If both records are C++ classes, check that base classes match.
8613 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8614 // If one of records is a CXXRecordDecl we are in C++ mode,
8615 // thus the other one is a CXXRecordDecl, too.
8616 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8617 // Check number of base classes.
8618 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8619 return false;
8620
8621 // Check the base classes.
8622 for (CXXRecordDecl::base_class_const_iterator
8623 Base1 = D1CXX->bases_begin(),
8624 BaseEnd1 = D1CXX->bases_end(),
8625 Base2 = D2CXX->bases_begin();
8626 Base1 != BaseEnd1;
8627 ++Base1, ++Base2) {
8628 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8629 return false;
8630 }
8631 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8632 // If only RD2 is a C++ class, it should have zero base classes.
8633 if (D2CXX->getNumBases() > 0)
8634 return false;
8635 }
8636
8637 // Check the fields.
8638 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8639 Field2End = RD2->field_end(),
8640 Field1 = RD1->field_begin(),
8641 Field1End = RD1->field_end();
8642 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8643 if (!isLayoutCompatible(C, *Field1, *Field2))
8644 return false;
8645 }
8646 if (Field1 != Field1End || Field2 != Field2End)
8647 return false;
8648
8649 return true;
8650}
8651
8652/// \brief Check if two standard-layout unions are layout-compatible.
8653/// (C++11 [class.mem] p18)
8654bool isLayoutCompatibleUnion(ASTContext &C,
8655 RecordDecl *RD1,
8656 RecordDecl *RD2) {
8657 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008658 for (auto *Field2 : RD2->fields())
8659 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008660
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008661 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008662 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8663 I = UnmatchedFields.begin(),
8664 E = UnmatchedFields.end();
8665
8666 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008667 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008668 bool Result = UnmatchedFields.erase(*I);
8669 (void) Result;
8670 assert(Result);
8671 break;
8672 }
8673 }
8674 if (I == E)
8675 return false;
8676 }
8677
8678 return UnmatchedFields.empty();
8679}
8680
8681bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8682 if (RD1->isUnion() != RD2->isUnion())
8683 return false;
8684
8685 if (RD1->isUnion())
8686 return isLayoutCompatibleUnion(C, RD1, RD2);
8687 else
8688 return isLayoutCompatibleStruct(C, RD1, RD2);
8689}
8690
8691/// \brief Check if two types are layout-compatible in C++11 sense.
8692bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8693 if (T1.isNull() || T2.isNull())
8694 return false;
8695
8696 // C++11 [basic.types] p11:
8697 // If two types T1 and T2 are the same type, then T1 and T2 are
8698 // layout-compatible types.
8699 if (C.hasSameType(T1, T2))
8700 return true;
8701
8702 T1 = T1.getCanonicalType().getUnqualifiedType();
8703 T2 = T2.getCanonicalType().getUnqualifiedType();
8704
8705 const Type::TypeClass TC1 = T1->getTypeClass();
8706 const Type::TypeClass TC2 = T2->getTypeClass();
8707
8708 if (TC1 != TC2)
8709 return false;
8710
8711 if (TC1 == Type::Enum) {
8712 return isLayoutCompatible(C,
8713 cast<EnumType>(T1)->getDecl(),
8714 cast<EnumType>(T2)->getDecl());
8715 } else if (TC1 == Type::Record) {
8716 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8717 return false;
8718
8719 return isLayoutCompatible(C,
8720 cast<RecordType>(T1)->getDecl(),
8721 cast<RecordType>(T2)->getDecl());
8722 }
8723
8724 return false;
8725}
8726}
8727
8728//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8729
8730namespace {
8731/// \brief Given a type tag expression find the type tag itself.
8732///
8733/// \param TypeExpr Type tag expression, as it appears in user's code.
8734///
8735/// \param VD Declaration of an identifier that appears in a type tag.
8736///
8737/// \param MagicValue Type tag magic value.
8738bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8739 const ValueDecl **VD, uint64_t *MagicValue) {
8740 while(true) {
8741 if (!TypeExpr)
8742 return false;
8743
8744 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8745
8746 switch (TypeExpr->getStmtClass()) {
8747 case Stmt::UnaryOperatorClass: {
8748 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8749 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8750 TypeExpr = UO->getSubExpr();
8751 continue;
8752 }
8753 return false;
8754 }
8755
8756 case Stmt::DeclRefExprClass: {
8757 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8758 *VD = DRE->getDecl();
8759 return true;
8760 }
8761
8762 case Stmt::IntegerLiteralClass: {
8763 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8764 llvm::APInt MagicValueAPInt = IL->getValue();
8765 if (MagicValueAPInt.getActiveBits() <= 64) {
8766 *MagicValue = MagicValueAPInt.getZExtValue();
8767 return true;
8768 } else
8769 return false;
8770 }
8771
8772 case Stmt::BinaryConditionalOperatorClass:
8773 case Stmt::ConditionalOperatorClass: {
8774 const AbstractConditionalOperator *ACO =
8775 cast<AbstractConditionalOperator>(TypeExpr);
8776 bool Result;
8777 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8778 if (Result)
8779 TypeExpr = ACO->getTrueExpr();
8780 else
8781 TypeExpr = ACO->getFalseExpr();
8782 continue;
8783 }
8784 return false;
8785 }
8786
8787 case Stmt::BinaryOperatorClass: {
8788 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8789 if (BO->getOpcode() == BO_Comma) {
8790 TypeExpr = BO->getRHS();
8791 continue;
8792 }
8793 return false;
8794 }
8795
8796 default:
8797 return false;
8798 }
8799 }
8800}
8801
8802/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8803///
8804/// \param TypeExpr Expression that specifies a type tag.
8805///
8806/// \param MagicValues Registered magic values.
8807///
8808/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8809/// kind.
8810///
8811/// \param TypeInfo Information about the corresponding C type.
8812///
8813/// \returns true if the corresponding C type was found.
8814bool GetMatchingCType(
8815 const IdentifierInfo *ArgumentKind,
8816 const Expr *TypeExpr, const ASTContext &Ctx,
8817 const llvm::DenseMap<Sema::TypeTagMagicValue,
8818 Sema::TypeTagData> *MagicValues,
8819 bool &FoundWrongKind,
8820 Sema::TypeTagData &TypeInfo) {
8821 FoundWrongKind = false;
8822
8823 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008824 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008825
8826 uint64_t MagicValue;
8827
8828 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8829 return false;
8830
8831 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008832 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008833 if (I->getArgumentKind() != ArgumentKind) {
8834 FoundWrongKind = true;
8835 return false;
8836 }
8837 TypeInfo.Type = I->getMatchingCType();
8838 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8839 TypeInfo.MustBeNull = I->getMustBeNull();
8840 return true;
8841 }
8842 return false;
8843 }
8844
8845 if (!MagicValues)
8846 return false;
8847
8848 llvm::DenseMap<Sema::TypeTagMagicValue,
8849 Sema::TypeTagData>::const_iterator I =
8850 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8851 if (I == MagicValues->end())
8852 return false;
8853
8854 TypeInfo = I->second;
8855 return true;
8856}
8857} // unnamed namespace
8858
8859void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8860 uint64_t MagicValue, QualType Type,
8861 bool LayoutCompatible,
8862 bool MustBeNull) {
8863 if (!TypeTagForDatatypeMagicValues)
8864 TypeTagForDatatypeMagicValues.reset(
8865 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8866
8867 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8868 (*TypeTagForDatatypeMagicValues)[Magic] =
8869 TypeTagData(Type, LayoutCompatible, MustBeNull);
8870}
8871
8872namespace {
8873bool IsSameCharType(QualType T1, QualType T2) {
8874 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8875 if (!BT1)
8876 return false;
8877
8878 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8879 if (!BT2)
8880 return false;
8881
8882 BuiltinType::Kind T1Kind = BT1->getKind();
8883 BuiltinType::Kind T2Kind = BT2->getKind();
8884
8885 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8886 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8887 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8888 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8889}
8890} // unnamed namespace
8891
8892void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8893 const Expr * const *ExprArgs) {
8894 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8895 bool IsPointerAttr = Attr->getIsPointer();
8896
8897 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8898 bool FoundWrongKind;
8899 TypeTagData TypeInfo;
8900 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8901 TypeTagForDatatypeMagicValues.get(),
8902 FoundWrongKind, TypeInfo)) {
8903 if (FoundWrongKind)
8904 Diag(TypeTagExpr->getExprLoc(),
8905 diag::warn_type_tag_for_datatype_wrong_kind)
8906 << TypeTagExpr->getSourceRange();
8907 return;
8908 }
8909
8910 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8911 if (IsPointerAttr) {
8912 // Skip implicit cast of pointer to `void *' (as a function argument).
8913 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008914 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008915 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008916 ArgumentExpr = ICE->getSubExpr();
8917 }
8918 QualType ArgumentType = ArgumentExpr->getType();
8919
8920 // Passing a `void*' pointer shouldn't trigger a warning.
8921 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8922 return;
8923
8924 if (TypeInfo.MustBeNull) {
8925 // Type tag with matching void type requires a null pointer.
8926 if (!ArgumentExpr->isNullPointerConstant(Context,
8927 Expr::NPC_ValueDependentIsNotNull)) {
8928 Diag(ArgumentExpr->getExprLoc(),
8929 diag::warn_type_safety_null_pointer_required)
8930 << ArgumentKind->getName()
8931 << ArgumentExpr->getSourceRange()
8932 << TypeTagExpr->getSourceRange();
8933 }
8934 return;
8935 }
8936
8937 QualType RequiredType = TypeInfo.Type;
8938 if (IsPointerAttr)
8939 RequiredType = Context.getPointerType(RequiredType);
8940
8941 bool mismatch = false;
8942 if (!TypeInfo.LayoutCompatible) {
8943 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8944
8945 // C++11 [basic.fundamental] p1:
8946 // Plain char, signed char, and unsigned char are three distinct types.
8947 //
8948 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8949 // char' depending on the current char signedness mode.
8950 if (mismatch)
8951 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8952 RequiredType->getPointeeType())) ||
8953 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8954 mismatch = false;
8955 } else
8956 if (IsPointerAttr)
8957 mismatch = !isLayoutCompatible(Context,
8958 ArgumentType->getPointeeType(),
8959 RequiredType->getPointeeType());
8960 else
8961 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8962
8963 if (mismatch)
8964 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008965 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008966 << TypeInfo.LayoutCompatible << RequiredType
8967 << ArgumentExpr->getSourceRange()
8968 << TypeTagExpr->getSourceRange();
8969}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008970