blob: 5a0d8d4a5385b095c5f911d195489f7664de99bf [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattner59907c42007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070035#include "llvm/ADT/STLExtras.h"
Richard Smith0e218972013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000040#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000043
Chris Lattner60800082009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000048}
49
John McCall8e10f3b2011-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 Lerougee5939212012-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 Lerouge77f68bb2011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerougee5939212012-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 Lerouge77f68bb2011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith5154dce2013-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
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700104 ExprResult Arg(TheCall->getArg(0));
Richard Smith5154dce2013-07-11 02:27:57 +0000105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700109 TheCall->setArg(0, Arg.get());
Richard Smith5154dce2013-07-11 02:27:57 +0000110 TheCall->setType(ResultType);
111 return false;
112}
113
Stephen Hines176edba2014-12-01 14:53:08 -0800114static 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
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700142static 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
187 QualType ReturnTy = CE->getCallReturnType(S.Context);
188 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
205static 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 McCall60d7b3a2010-08-24 06:29:42 +0000227ExprResult
Stephen Hines176edba2014-12-01 14:53:08 -0800228Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
229 CallExpr *TheCall) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700230 ExprResult TheCallResult(TheCall);
Douglas Gregor2def4832008-11-17 20:34:05 +0000231
Chris Lattner946928f2010-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 Carlssond406bf02009-08-16 01:56:34 +0000250 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000251 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000252 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000253 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000254 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000255 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000256 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000257 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000258 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000259 if (SemaBuiltinVAStart(TheCall))
260 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000261 break;
Stephen Hines176edba2014-12-01 14:53:08 -0800262 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 Lattner1b9a0792007-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 Redl0eb23302009-01-19 00:08:26 +0000282 if (SemaBuiltinUnorderedCompare(TheCall))
283 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000284 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000285 case Builtin::BI__builtin_fpclassify:
286 if (SemaBuiltinFPClassification(TheCall, 6))
287 return ExprError();
288 break;
Eli Friedman9ac6f622009-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 Kramer3b1e26b2010-02-16 10:07:31 +0000294 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000295 return ExprError();
296 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000297 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-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 Dunbar4493f792008-07-21 22:59:13 +0000301 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000302 if (SemaBuiltinPrefetch(TheCall))
303 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000304 break;
Stephen Hines176edba2014-12-01 14:53:08 -0800305 case Builtin::BI__assume:
306 case Builtin::BI__builtin_assume:
307 if (SemaBuiltinAssume(TheCall))
308 return ExprError();
309 break;
310 case Builtin::BI__builtin_assume_aligned:
311 if (SemaBuiltinAssumeAligned(TheCall))
312 return ExprError();
313 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000314 case Builtin::BI__builtin_object_size:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700315 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000316 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000317 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000318 case Builtin::BI__builtin_longjmp:
319 if (SemaBuiltinLongjmp(TheCall))
320 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000321 break;
John McCall8e10f3b2011-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 Lattner75c29a02010-10-12 17:47:42 +0000327 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000328 if (checkArgCount(*this, TheCall, 1)) return true;
329 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000330 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000331 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-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 Lattner5caa3702009-05-08 06:58:22 +0000337 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-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 Lattner5caa3702009-05-08 06:58:22 +0000343 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-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 Lattner5caa3702009-05-08 06:58:22 +0000349 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-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 Lattner5caa3702009-05-08 06:58:22 +0000355 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-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:
Stephen Hines176edba2014-12-01 14:53:08 -0800361 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 Lattner5caa3702009-05-08 06:58:22 +0000367 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-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 Lattner5caa3702009-05-08 06:58:22 +0000373 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-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 Lattner5caa3702009-05-08 06:58:22 +0000379 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-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 Lattner5caa3702009-05-08 06:58:22 +0000385 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-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 Lattner5caa3702009-05-08 06:58:22 +0000391 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-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:
Stephen Hines176edba2014-12-01 14:53:08 -0800397 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 Lattner5caa3702009-05-08 06:58:22 +0000403 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-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 Lattner5caa3702009-05-08 06:58:22 +0000409 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-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 Lattner5caa3702009-05-08 06:58:22 +0000415 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-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 Lattner5caa3702009-05-08 06:58:22 +0000421 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-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 Lattner23aa9c82011-04-09 03:57:26 +0000427 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-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 Kramer3fe198b2012-08-23 21:35:17 +0000433 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000434#define BUILTIN(ID, TYPE, ATTRS)
435#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
436 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000437 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000438#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000439 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000440 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000441 return ExprError();
442 break;
Richard Smith5154dce2013-07-11 02:27:57 +0000443 case Builtin::BI__builtin_addressof:
444 if (SemaBuiltinAddressof(*this, TheCall))
445 return ExprError();
446 break;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700447 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;
Stephen Hines176edba2014-12-01 14:53:08 -0800461
462 // check secure string manipulation functions where overflows
463 // are detectable at compile time
464 case Builtin::BI__builtin___memcpy_chk:
465 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;
474 case Builtin::BI__builtin___memccpy_chk:
475 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
476 break;
477 case Builtin::BI__builtin___snprintf_chk:
478 case Builtin::BI__builtin___vsnprintf_chk:
479 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
480 break;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700481
482 case Builtin::BI__builtin_call_with_static_chain:
483 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
484 return ExprError();
485 break;
486
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 Begeman26a31422010-06-08 02:47:44 +0000502 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700503
Nate Begeman26a31422010-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 Gregorbcfd1f52011-09-02 00:18:52 +0000507 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000508 case llvm::Triple::arm:
Stephen Hines651f13c2014-04-23 16:59:28 -0700509 case llvm::Triple::armeb:
Nate Begeman26a31422010-06-08 02:47:44 +0000510 case llvm::Triple::thumb:
Stephen Hines651f13c2014-04-23 16:59:28 -0700511 case llvm::Triple::thumbeb:
Nate Begeman26a31422010-06-08 02:47:44 +0000512 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
513 return ExprError();
514 break;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000515 case llvm::Triple::aarch64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700516 case llvm::Triple::aarch64_be:
Tim Northoverb793f0d2013-08-01 09:23:19 +0000517 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
518 return ExprError();
519 break;
Simon Atanasyanfad0a322012-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;
Stephen Hines651f13c2014-04-23 16:59:28 -0700527 case llvm::Triple::x86:
528 case llvm::Triple::x86_64:
529 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
530 return ExprError();
531 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000532 default:
533 break;
534 }
535 }
536
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000537 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000538}
539
Nate Begeman61eecf52010-06-14 05:21:25 +0000540// Get the valid immediate range for the specified NEON type code.
Stephen Hines651f13c2014-04-23 16:59:28 -0700541static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000542 NeonTypeFlags Type(t);
Stephen Hines651f13c2014-04-23 16:59:28 -0700543 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilsonda95f732011-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 Qin624bb5e2013-11-14 03:29:16 +0000554 case NeonTypeFlags::Poly64:
Bob Wilsonda95f732011-11-08 01:16:11 +0000555 return shift ? 63 : (1 << IsQuad) - 1;
Stephen Hines651f13c2014-04-23 16:59:28 -0700556 case NeonTypeFlags::Poly128:
557 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilsonda95f732011-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 Northoverb793f0d2013-08-01 09:23:19 +0000564 case NeonTypeFlags::Float64:
565 assert(!shift && "cannot shift float types!");
566 return (1 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000567 }
David Blaikie7530c032012-01-17 06:56:22 +0000568 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000569}
570
Bob Wilson6f9f03e2011-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 Qin624bb5e2013-11-14 03:29:16 +0000574static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Stephen Hines651f13c2014-04-23 16:59:28 -0700575 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilson6f9f03e2011-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:
Stephen Hines651f13c2014-04-23 16:59:28 -0700584 if (IsInt64Long)
585 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
586 else
587 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
588 : Context.LongLongTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000589 case NeonTypeFlags::Poly8:
Stephen Hines651f13c2014-04-23 16:59:28 -0700590 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000591 case NeonTypeFlags::Poly16:
Stephen Hines651f13c2014-04-23 16:59:28 -0700592 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qin624bb5e2013-11-14 03:29:16 +0000593 case NeonTypeFlags::Poly64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700594 return Context.UnsignedLongTy;
595 case NeonTypeFlags::Poly128:
596 break;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000597 case NeonTypeFlags::Float16:
Kevin Qin624bb5e2013-11-14 03:29:16 +0000598 return Context.HalfTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000599 case NeonTypeFlags::Float32:
600 return Context.FloatTy;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000601 case NeonTypeFlags::Float64:
602 return Context.DoubleTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000603 }
David Blaikie7530c032012-01-17 06:56:22 +0000604 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000605}
606
Stephen Hines651f13c2014-04-23 16:59:28 -0700607bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northoverb793f0d2013-08-01 09:23:19 +0000608 llvm::APSInt Result;
Tim Northoverb793f0d2013-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) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700614#define GET_NEON_OVERLOAD_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000615#include "clang/Basic/arm_neon.inc"
Stephen Hines651f13c2014-04-23 16:59:28 -0700616#undef GET_NEON_OVERLOAD_CHECK
Tim Northoverb793f0d2013-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.
Stephen Hines651f13c2014-04-23 16:59:28 -0700621 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northoverb793f0d2013-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)
Stephen Hines651f13c2014-04-23 16:59:28 -0700629 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northoverb793f0d2013-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();
Stephen Hines651f13c2014-04-23 16:59:28 -0700639
640 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Stephen Hines176edba2014-12-01 14:53:08 -0800641 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Stephen Hines651f13c2014-04-23 16:59:28 -0700642 bool IsInt64Long =
643 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
644 QualType EltTy =
645 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northoverb793f0d2013-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;
Stephen Hines651f13c2014-04-23 16:59:28 -0700664#define GET_NEON_IMMEDIATE_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000665#include "clang/Basic/arm_neon.inc"
Stephen Hines651f13c2014-04-23 16:59:28 -0700666#undef GET_NEON_IMMEDIATE_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000667 }
Tim Northoverb793f0d2013-08-01 09:23:19 +0000668
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700669 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Stephen Hines651f13c2014-04-23 16:59:28 -0700670}
671
672bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
673 unsigned MaxWidth) {
Tim Northover09df2b02013-07-16 09:47:53 +0000674 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700675 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Stephen Hines651f13c2014-04-23 16:59:28 -0700676 BuiltinID == ARM::BI__builtin_arm_strex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700677 BuiltinID == ARM::BI__builtin_arm_stlex ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700678 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700679 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
680 BuiltinID == AArch64::BI__builtin_arm_strex ||
681 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover09df2b02013-07-16 09:47:53 +0000682 "unexpected ARM builtin");
Stephen Hines651f13c2014-04-23 16:59:28 -0700683 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700684 BuiltinID == ARM::BI__builtin_arm_ldaex ||
685 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
686 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover09df2b02013-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;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700702 PointerArg = PointerArgRes.get();
Tim Northover09df2b02013-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;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700734 PointerArg = PointerArgRes.get();
Tim Northover09df2b02013-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.
Stephen Hines651f13c2014-04-23 16:59:28 -0700747 if (Context.getTypeSize(ValType) > MaxWidth) {
748 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover09df2b02013-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 Northover09df2b02013-07-16 09:47:53 +0000781 TheCall->setArg(0, ValArg.get());
Tim Northovera6306fc2013-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 Northover09df2b02013-07-16 09:47:53 +0000786 return false;
787}
788
Nate Begeman26a31422010-06-08 02:47:44 +0000789bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000790 llvm::APSInt Result;
791
Tim Northover09df2b02013-07-16 09:47:53 +0000792 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700793 BuiltinID == ARM::BI__builtin_arm_ldaex ||
794 BuiltinID == ARM::BI__builtin_arm_strex ||
795 BuiltinID == ARM::BI__builtin_arm_stlex) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700796 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover09df2b02013-07-16 09:47:53 +0000797 }
798
Stephen Hines176edba2014-12-01 14:53:08 -0800799 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
800 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
801 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
802 }
803
Stephen Hines651f13c2014-04-23 16:59:28 -0700804 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
805 return true;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000806
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700807 // For intrinsics which take an immediate value as part of the instruction,
808 // range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000809 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000810 switch (BuiltinID) {
811 default: return false;
Nate Begemanbb37f502010-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 Begeman99c40bb2010-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 Zhao186b26d2013-11-12 21:42:50 +0000816 case ARM::BI__builtin_arm_dmb:
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700817 case ARM::BI__builtin_arm_dsb:
Stephen Hines176edba2014-12-01 14:53:08 -0800818 case ARM::BI__builtin_arm_isb:
819 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700820 }
Nate Begeman0d15c532010-06-13 04:47:52 +0000821
Nate Begeman99c40bb2010-08-03 21:32:34 +0000822 // FIXME: VFP Intrinsics should error if VFP not present.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700823 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssond406bf02009-08-16 01:56:34 +0000824}
Daniel Dunbarde454282008-10-02 18:44:07 +0000825
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700826bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Stephen Hines651f13c2014-04-23 16:59:28 -0700827 CallExpr *TheCall) {
828 llvm::APSInt Result;
829
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700830 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700831 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
832 BuiltinID == AArch64::BI__builtin_arm_strex ||
833 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700834 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
835 }
836
Stephen Hines176edba2014-12-01 14:53:08 -0800837 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
Stephen Hines651f13c2014-04-23 16:59:28 -0700844 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
845 return true;
846
Stephen Hines176edba2014-12-01 14:53:08 -0800847 // 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
857 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Stephen Hines651f13c2014-04-23 16:59:28 -0700858}
859
Simon Atanasyanfad0a322012-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 Atanasyanbe22cb82012-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;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700871 }
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000872
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700873 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000874}
875
Stephen Hines651f13c2014-04-23 16:59:28 -0700876bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700877 unsigned i = 0, l = 0, u = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700878 switch (BuiltinID) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700879 default: return false;
880 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
881 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:
888 case X86::BI__builtin_ia32_insert128i256: i = 2, l = 0; u = 1; break;
889 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
890 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;
894 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;
918 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;
932 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;
Stephen Hines651f13c2014-04-23 16:59:28 -0700940 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700941 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Stephen Hines651f13c2014-04-23 16:59:28 -0700942}
943
Richard Smith831421f2012-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 Carlssond406bf02009-08-16 01:56:34 +0000953
Richard Smith831421f2012-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 Stump1eb44332009-09-09 15:08:12 +0000966
Stephen Hines651f13c2014-04-23 16:59:28 -0700967/// 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) {
972 // As a special case, transparent unions initialized with zero are
973 // considered null for the purposes of the nonnull attribute.
974 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
975 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
976 if (const CompoundLiteralExpr *CLE =
977 dyn_cast<CompoundLiteralExpr>(Expr))
978 if (const InitListExpr *ILE =
979 dyn_cast<InitListExpr>(CLE->getInitializer()))
980 Expr = ILE->getInit(0);
981 }
982
983 bool Result;
984 return (!Expr->isValueDependent() &&
985 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
986 !Result);
987}
988
989static void CheckNonNullArgument(Sema &S,
990 const Expr *ArgExpr,
991 SourceLocation CallSiteLoc) {
992 if (CheckNonNullExpr(S, ArgExpr))
993 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
994}
995
Stephen Hines176edba2014-12-01 14:53:08 -0800996bool 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}
1005/// \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) {
1012 unsigned Idx = 0;
1013 bool Format = false;
1014 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1015 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
1016 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 }
1025 }
1026 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();
1044 }
1045}
1046
Stephen Hines651f13c2014-04-23 16:59:28 -07001047static void CheckNonNullArguments(Sema &S,
1048 const NamedDecl *FDecl,
Stephen Hines176edba2014-12-01 14:53:08 -08001049 ArrayRef<const Expr *> Args,
Stephen Hines651f13c2014-04-23 16:59:28 -07001050 SourceLocation CallSiteLoc) {
1051 // Check the attributes attached to the method/function itself.
Stephen Hines176edba2014-12-01 14:53:08 -08001052 llvm::SmallBitVector NonNullArgs;
Stephen Hines651f13c2014-04-23 16:59:28 -07001053 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Stephen Hines176edba2014-12-01 14:53:08 -08001054 if (!NonNull->args_size()) {
1055 // Easy case: all pointer arguments are nonnull.
1056 for (const auto *Arg : Args)
1057 if (S.isValidPointerAttrType(Arg->getType()))
1058 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 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001069 }
1070
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
Stephen Hines176edba2014-12-01 14:53:08 -08001078 unsigned ArgIndex = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -07001079 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Stephen Hines176edba2014-12-01 14:53:08 -08001080 I != E; ++I, ++ArgIndex) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001081 const ParmVarDecl *PVD = *I;
Stephen Hines176edba2014-12-01 14:53:08 -08001082 if (PVD->hasAttr<NonNullAttr>() ||
1083 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1084 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Stephen Hines651f13c2014-04-23 16:59:28 -07001085 }
Stephen Hines176edba2014-12-01 14:53:08 -08001086
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);
Stephen Hines651f13c2014-04-23 16:59:28 -07001091}
1092
Richard Smith831421f2012-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.
Stephen Hines651f13c2014-04-23 16:59:28 -07001095void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1096 unsigned NumParams, bool IsMemberFunction,
1097 SourceLocation Loc, SourceRange Range,
Richard Smith831421f2012-06-25 20:30:08 +00001098 VariadicCallType CallType) {
Richard Smith0e218972013-08-05 18:49:43 +00001099 // FIXME: We should check as much as we can in the template definition.
Jordan Rose66360e22012-10-02 01:49:54 +00001100 if (CurContext->isDependentContext())
1101 return;
Daniel Dunbarde454282008-10-02 18:44:07 +00001102
Ted Kremenekc82faca2010-09-09 04:33:05 +00001103 // Printf and scanf checking.
Richard Smith0e218972013-08-05 18:49:43 +00001104 llvm::SmallBitVector CheckedVarArgs;
1105 if (FDecl) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001106 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer541a28f2013-08-09 09:39:17 +00001107 // Only create vector if there are format attributes.
1108 CheckedVarArgs.resize(Args.size());
1109
Stephen Hines651f13c2014-04-23 16:59:28 -07001110 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramer47abb252013-08-08 11:08:26 +00001111 CheckedVarArgs);
Benjamin Kramer541a28f2013-08-09 09:39:17 +00001112 }
Richard Smith0e218972013-08-05 18:49:43 +00001113 }
Richard Smith831421f2012-06-25 20:30:08 +00001114
1115 // Refuse POD arguments that weren't caught by the format string
1116 // checks above.
Richard Smith0e218972013-08-05 18:49:43 +00001117 if (CallType != VariadicDoesNotApply) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001118 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +00001119 // Args[ArgIdx] can be null in malformed code.
Richard Smith0e218972013-08-05 18:49:43 +00001120 if (const Expr *Arg = Args[ArgIdx]) {
1121 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1122 checkVariadicArgument(Arg, CallType);
1123 }
Ted Kremenek0234bfa2012-10-11 19:06:43 +00001124 }
Richard Smith0e218972013-08-05 18:49:43 +00001125 }
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Richard Trieu0538f0e2013-06-22 00:20:41 +00001127 if (FDecl) {
Stephen Hines176edba2014-12-01 14:53:08 -08001128 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00001129
Richard Trieu0538f0e2013-06-22 00:20:41 +00001130 // Type safety checking.
Stephen Hines651f13c2014-04-23 16:59:28 -07001131 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1132 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00001133 }
Richard Smith831421f2012-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 Gribenko1c030e92013-01-13 20:46:02 +00001138void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1139 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +00001140 const FunctionProtoType *Proto,
1141 SourceLocation Loc) {
1142 VariadicCallType CallType =
1143 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Stephen Hines651f13c2014-04-23 16:59:28 -07001144 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith831421f2012-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 Friedman2edcde82012-10-11 00:30:58 +00001152 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1153 isa<CXXMethodDecl>(FDecl);
1154 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1155 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +00001156 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1157 TheCall->getCallee());
Stephen Hines651f13c2014-04-23 16:59:28 -07001158 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +00001159 Expr** Args = TheCall->getArgs();
1160 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +00001161 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-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 }
Stephen Hines176edba2014-12-01 14:53:08 -08001168 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith831421f2012-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 Redl0eb23302009-01-19 00:08:26 +00001177
Stephen Hines651f13c2014-04-23 16:59:28 -07001178 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Stephen Hines176edba2014-12-01 14:53:08 -08001179 if (getLangOpts().ObjC1)
1180 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Stephen Hines651f13c2014-04-23 16:59:28 -07001181
Anna Zaks0a151a12012-01-17 00:37:07 +00001182 unsigned CMId = FDecl->getMemoryFunctionKind();
1183 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +00001184 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00001185
Anna Zaksd9b859a2012-01-13 21:52:01 +00001186 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +00001187 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00001188 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +00001189 else if (CMId == Builtin::BIstrncat)
1190 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +00001191 else
Anna Zaks0a151a12012-01-17 00:37:07 +00001192 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001193
Anders Carlssond406bf02009-08-16 01:56:34 +00001194 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001195}
1196
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001197bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +00001198 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +00001199 VariadicCallType CallType =
1200 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001201
Dmitri Gribenko287f24d2013-05-05 19:42:09 +00001202 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +00001203 /*IsMemberFunction=*/false,
1204 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001205
1206 return false;
1207}
1208
Richard Trieuf462b012013-06-20 21:03:13 +00001209bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1210 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +00001211 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1212 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +00001213 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Fariborz Jahanian725165f2009-05-18 21:05:18 +00001215 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +00001216 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +00001217 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Richard Trieuf462b012013-06-20 21:03:13 +00001219 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +00001220 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +00001221 CallType = VariadicDoesNotApply;
1222 } else if (Ty->isBlockPointerType()) {
1223 CallType = VariadicBlock;
1224 } else { // Ty->isFunctionPointerType()
1225 CallType = VariadicFunction;
1226 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001227 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +00001228
Stephen Hines176edba2014-12-01 14:53:08 -08001229 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1230 TheCall->getNumArgs()),
Stephen Hines651f13c2014-04-23 16:59:28 -07001231 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith831421f2012-06-25 20:30:08 +00001232 TheCall->getCallee()->getSourceRange(), CallType);
Stephen Hines651f13c2014-04-23 16:59:28 -07001233
Anders Carlssond406bf02009-08-16 01:56:34 +00001234 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +00001235}
1236
Richard Trieu0538f0e2013-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) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001240 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu0538f0e2013-06-22 00:20:41 +00001241 TheCall->getCallee());
Stephen Hines651f13c2014-04-23 16:59:28 -07001242 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu0538f0e2013-06-22 00:20:41 +00001243
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001244 checkCall(/*FDecl=*/nullptr,
Stephen Hines176edba2014-12-01 14:53:08 -08001245 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Stephen Hines651f13c2014-04-23 16:59:28 -07001246 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu0538f0e2013-06-22 00:20:41 +00001247 TheCall->getCallee()->getSourceRange(), CallType);
1248
1249 return false;
1250}
1251
Stephen Hines651f13c2014-04-23 16:59:28 -07001252static 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 Smithff34d402012-04-12 05:08:17 +00001279ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1280 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +00001281 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1282 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +00001283
Richard Smithff34d402012-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 Friedman276b0612011-10-11 02:20:01 +00001311
Richard Smithff34d402012-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 Smith51b92402012-04-13 06:31:38 +00001354 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-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 Smith51b92402012-04-13 06:31:38 +00001358 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-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 Friedman276b0612011-10-11 02:20:01 +00001384 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +00001385 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +00001386 << TheCall->getCallee()->getSourceRange();
1387 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +00001388 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1389 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +00001390 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +00001391 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +00001392 << TheCall->getCallee()->getSourceRange();
1393 return ExprError();
1394 }
1395
Richard Smithff34d402012-04-12 05:08:17 +00001396 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001397 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +00001398 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1399 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1400 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +00001401 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +00001402 << Ptr->getType() << Ptr->getSourceRange();
1403 return ExprError();
1404 }
1405
Richard Smithff34d402012-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 Smithbc57b102012-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 Smithff34d402012-04-12 05:08:17 +00001420 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00001421 }
Eli Friedman276b0612011-10-11 02:20:01 +00001422
Richard Smithff34d402012-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 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001436 if (IsC11 && ValType->isPointerType() &&
1437 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1438 diag::err_incomplete_type)) {
1439 return ExprError();
1440 }
Richard Smithff34d402012-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 Friedman276b0612011-10-11 02:20:01 +00001444 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +00001445 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1446 return ExprError();
1447 }
1448
Eli Friedmana3d727b2013-09-11 03:49:34 +00001449 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1450 !AtomTy->isScalarType()) {
Richard Smithff34d402012-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 Friedman276b0612011-10-11 02:20:01 +00001454 << Ptr->getType() << Ptr->getSourceRange();
1455 return ExprError();
1456 }
1457
Richard Smithff34d402012-04-12 05:08:17 +00001458 // FIXME: For any builtin other than a load, the ValType must not be
1459 // const-qualified.
Eli Friedman276b0612011-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 Smithff34d402012-04-12 05:08:17 +00001470 // FIXME: Can this happen? By this point, ValType should be known
1471 // to be trivially copyable.
Eli Friedman276b0612011-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 Smithff34d402012-04-12 05:08:17 +00001478 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001479 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001480 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001481 ResultType = Context.BoolTy;
1482
Richard Smithff34d402012-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 Friedman276b0612011-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 Smithff34d402012-04-12 05:08:17 +00001492 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001493 QualType Ty;
Richard Smithff34d402012-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 Friedman276b0612011-10-11 02:20:01 +00001521 } else {
1522 // The order(s) are always converted to int.
1523 Ty = Context.IntTy;
1524 }
Richard Smithff34d402012-04-12 05:08:17 +00001525
Eli Friedman276b0612011-10-11 02:20:01 +00001526 InitializedEntity Entity =
1527 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001528 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-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 Smithff34d402012-04-12 05:08:17 +00001535 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001536 SmallVector<Expr*, 5> SubExprs;
1537 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001538 switch (Form) {
1539 case Init:
1540 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001541 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-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 Friedmandfa64ba2011-10-14 22:48:56 +00001549 SubExprs.push_back(TheCall->getArg(2)); // Order
1550 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-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 Friedmandfa64ba2011-10-14 22:48:56 +00001559 SubExprs.push_back(TheCall->getArg(3)); // Order
1560 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001561 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001562 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-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 Friedman276b0612011-10-11 02:20:01 +00001571 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001572
1573 if (SubExprs.size() >= 2 && Form != Init) {
1574 llvm::APSInt Result(32);
1575 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1576 !isValidOrderingForOp(Result.getSExtValue(), Op))
1577 Diag(SubExprs[1]->getLocStart(),
1578 diag::warn_atomic_op_has_invalid_memory_order)
1579 << SubExprs[1]->getSourceRange();
1580 }
1581
Fariborz Jahanian538bbe52013-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 Friedmandfa64ba2011-10-14 22:48:56 +00001591
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001592 return AE;
Eli Friedman276b0612011-10-11 02:20:01 +00001593}
1594
1595
John McCall5f8d6042011-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
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001616 E->setArg(ArgIndex, Arg.get());
John McCall5f8d6042011-08-27 01:09:30 +00001617 return false;
1618}
1619
Chris Lattner5caa3702009-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 McCall60d7b3a2010-08-24 06:29:42 +00001628ExprResult
1629Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001630 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-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 Carruthd2014572010-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 Stump1eb44332009-09-09 15:08:12 +00001641
Chris Lattner5caa3702009-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 Carruthd2014572010-07-09 18:59:35 +00001646 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001647 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001648 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1649 if (FirstArgResult.isInvalid())
1650 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001651 FirstArg = FirstArgResult.get();
Eli Friedman8c382062012-01-23 02:35:22 +00001652 TheCall->setArg(0, FirstArg);
1653
John McCallf85e1932011-06-15 23:02:42 +00001654 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1655 if (!pointerType) {
Chandler Carruthd2014572010-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 Stump1eb44332009-09-09 15:08:12 +00001660
John McCallf85e1932011-06-15 23:02:42 +00001661 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001662 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-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 Lattner5caa3702009-05-08 06:58:22 +00001668
John McCallf85e1932011-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 Kyrtzidisb8b03132011-06-24 00:08:59 +00001678 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001679 << ValType << FirstArg->getSourceRange();
1680 return ExprError();
1681 }
1682
John McCallb45ae252011-10-05 07:41:44 +00001683 // Strip any qualifiers off ValType.
1684 ValType = ValType.getUnqualifiedType();
1685
Chandler Carruth8d13d222010-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 Lattner5caa3702009-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 Stump1eb44332009-09-09 15:08:12 +00001696
Chris Lattner5caa3702009-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),
Stephen Hines176edba2014-12-01 14:53:08 -08001703 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Chris Lattner5caa3702009-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),
Stephen Hines176edba2014-12-01 14:53:08 -08001710 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Chris Lattner5caa3702009-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 Lattner23aa9c82011-04-09 03:57:26 +00001715 BUILTIN_ROW(__sync_lock_release),
1716 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001717 };
Mike Stump1eb44332009-09-09 15:08:12 +00001718#undef BUILTIN_ROW
1719
Chris Lattner5caa3702009-05-08 06:58:22 +00001720 // Determine the index of the size.
1721 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001722 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-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 Carruthd2014572010-07-09 18:59:35 +00001729 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1730 << FirstArg->getType() << FirstArg->getSourceRange();
1731 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001732 }
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Chris Lattner5caa3702009-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 Gregor7814e6d2009-09-12 00:22:50 +00001738 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001739 unsigned BuiltinIndex, NumFixed = 1;
Stephen Hines176edba2014-12-01 14:53:08 -08001740 bool WarnAboutSemanticsChange = false;
Chris Lattner5caa3702009-05-08 06:58:22 +00001741 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001742 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-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 Stump1eb44332009-09-09 15:08:12 +00001778
Douglas Gregora9766412011-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
Stephen Hines176edba2014-12-01 14:53:08 -08001788 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 Gregora9766412011-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:
Stephen Hines176edba2014-12-01 14:53:08 -08001804 BuiltinIndex = 6;
Douglas Gregora9766412011-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:
Stephen Hines176edba2014-12-01 14:53:08 -08001813 BuiltinIndex = 7;
Douglas Gregora9766412011-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:
Stephen Hines176edba2014-12-01 14:53:08 -08001822 BuiltinIndex = 8;
Douglas Gregora9766412011-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:
Stephen Hines176edba2014-12-01 14:53:08 -08001831 BuiltinIndex = 9;
Douglas Gregora9766412011-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:
Stephen Hines176edba2014-12-01 14:53:08 -08001840 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 Gregora9766412011-11-28 16:30:08 +00001851 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Chris Lattner5caa3702009-05-08 06:58:22 +00001853 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-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:
Stephen Hines176edba2014-12-01 14:53:08 -08001859 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +00001860 NumFixed = 2;
1861 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001862
Chris Lattner5caa3702009-05-08 06:58:22 +00001863 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-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:
Stephen Hines176edba2014-12-01 14:53:08 -08001869 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001870 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001871 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001872 break;
Douglas Gregora9766412011-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:
Stephen Hines176edba2014-12-01 14:53:08 -08001880 BuiltinIndex = 14;
Douglas Gregora9766412011-11-28 16:30:08 +00001881 break;
1882
Chris Lattner5caa3702009-05-08 06:58:22 +00001883 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-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:
Stephen Hines176edba2014-12-01 14:53:08 -08001889 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +00001890 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001891 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001892 break;
Douglas Gregora9766412011-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:
Stephen Hines176edba2014-12-01 14:53:08 -08001900 BuiltinIndex = 16;
Douglas Gregora9766412011-11-28 16:30:08 +00001901 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001902 }
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Chris Lattner5caa3702009-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 Carruthd2014572010-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 Stump1eb44332009-09-09 15:08:12 +00001912
Stephen Hines176edba2014-12-01 14:53:08 -08001913 if (WarnAboutSemanticsChange) {
1914 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1915 << TheCall->getCallee()->getSourceRange();
1916 }
1917
Chris Lattnere7ac0a92009-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 Bagnara2ad11cd2012-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());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001932 if (!NewBuiltinDecl)
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001933 return ExprError();
1934 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001935
John McCallf871d0c2010-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 Lattner5caa3702009-05-08 06:58:22 +00001939 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001940 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Chris Lattner5caa3702009-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 McCallb45ae252011-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 Wiegley429bb272011-04-08 18:41:53 +00001948 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001949 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Chris Lattner5caa3702009-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 Stump1eb44332009-09-09 15:08:12 +00001956 // FIXME: Do this check.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001957 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +00001958 }
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Douglas Gregorbbcb7ea2011-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 Bagnarae4b92762012-01-27 09:46:47 +00001966 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001967 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001968 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001969 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001970 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001971 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Chris Lattner5caa3702009-05-08 06:58:22 +00001973 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-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);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001978 TheCall->setCallee(PromotedCall.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Chandler Carruthdb4325b2010-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 Carruth8d13d222010-07-18 20:54:12 +00001983 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001984
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001985 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001986}
1987
Chris Lattner69039812009-02-18 06:01:06 +00001988/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001989/// CFString constructor is correct
Steve Narofffd942622009-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 Lattner69039812009-02-18 06:01:06 +00001992bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001993 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001994 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1995
Douglas Gregor5cee1192011-07-27 05:40:30 +00001996 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001997 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1998 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001999 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002000 }
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Fariborz Jahanian7da71022010-09-07 19:38:13 +00002002 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002003 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00002004 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002005 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00002006 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-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 Carlsson9cdc4d32007-08-17 15:44:17 +00002017 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00002018}
2019
Chris Lattnerc27c6652007-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 Lattner925e60d2007-12-28 05:29:59 +00002022bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2023 Expr *Fn = TheCall->getCallee();
2024 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00002025 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002026 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00002027 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2028 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00002029 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002030 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00002031 return true;
2032 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00002033
2034 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-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 Friedman56f20ae2008-12-15 22:05:35 +00002038 }
2039
John McCall5f8d6042011-08-27 01:09:30 +00002040 // Type-check the first argument normally.
2041 if (checkBuiltinArgument(*this, TheCall, 0))
2042 return true;
2043
Chris Lattnerc27c6652007-12-20 00:05:45 +00002044 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00002045 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00002046 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00002047 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00002048 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00002049 else if (FunctionDecl *FD = getCurFunctionDecl())
2050 isVariadic = FD->isVariadic();
2051 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002052 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Chris Lattnerc27c6652007-12-20 00:05:45 +00002054 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00002055 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2056 return true;
2057 }
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Chris Lattner30ce3442007-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 Carlssone2c14102008-02-13 01:22:59 +00002062 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Nico Weberb07d4482013-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 Carlsson88cf2262008-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 Lattner30ce3442007-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 Carlsson88cf2262008-02-11 04:20:54 +00002073 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00002074 if (CurBlock)
2075 LastArg = *(CurBlock->TheDecl->param_end()-1);
2076 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00002077 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00002078 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002079 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00002080 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00002081
2082 Type = PV->getType();
2083 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00002084 }
2085 }
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Chris Lattner30ce3442007-12-19 23:59:04 +00002087 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00002088 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00002089 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-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 Zaffanella54de9bb2013-11-07 08:14:26 +00002096 TheCall->setType(Context.VoidTy);
Chris Lattner30ce3442007-12-19 23:59:04 +00002097 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00002098}
Chris Lattner30ce3442007-12-19 23:59:04 +00002099
Stephen Hines176edba2014-12-01 14:53:08 -08002100bool 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
2131 static const struct {
2132 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 Lattner1b9a0792007-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 Lattner925e60d2007-12-28 05:29:59 +00002154bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2155 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00002156 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00002157 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00002158 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00002159 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002160 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00002161 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002162 << SourceRange(TheCall->getArg(2)->getLocStart(),
2163 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00002164
John Wiegley429bb272011-04-08 18:41:53 +00002165 ExprResult OrigArg0 = TheCall->getArg(0);
2166 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00002167
Chris Lattner1b9a0792007-12-20 00:26:33 +00002168 // Do standard promotions between the two arguments, returning their common
2169 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00002170 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00002171 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2172 return true;
Daniel Dunbar403bc2b2009-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 Wiegley429bb272011-04-08 18:41:53 +00002177 TheCall->setArg(0, OrigArg0.get());
2178 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00002179
John Wiegley429bb272011-04-08 18:41:53 +00002180 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00002181 return false;
2182
Chris Lattner1b9a0792007-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 Friedman860a3192012-06-16 02:19:17 +00002185 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00002186 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002187 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00002188 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2189 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00002190
Chris Lattner1b9a0792007-12-20 00:26:33 +00002191 return false;
2192}
2193
Benjamin Kramere771a7a2010-02-15 22:42:31 +00002194/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2195/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-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 Friedman9ac6f622009-08-31 20:06:00 +00002200 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00002201 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00002202 if (TheCall->getNumArgs() > NumArgs)
2203 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00002204 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00002205 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00002206 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00002207 (*(TheCall->arg_end()-1))->getLocEnd());
2208
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00002209 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00002210
Eli Friedman9ac6f622009-08-31 20:06:00 +00002211 if (OrigArg->isTypeDependent())
2212 return false;
2213
Chris Lattner81368fb2010-05-06 05:50:07 +00002214 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00002215 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00002216 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00002217 diag::err_typecheck_call_invalid_unary_fp)
2218 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Chris Lattner81368fb2010-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");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002226 Cast->setSubExpr(nullptr);
Chris Lattner81368fb2010-05-06 05:50:07 +00002227 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00002228 }
2229 }
2230
Eli Friedman9ac6f622009-08-31 20:06:00 +00002231 return false;
2232}
2233
Eli Friedmand38617c2008-05-14 19:38:39 +00002234/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2235// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00002236ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00002237 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002238 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00002239 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00002240 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2241 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00002242
Nate Begeman37b6a572010-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 Toppere3fbbe92013-07-19 04:46:31 +00002249
Douglas Gregorcde01732009-05-19 22:10:17 +00002250 if (!TheCall->getArg(0)->isTypeDependent() &&
2251 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00002252 QualType LHSType = TheCall->getArg(0)->getType();
2253 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00002254
Craig Topperbbe759c2013-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 Toppere3fbbe92013-07-19 04:46:31 +00002260
Nate Begeman37b6a572010-06-08 00:16:34 +00002261 numElements = LHSType->getAs<VectorType>()->getNumElements();
2262 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Nate Begeman37b6a572010-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 Ledru4cb3d902013-07-06 08:00:09 +00002268 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00002269 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-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 Toppere3fbbe92013-07-19 04:46:31 +00002274 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-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 Begeman37b6a572010-06-08 00:16:34 +00002279 } else if (numElements != numResElements) {
2280 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00002281 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002282 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00002283 }
Eli Friedmand38617c2008-05-14 19:38:39 +00002284 }
2285
2286 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00002287 if (TheCall->getArg(i)->isTypeDependent() ||
2288 TheCall->getArg(i)->isValueDependent())
2289 continue;
2290
Nate Begeman37b6a572010-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 Topperb44545a2013-07-28 21:50:10 +00002294 diag::err_shufflevector_nonconstant_argument)
2295 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002296
Craig Topper6f4f8082013-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 Lattnerd1a0b6d2008-08-10 02:05:13 +00002301 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002302 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00002303 diag::err_shufflevector_argument_too_large)
2304 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00002305 }
2306
Chris Lattner5f9e2722011-07-23 10:55:15 +00002307 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00002308
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00002309 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00002310 exprs.push_back(TheCall->getArg(i));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002311 TheCall->setArg(i, nullptr);
Eli Friedmand38617c2008-05-14 19:38:39 +00002312 }
2313
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002314 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2315 TheCall->getCallee()->getLocStart(),
2316 TheCall->getRParenLoc());
Eli Friedmand38617c2008-05-14 19:38:39 +00002317}
Chris Lattner30ce3442007-12-19 23:59:04 +00002318
Hal Finkel414a1bd2013-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
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002345 return new (Context)
2346 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkel414a1bd2013-09-18 03:29:45 +00002347}
2348
Daniel Dunbar4493f792008-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 Lattnerfa25bbb2008-11-19 05:08:23 +00002353 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00002354
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002355 if (NumArgs > 3)
Eric Christopherccfa9632010-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 Dunbar4493f792008-07-21 22:59:13 +00002360
2361 // Argument 0 is checked for us and the remaining arguments must be
2362 // constant integers.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002363 for (unsigned i = 1; i != NumArgs; ++i)
2364 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher691ebc32010-04-17 02:26:23 +00002365 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002366
Stephen Hines651f13c2014-04-23 16:59:28 -07002367 return false;
2368}
2369
Stephen Hines176edba2014-12-01 14:53:08 -08002370/// 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))
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002378 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Stephen Hines176edba2014-12-01 14:53:08 -08002379 << 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 }
2419
2420 return false;
2421}
2422
Eric Christopher691ebc32010-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 Christopher5e896552010-04-19 18:23:02 +00002435 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00002436
Chris Lattner21fb98e2009-09-23 06:06:36 +00002437 return false;
2438}
2439
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002440/// 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 Christopher691ebc32010-04-17 02:26:23 +00002444 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00002445
2446 // We can't check the value of a dependent argument.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002447 Expr *Arg = TheCall->getArg(ArgNum);
2448 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor592a4232012-06-29 01:05:22 +00002449 return false;
2450
Eric Christopher691ebc32010-04-17 02:26:23 +00002451 // Check constant-ness first.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002452 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher691ebc32010-04-17 02:26:23 +00002453 return true;
2454
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002455 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002456 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002457 << Low << High << Arg->getSourceRange();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00002458
2459 return false;
2460}
2461
Eli Friedman586d6a82009-05-03 06:04:26 +00002462/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-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 Christopher691ebc32010-04-17 02:26:23 +00002466 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00002467
Eric Christopher691ebc32010-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 Friedmand875fed2009-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 Smith0e218972013-08-05 18:49:43 +00002479namespace {
2480enum StringLiteralCheckType {
2481 SLCT_NotALiteral,
2482 SLCT_UncheckedLiteral,
2483 SLCT_CheckedLiteral
2484};
2485}
2486
Richard Smith831421f2012-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 Smith0e218972013-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 Kremenek4fe64412010-09-09 03:51:39 +00002497 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00002498 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00002499 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002500
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002501 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00002502
Richard Smith0e218972013-08-05 18:49:43 +00002503 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikiea73cdcb2012-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 Smith0e218972013-08-05 18:49:43 +00002508 return SLCT_UncheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00002509
Ted Kremenekd30ef872009-01-12 23:09:09 +00002510 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00002511 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00002512 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-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 Smith0e218972013-08-05 18:49:43 +00002518 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002519 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002520 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002521 if (Left == SLCT_NotALiteral)
2522 return SLCT_NotALiteral;
2523 StringLiteralCheckType Right =
Richard Smith0e218972013-08-05 18:49:43 +00002524 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002525 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002526 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002527 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002528 }
2529
2530 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002531 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2532 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002533 }
2534
John McCall56ca35d2011-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 Smith831421f2012-06-25 20:30:08 +00002540 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00002541
Ted Kremenekb43e8ad2011-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 Smith831421f2012-06-25 20:30:08 +00002546 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002547
Ted Kremenek082d9362009-03-20 21:35:28 +00002548 case Stmt::DeclRefExprClass: {
2549 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002550
Ted Kremenek082d9362009-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 Kremenekd30ef872009-01-12 23:09:09 +00002556
Richard Smith0e218972013-08-05 18:49:43 +00002557 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2558 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002559 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smith0e218972013-08-05 18:49:43 +00002560 isConstant = T.isConstant(S.Context) &&
2561 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupase98e5b52012-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 Smith0e218972013-08-05 18:49:43 +00002565 isConstant = T.isConstant(S.Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00002566 }
Mike Stump1eb44332009-09-09 15:08:12 +00002567
Ted Kremenek082d9362009-03-20 21:35:28 +00002568 if (isConstant) {
Matt Beaumont-Gaye2c60662012-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 Smith0e218972013-08-05 18:49:43 +00002575 return checkFormatStringExpr(S, Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002576 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002577 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002578 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002579 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002580 }
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Anders Carlssond966a552009-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 Smith0e218972013-08-05 18:49:43 +00002595 // }
Jean-Daniel Dupasf57c4132012-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;
Stephen Hines651f13c2014-04-23 16:59:28 -07002600 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupasf57c4132012-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 Smith0e218972013-08-05 18:49:43 +00002608 Type == S.GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002609 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002610 }
2611 }
2612 }
2613 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002614 }
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Richard Smith831421f2012-06-25 20:30:08 +00002616 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002617 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002618
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002619 case Stmt::CallExprClass:
2620 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002621 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-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 Stump1eb44332009-09-09 15:08:12 +00002629
Richard Smith0e218972013-08-05 18:49:43 +00002630 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002631 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002632 Type, CallType, InFunctionCall,
2633 CheckedVarArgs);
Jordan Rose50687312012-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 Smith0e218972013-08-05 18:49:43 +00002639 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002640 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002641 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002642 InFunctionCall, CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002643 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002644 }
2645 }
Mike Stump1eb44332009-09-09 15:08:12 +00002646
Richard Smith831421f2012-06-25 20:30:08 +00002647 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002648 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002649 case Stmt::ObjCStringLiteralClass:
2650 case Stmt::StringLiteralClass: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002651 const StringLiteral *StrE = nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +00002652
Ted Kremenek082d9362009-03-20 21:35:28 +00002653 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002654 StrE = ObjCFExpr->getString();
2655 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002656 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002657
Ted Kremenekd30ef872009-01-12 23:09:09 +00002658 if (StrE) {
Richard Smith0e218972013-08-05 18:49:43 +00002659 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2660 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002661 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002662 }
Mike Stump1eb44332009-09-09 15:08:12 +00002663
Richard Smith831421f2012-06-25 20:30:08 +00002664 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002665 }
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Ted Kremenek082d9362009-03-20 21:35:28 +00002667 default:
Richard Smith831421f2012-06-25 20:30:08 +00002668 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002669 }
2670}
2671
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002672Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00002673 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas34269df2012-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)
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002680 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
2681 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002682 .Default(FST_Unknown);
2683}
2684
Jordan Roseddcfbc92012-07-19 18:10:23 +00002685/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002686/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002687/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002688bool Sema::CheckFormatArguments(const FormatAttr *Format,
2689 ArrayRef<const Expr *> Args,
2690 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002691 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002692 SourceLocation Loc, SourceRange Range,
2693 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith831421f2012-06-25 20:30:08 +00002694 FormatStringInfo FSI;
2695 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002696 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002697 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smith0e218972013-08-05 18:49:43 +00002698 CallType, Loc, Range, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002699 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002700}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002701
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002702bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002703 bool HasVAListArg, unsigned format_idx,
2704 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002705 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002706 SourceLocation Loc, SourceRange Range,
2707 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002708 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002709 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002710 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002711 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002712 }
Mike Stump1eb44332009-09-09 15:08:12 +00002713
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002714 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Chris Lattner59907c42007-08-10 20:18:51 +00002716 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002717 //
Ted Kremenek71895b92007-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 Kremenek7ff22b22008-06-16 18:00:42 +00002723
Mike Stump1eb44332009-09-09 15:08:12 +00002724 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002725 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002726 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002727 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002728 StringLiteralCheckType CT =
Richard Smith0e218972013-08-05 18:49:43 +00002729 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2730 format_idx, firstDataArg, Type, CallType,
2731 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002732 if (CT != SLCT_NotALiteral)
2733 // Literal format string found, check done!
2734 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002735
Jean-Daniel Dupas2837a2f2012-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 Smith831421f2012-06-25 20:30:08 +00002739 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002740
Jean-Daniel Dupasce3aa392012-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 Dupasdc170202012-05-04 21:08:08 +00002745 if (Type == FST_NSString &&
2746 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002747 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002748
Chris Lattner655f1412009-04-29 04:59:47 +00002749 // If there are no arguments specified, warn with -Wformat-security, otherwise
2750 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002751 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002752 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002753 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002754 << OrigFormatExpr->getSourceRange();
2755 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002756 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002757 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002758 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002759 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002760}
Ted Kremenek71895b92007-08-14 17:39:48 +00002761
Ted Kremeneke0e53132010-01-28 23:39:18 +00002762namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002763class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2764protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002765 Sema &S;
2766 const StringLiteral *FExpr;
2767 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002768 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002769 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002770 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002771 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002772 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002773 unsigned FormatIdx;
Richard Smith0e218972013-08-05 18:49:43 +00002774 llvm::SmallBitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002775 bool usesPositionalArgs;
2776 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002777 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002778 Sema::VariadicCallType CallType;
Richard Smith0e218972013-08-05 18:49:43 +00002779 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002780public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002781 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002782 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002783 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002784 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002785 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002786 Sema::VariadicCallType callType,
2787 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002788 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002789 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2790 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002791 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002792 usesPositionalArgs(false), atFirstArg(true),
Richard Smith0e218972013-08-05 18:49:43 +00002793 inFunctionCall(inFunctionCall), CallType(callType),
2794 CheckedVarArgs(CheckedVarArgs) {
2795 CoveredArgs.resize(numDataArgs);
2796 CoveredArgs.reset();
2797 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002798
Ted Kremenek07d161f2010-01-29 01:50:07 +00002799 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002800
Ted Kremenek826a3452010-07-16 02:11:22 +00002801 void HandleIncompleteSpecifier(const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07002802 unsigned specifierLen) override;
Hans Wennborg76517422012-02-22 10:17:01 +00002803
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002804 void HandleInvalidLengthModifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002805 const analyze_format_string::FormatSpecifier &FS,
2806 const analyze_format_string::ConversionSpecifier &CS,
2807 const char *startSpecifier, unsigned specifierLen,
2808 unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002809
Hans Wennborg76517422012-02-22 10:17:01 +00002810 void HandleNonStandardLengthModifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002811 const analyze_format_string::FormatSpecifier &FS,
2812 const char *startSpecifier, unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002813
2814 void HandleNonStandardConversionSpecifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002815 const analyze_format_string::ConversionSpecifier &CS,
2816 const char *startSpecifier, unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002817
Stephen Hines651f13c2014-04-23 16:59:28 -07002818 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgf8562642012-03-09 10:10:54 +00002819
Stephen Hines651f13c2014-04-23 16:59:28 -07002820 void HandleInvalidPosition(const char *startSpecifier,
2821 unsigned specifierLen,
2822 analyze_format_string::PositionContext p) override;
Ted Kremenekefaff192010-02-27 01:41:03 +00002823
Stephen Hines651f13c2014-04-23 16:59:28 -07002824 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekefaff192010-02-27 01:41:03 +00002825
Stephen Hines651f13c2014-04-23 16:59:28 -07002826 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002827
Richard Trieu55733de2011-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 Gribenko55431692013-05-05 00:41:58 +00002834 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002835
Ted Kremenek826a3452010-07-16 02:11:22 +00002836protected:
Ted Kremenekc09b6a52010-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 Trieu55733de2011-10-28 00:41:25 +00002841
2842 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2843 const char *startSpec,
2844 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002845
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002846 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002847 CharSourceRange getSpecifierRange(const char *startSpecifier,
2848 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002849 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002850
Ted Kremenek0d277352010-01-29 01:06:55 +00002851 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-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 Trieu55733de2011-10-28 00:41:25 +00002857
2858 template <typename Range>
2859 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2860 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002861 ArrayRef<FixItHint> Fixit = None);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002862};
2863}
2864
Ted Kremenek826a3452010-07-16 02:11:22 +00002865SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002866 return OrigFormatExpr->getSourceRange();
2867}
2868
Ted Kremenek826a3452010-07-16 02:11:22 +00002869CharSourceRange CheckFormatHandler::
2870getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-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 Kyrtzidisa64ccef2011-09-19 20:40:19 +00002875 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002876
2877 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002878}
2879
Ted Kremenek826a3452010-07-16 02:11:22 +00002880SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002881 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002882}
2883
Ted Kremenek826a3452010-07-16 02:11:22 +00002884void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2885 unsigned specifierLen){
Richard Trieu55733de2011-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 Kremenek808015a2010-01-29 03:16:21 +00002890}
2891
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002892void CheckFormatHandler::HandleInvalidLengthModifier(
2893 const analyze_format_string::FormatSpecifier &FS,
2894 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002895 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-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 Blaikiedc84cd52013-02-20 22:23:23 +00002902 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002903 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002904 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-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 Rose8be066e2012-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 Rosebbb6bb42012-09-08 04:00:03 +00002919 getLocationOfByte(LM.getStart()),
2920 /*IsStringLocation*/true,
2921 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002922 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002923 }
2924}
2925
Hans Wennborg76517422012-02-22 10:17:01 +00002926void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002927 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002928 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-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 Blaikiedc84cd52013-02-20 22:23:23 +00002935 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-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 Wennborg76517422012-02-22 10:17:01 +00002954}
2955
2956void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2957 const analyze_format_string::ConversionSpecifier &CS,
2958 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002959 using namespace analyze_format_string;
2960
2961 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002962 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-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 Wennborg76517422012-02-22 10:17:01 +00002981}
2982
Hans Wennborgf8562642012-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 Kremenekefaff192010-02-27 01:41:03 +00002991void
Ted Kremenek826a3452010-07-16 02:11:22 +00002992CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2993 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-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 Kremenekefaff192010-02-27 01:41:03 +00002998}
2999
Ted Kremenek826a3452010-07-16 02:11:22 +00003000void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00003001 unsigned posLen) {
Richard Trieu55733de2011-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 Kremenekefaff192010-02-27 01:41:03 +00003006}
3007
Ted Kremenek826a3452010-07-16 02:11:22 +00003008void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00003009 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00003010 // The presence of a null character is likely an error.
Richard Trieu55733de2011-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 Kremenek0c069442011-03-15 21:18:48 +00003015 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003016}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003017
Jordan Rose48716662012-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 Kremenek826a3452010-07-16 02:11:22 +00003020const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003021 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-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 Rose48716662012-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 Wilsonc03f2df2012-05-03 19:47:19 +00003040 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003041 }
3042 }
3043}
3044
Ted Kremenekc09b6a52010-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 Trieu55733de2011-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 Kremenekc09b6a52010-07-19 21:25:57 +00003072
3073 return keepGoing;
3074}
3075
Richard Trieu55733de2011-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 Kremenek666a1972010-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 Trieu55733de2011-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 Kremenek666a1972010-07-26 19:45:42 +00003099 return false;
3100 }
3101 return true;
3102}
3103
Richard Trieu55733de2011-10-28 00:41:25 +00003104template<typename Range>
3105void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3106 SourceLocation Loc,
3107 bool IsStringLocation,
3108 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00003109 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003110 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-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 Gribenko70517ca2012-08-23 17:58:28 +00003117/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-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 Gribenko70517ca2012-08-23 17:58:28 +00003140/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-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 Roseec087352012-09-05 22:56:26 +00003148 ArrayRef<FixItHint> FixIt) {
3149 if (InFunctionCall) {
3150 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3151 D << StringRange;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003152 D << FixIt;
Jordan Roseec087352012-09-05 22:56:26 +00003153 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00003154 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3155 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-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;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003162 Note << FixIt;
Richard Trieu55733de2011-10-28 00:41:25 +00003163 }
3164}
3165
Ted Kremenek826a3452010-07-16 02:11:22 +00003166//===--- CHECK: Printf format string checking ------------------------------===//
3167
3168namespace {
3169class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00003170 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00003171public:
3172 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3173 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003174 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00003175 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003176 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003177 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-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 Roseddcfbc92012-07-19 18:10:23 +00003184 {}
3185
Stephen Hines651f13c2014-04-23 16:59:28 -07003186
Ted Kremenek826a3452010-07-16 02:11:22 +00003187 bool HandleInvalidPrintfConversionSpecifier(
3188 const analyze_printf::PrintfSpecifier &FS,
3189 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003190 unsigned specifierLen) override;
3191
Ted Kremenek826a3452010-07-16 02:11:22 +00003192 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3193 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003194 unsigned specifierLen) override;
Richard Smith831421f2012-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 Kremenek826a3452010-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 Wennborgf3749f42012-08-07 08:11:26 +00003213 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Stephen Hines651f13c2014-04-23 16:59:28 -07003214 const Expr *E);
Richard Smith831421f2012-06-25 20:30:08 +00003215
Ted Kremenek826a3452010-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 Kremenek6ecb9502010-07-20 20:04:27 +00003223 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003224 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003225
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003226 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3227 getLocationOfByte(CS.getStart()),
3228 startSpecifier, specifierLen,
3229 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00003230}
3231
Ted Kremenek826a3452010-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 Kremenek0d277352010-01-29 01:06:55 +00003236
3237 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00003238 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003239 unsigned argIndex = Amt.getArgIndex();
3240 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-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 Kremenek0d277352010-01-29 01:06:55 +00003246 // Don't do any more checking. We will just emit
3247 // spurious errors.
3248 return false;
3249 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003250
Ted Kremenek0d277352010-01-29 01:06:55 +00003251 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-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 Kremenek7f70dc82010-02-26 19:18:41 +00003255 CoveredArgs.set(argIndex);
3256 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003257 if (!Arg)
3258 return false;
3259
Ted Kremenek0d277352010-01-29 01:06:55 +00003260 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003261
Hans Wennborgf3749f42012-08-07 08:11:26 +00003262 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3263 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003264
Hans Wennborgf3749f42012-08-07 08:11:26 +00003265 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00003266 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00003267 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00003268 << T << Arg->getSourceRange(),
3269 getLocationOfByte(Amt.getStart()),
3270 /*IsStringLocation*/true,
3271 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-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 Kremenek0d277352010-01-29 01:06:55 +00003280
Tom Caree4ee9662010-06-17 19:00:27 +00003281void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00003282 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00003283 const analyze_printf::OptionalAmount &Amt,
3284 unsigned type,
3285 const char *startSpecifier,
3286 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003287 const analyze_printf::PrintfConversionSpecifier &CS =
3288 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00003289
Richard Trieu55733de2011-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 Caree4ee9662010-06-17 19:00:27 +00003302}
3303
Ted Kremenek826a3452010-07-16 02:11:22 +00003304void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-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 Kremenek6ecb9502010-07-20 20:04:27 +00003309 const analyze_printf::PrintfConversionSpecifier &CS =
3310 FS.getConversionSpecifier();
Richard Trieu55733de2011-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 Caree4ee9662010-06-17 19:00:27 +00003318}
3319
3320void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00003321 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-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 Trieu55733de2011-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 Caree4ee9662010-06-17 19:00:27 +00003334}
3335
Richard Smith831421f2012-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());
Stephen Hines651f13c2014-04-23 16:59:28 -07003348 if (!RD || !RD->getDefinition())
Richard Smith831421f2012-06-25 20:30:08 +00003349 return Results;
3350
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003351 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith831421f2012-06-25 20:30:08 +00003352 Sema::LookupMemberName);
Stephen Hines651f13c2014-04-23 16:59:28 -07003353 R.suppressDiagnostics();
Richard Smith831421f2012-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
Stephen Hines651f13c2014-04-23 16:59:28 -07003366/// 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 Smith831421f2012-06-25 20:30:08 +00003381// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00003382// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00003383// Returns true when a c_str() conversion method is found.
3384bool CheckPrintfHandler::checkForCStrMembers(
Stephen Hines651f13c2014-04-23 16:59:28 -07003385 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith831421f2012-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;
Stephen Hines651f13c2014-04-23 16:59:28 -07003394 if (Method->getMinRequiredArguments() == 0 &&
3395 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith831421f2012-06-25 20:30:08 +00003396 // FIXME: Suggest parens if the expression needs them.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003397 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith831421f2012-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 Kremeneke0e53132010-01-28 23:39:18 +00003408bool
Ted Kremenek826a3452010-07-16 02:11:22 +00003409CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00003410 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00003411 const char *startSpecifier,
3412 unsigned specifierLen) {
3413
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003414 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00003415 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003416 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00003417
Ted Kremenekbaa40062010-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 Trieu55733de2011-10-28 00:41:25 +00003424 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3425 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003426 return false;
3427 }
Ted Kremenek0d277352010-01-29 01:06:55 +00003428 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003429
Ted Kremenekefaff192010-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 Kremenek0d277352010-01-29 01:06:55 +00003439 return false;
3440 }
3441
Ted Kremenekf88c8e02010-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 Kremenek0e5675d2010-02-10 02:16:30 +00003445 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00003446 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003447
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003448 // Consume the argument.
3449 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-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 Kremenek7f70dc82010-02-26 19:18:41 +00003456
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003457 // 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 Kremenek7f70dc82010-02-26 19:18:41 +00003494 // Check for using an Objective-C specific conversion specifier
3495 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00003496 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003497 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3498 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003499 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003500
Tom Caree4ee9662010-06-17 19:00:27 +00003501 // Check for invalid use of field width
3502 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00003503 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-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 Kremenek65197b42011-01-08 05:28:46 +00003514 if (!FS.hasValidThousandsGroupingPrefix())
3515 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-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 Care45f9b7e2010-06-21 21:21:01 +00003520 if (!FS.hasValidSpacePrefix())
3521 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-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 Care45f9b7e2010-06-21 21:21:01 +00003528 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3529 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3530 startSpecifier, specifierLen);
Tom Caree4ee9662010-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 Rosebbb6bb42012-09-08 04:00:03 +00003536 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003537 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3538 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003539 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003540 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003541 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003542 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3543 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00003544
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003545 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3546 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3547
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003548 // The remaining checks depend on the data arguments.
3549 if (HasVAListArg)
3550 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003551
Ted Kremenek666a1972010-07-26 19:45:42 +00003552 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003553 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003554
Jordan Rose48716662012-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 Smith831421f2012-06-25 20:30:08 +00003560}
3561
Jordan Roseec087352012-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 Rose17ddc542012-12-05 18:44:44 +00003573 case Stmt::CharacterLiteralClass:
3574 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003575 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003576 case Stmt::FloatingLiteralClass:
3577 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003578 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-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 Roseec087352012-09-05 22:56:26 +00003584 case Stmt::ObjCIvarRefExprClass:
3585 case Stmt::ObjCMessageExprClass:
3586 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003587 case Stmt::ObjCStringLiteralClass:
3588 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003589 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003590 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003591 case Stmt::UnaryOperatorClass:
3592 return false;
3593 default:
3594 return true;
3595 }
3596}
3597
Stephen Hines176edba2014-12-01 14:53:08 -08003598static 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 Smith831421f2012-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. Spencer96827eb2010-07-27 04:46:02 +00003660 // Now type check the data expression that matches the
3661 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003662 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3663 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003664 if (!AT.isValid())
3665 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003666
Jordan Rose448ac3e2012-12-05 18:44:40 +00003667 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003668 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3669 ExprTy = TET->getUnderlyingExpr()->getType();
3670 }
3671
Jordan Rose448ac3e2012-12-05 18:44:40 +00003672 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003673 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00003674
Jordan Rose614a8652012-09-05 22:56:19 +00003675 // Look through argument promotions for our error message's reported type.
3676 // This includes the integral and floating promotions, but excludes array
3677 // and function pointer decay; seeing that an argument intended to be a
3678 // string has type 'char [6]' is probably more confusing than 'char *'.
3679 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3680 if (ICE->getCastKind() == CK_IntegralCast ||
3681 ICE->getCastKind() == CK_FloatingCast) {
3682 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003683 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003684
3685 // Check if we didn't match because of an implicit cast from a 'char'
3686 // or 'short' to an 'int'. This is done because printf is a varargs
3687 // function.
3688 if (ICE->getType() == S.Context.IntTy ||
3689 ICE->getType() == S.Context.UnsignedIntTy) {
3690 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003691 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003692 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003693 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003694 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003695 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3696 // Special case for 'a', which has type 'int' in C.
3697 // Note, however, that we do /not/ want to treat multibyte constants like
3698 // 'MooV' as characters! This form is deprecated but still exists.
3699 if (ExprTy == S.Context.IntTy)
3700 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3701 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003702 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003703
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003704 // Look through enums to their underlying type.
3705 bool IsEnum = false;
3706 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3707 ExprTy = EnumTy->getDecl()->getIntegerType();
3708 IsEnum = true;
3709 }
3710
Jordan Rose2cd34402012-12-05 18:44:49 +00003711 // %C in an Objective-C context prints a unichar, not a wchar_t.
3712 // If the argument is an integer of some kind, believe the %C and suggest
3713 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003714 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003715 if (ObjCContext &&
3716 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3717 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3718 !ExprTy->isCharType()) {
3719 // 'unichar' is defined as a typedef of unsigned short, but we should
3720 // prefer using the typedef if it is visible.
3721 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenek656465d2013-10-15 05:25:17 +00003722
3723 // While we are here, check if the value is an IntegerLiteral that happens
3724 // to be within the valid range.
3725 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3726 const llvm::APInt &V = IL->getValue();
3727 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3728 return true;
3729 }
3730
Jordan Rose2cd34402012-12-05 18:44:49 +00003731 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3732 Sema::LookupOrdinaryName);
3733 if (S.LookupName(Result, S.getCurScope())) {
3734 NamedDecl *ND = Result.getFoundDecl();
3735 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3736 if (TD->getUnderlyingType() == IntendedTy)
3737 IntendedTy = S.Context.getTypedefType(TD);
3738 }
3739 }
3740 }
3741
3742 // Special-case some of Darwin's platform-independence types by suggesting
3743 // casts to primitive types that are known to be large enough.
Stephen Hines176edba2014-12-01 14:53:08 -08003744 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseec087352012-09-05 22:56:26 +00003745 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Stephen Hines176edba2014-12-01 14:53:08 -08003746 QualType CastTy;
3747 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3748 if (!CastTy.isNull()) {
3749 IntendedTy = CastTy;
3750 ShouldNotPrintDirectly = true;
Jordan Roseec087352012-09-05 22:56:26 +00003751 }
3752 }
3753
Jordan Rose614a8652012-09-05 22:56:19 +00003754 // We may be able to offer a FixItHint if it is a supported type.
3755 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003756 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003757 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003758
Jordan Rose614a8652012-09-05 22:56:19 +00003759 if (success) {
3760 // Get the fix string from the fixed format specifier
3761 SmallString<16> buf;
3762 llvm::raw_svector_ostream os(buf);
3763 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003764
Jordan Roseec087352012-09-05 22:56:26 +00003765 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3766
Stephen Hines176edba2014-12-01 14:53:08 -08003767 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Jordan Rose2cd34402012-12-05 18:44:49 +00003768 // In this case, the specifier is wrong and should be changed to match
3769 // the argument.
3770 EmitFormatDiagnostic(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003771 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3772 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose2cd34402012-12-05 18:44:49 +00003773 << E->getSourceRange(),
3774 E->getLocStart(),
3775 /*IsStringLocation*/false,
3776 SpecRange,
3777 FixItHint::CreateReplacement(SpecRange, os.str()));
3778
3779 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003780 // The canonical type for formatting this value is different from the
3781 // actual type of the expression. (This occurs, for example, with Darwin's
3782 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3783 // should be printed as 'long' for 64-bit compatibility.)
3784 // Rather than emitting a normal format/argument mismatch, we want to
3785 // add a cast to the recommended type (and correct the format string
3786 // if necessary).
3787 SmallString<16> CastBuf;
3788 llvm::raw_svector_ostream CastFix(CastBuf);
3789 CastFix << "(";
3790 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3791 CastFix << ")";
3792
3793 SmallVector<FixItHint,4> Hints;
3794 if (!AT.matchesType(S.Context, IntendedTy))
3795 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3796
3797 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3798 // If there's already a cast present, just replace it.
3799 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3800 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3801
3802 } else if (!requiresParensToAddCast(E)) {
3803 // If the expression has high enough precedence,
3804 // just write the C-style cast.
3805 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3806 CastFix.str()));
3807 } else {
3808 // Otherwise, add parens around the expression as well as the cast.
3809 CastFix << "(";
3810 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3811 CastFix.str()));
3812
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003813 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseec087352012-09-05 22:56:26 +00003814 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3815 }
3816
Jordan Rose2cd34402012-12-05 18:44:49 +00003817 if (ShouldNotPrintDirectly) {
3818 // The expression has a type that should not be printed directly.
3819 // We extract the name from the typedef because we don't want to show
3820 // the underlying type in the diagnostic.
Stephen Hines176edba2014-12-01 14:53:08 -08003821 StringRef Name;
3822 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3823 Name = TypedefTy->getDecl()->getName();
3824 else
3825 Name = CastTyName;
Jordan Rose2cd34402012-12-05 18:44:49 +00003826 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003827 << Name << IntendedTy << IsEnum
Jordan Rose2cd34402012-12-05 18:44:49 +00003828 << E->getSourceRange(),
3829 E->getLocStart(), /*IsStringLocation=*/false,
3830 SpecRange, Hints);
3831 } else {
3832 // In this case, the expression could be printed using a different
3833 // specifier, but we've decided that the specifier is probably correct
3834 // and we should cast instead. Just use the normal warning message.
3835 EmitFormatDiagnostic(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003836 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3837 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose2cd34402012-12-05 18:44:49 +00003838 << E->getSourceRange(),
3839 E->getLocStart(), /*IsStringLocation*/false,
3840 SpecRange, Hints);
3841 }
Jordan Roseec087352012-09-05 22:56:26 +00003842 }
Jordan Rose614a8652012-09-05 22:56:19 +00003843 } else {
3844 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3845 SpecifierLen);
3846 // Since the warning for passing non-POD types to variadic functions
3847 // was deferred until now, we emit a warning for non-POD
3848 // arguments here.
Richard Smith0e218972013-08-05 18:49:43 +00003849 switch (S.isValidVarArgType(ExprTy)) {
3850 case Sema::VAK_Valid:
3851 case Sema::VAK_ValidInCXX11:
Jordan Rose614a8652012-09-05 22:56:19 +00003852 EmitFormatDiagnostic(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003853 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3854 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smith0e218972013-08-05 18:49:43 +00003855 << CSR
3856 << E->getSourceRange(),
3857 E->getLocStart(), /*IsStringLocation*/false, CSR);
3858 break;
3859
3860 case Sema::VAK_Undefined:
Stephen Hines176edba2014-12-01 14:53:08 -08003861 case Sema::VAK_MSVCUndefined:
Richard Smith0e218972013-08-05 18:49:43 +00003862 EmitFormatDiagnostic(
3863 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith80ad52f2013-01-02 11:42:31 +00003864 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003865 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003866 << CallType
3867 << AT.getRepresentativeTypeName(S.Context)
3868 << CSR
3869 << E->getSourceRange(),
3870 E->getLocStart(), /*IsStringLocation*/false, CSR);
Stephen Hines651f13c2014-04-23 16:59:28 -07003871 checkForCStrMembers(AT, E);
Richard Smith0e218972013-08-05 18:49:43 +00003872 break;
3873
3874 case Sema::VAK_Invalid:
3875 if (ExprTy->isObjCObjectType())
3876 EmitFormatDiagnostic(
3877 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3878 << S.getLangOpts().CPlusPlus11
3879 << ExprTy
3880 << CallType
3881 << AT.getRepresentativeTypeName(S.Context)
3882 << CSR
3883 << E->getSourceRange(),
3884 E->getLocStart(), /*IsStringLocation*/false, CSR);
3885 else
3886 // FIXME: If this is an initializer list, suggest removing the braces
3887 // or inserting a cast to the target type.
3888 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3889 << isa<InitListExpr>(E) << ExprTy << CallType
3890 << AT.getRepresentativeTypeName(S.Context)
3891 << E->getSourceRange();
3892 break;
3893 }
3894
3895 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3896 "format string specifier index out of range");
3897 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003898 }
3899
Ted Kremeneke0e53132010-01-28 23:39:18 +00003900 return true;
3901}
3902
Ted Kremenek826a3452010-07-16 02:11:22 +00003903//===--- CHECK: Scanf format string checking ------------------------------===//
3904
3905namespace {
3906class CheckScanfHandler : public CheckFormatHandler {
3907public:
3908 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3909 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003910 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003911 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003912 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003913 Sema::VariadicCallType CallType,
3914 llvm::SmallBitVector &CheckedVarArgs)
3915 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3916 numDataArgs, beg, hasVAListArg,
3917 Args, formatIdx, inFunctionCall, CallType,
3918 CheckedVarArgs)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003919 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003920
3921 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3922 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003923 unsigned specifierLen) override;
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003924
3925 bool HandleInvalidScanfConversionSpecifier(
3926 const analyze_scanf::ScanfSpecifier &FS,
3927 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003928 unsigned specifierLen) override;
Ted Kremenekb7c21012010-07-16 18:28:03 +00003929
Stephen Hines651f13c2014-04-23 16:59:28 -07003930 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek826a3452010-07-16 02:11:22 +00003931};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003932}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003933
Ted Kremenekb7c21012010-07-16 18:28:03 +00003934void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3935 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003936 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3937 getLocationOfByte(end), /*IsStringLocation*/true,
3938 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003939}
3940
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003941bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3942 const analyze_scanf::ScanfSpecifier &FS,
3943 const char *startSpecifier,
3944 unsigned specifierLen) {
3945
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003946 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003947 FS.getConversionSpecifier();
3948
3949 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3950 getLocationOfByte(CS.getStart()),
3951 startSpecifier, specifierLen,
3952 CS.getStart(), CS.getLength());
3953}
3954
Ted Kremenek826a3452010-07-16 02:11:22 +00003955bool CheckScanfHandler::HandleScanfSpecifier(
3956 const analyze_scanf::ScanfSpecifier &FS,
3957 const char *startSpecifier,
3958 unsigned specifierLen) {
3959
3960 using namespace analyze_scanf;
3961 using namespace analyze_format_string;
3962
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003963 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003964
Ted Kremenekbaa40062010-07-19 22:01:06 +00003965 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3966 // be used to decide if we are using positional arguments consistently.
3967 if (FS.consumesDataArgument()) {
3968 if (atFirstArg) {
3969 atFirstArg = false;
3970 usesPositionalArgs = FS.usesPositionalArg();
3971 }
3972 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003973 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3974 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003975 return false;
3976 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003977 }
3978
3979 // Check if the field with is non-zero.
3980 const OptionalAmount &Amt = FS.getFieldWidth();
3981 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3982 if (Amt.getConstantAmount() == 0) {
3983 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3984 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003985 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3986 getLocationOfByte(Amt.getStart()),
3987 /*IsStringLocation*/true, R,
3988 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003989 }
3990 }
3991
3992 if (!FS.consumesDataArgument()) {
3993 // FIXME: Technically specifying a precision or field width here
3994 // makes no sense. Worth issuing a warning at some point.
3995 return true;
3996 }
3997
3998 // Consume the argument.
3999 unsigned argIndex = FS.getArgIndex();
4000 if (argIndex < NumDataArgs) {
4001 // The check to see if the argIndex is valid will come later.
4002 // We set the bit here because we may exit early from this
4003 // function if we encounter some other error.
4004 CoveredArgs.set(argIndex);
4005 }
4006
Ted Kremenek1e51c202010-07-20 20:04:47 +00004007 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00004008 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00004009 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4010 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00004011 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00004012 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00004013 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00004014 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4015 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00004016
Jordan Rosebbb6bb42012-09-08 04:00:03 +00004017 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4018 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4019
Ted Kremenek826a3452010-07-16 02:11:22 +00004020 // The remaining checks depend on the data arguments.
4021 if (HasVAListArg)
4022 return true;
4023
Ted Kremenek666a1972010-07-26 19:45:42 +00004024 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00004025 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00004026
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004027 // Check that the argument type matches the format specifier.
4028 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00004029 if (!Ex)
4030 return true;
4031
Hans Wennborg58e1e542012-08-07 08:59:46 +00004032 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
4033 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004034 ScanfSpecifier fixedFS = FS;
Stephen Hines651f13c2014-04-23 16:59:28 -07004035 bool success = fixedFS.fixType(Ex->getType(),
4036 Ex->IgnoreImpCasts()->getType(),
4037 S.getLangOpts(), S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004038
4039 if (success) {
4040 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004041 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004042 llvm::raw_svector_ostream os(buf);
4043 fixedFS.toString(os);
4044
4045 EmitFormatDiagnostic(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004046 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4047 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004048 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00004049 Ex->getLocStart(),
4050 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004051 getSpecifierRange(startSpecifier, specifierLen),
4052 FixItHint::CreateReplacement(
4053 getSpecifierRange(startSpecifier, specifierLen),
4054 os.str()));
4055 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00004056 EmitFormatDiagnostic(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004057 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4058 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00004059 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00004060 Ex->getLocStart(),
4061 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00004062 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004063 }
4064 }
4065
Ted Kremenek826a3452010-07-16 02:11:22 +00004066 return true;
4067}
4068
4069void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00004070 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00004071 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00004072 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00004073 unsigned firstDataArg, FormatStringType Type,
Richard Smith0e218972013-08-05 18:49:43 +00004074 bool inFunctionCall, VariadicCallType CallType,
4075 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00004076
Ted Kremeneke0e53132010-01-28 23:39:18 +00004077 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00004078 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00004079 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00004080 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00004081 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4082 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00004083 return;
4084 }
Ted Kremenek826a3452010-07-16 02:11:22 +00004085
Ted Kremeneke0e53132010-01-28 23:39:18 +00004086 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00004087 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00004088 const char *Str = StrRef.data();
Stephen Hines651f13c2014-04-23 16:59:28 -07004089 // Account for cases where the string literal is truncated in a declaration.
4090 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4091 assert(T && "String literal not of constant array type!");
4092 size_t TypeSize = T->getSize().getZExtValue();
4093 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00004094 const unsigned numDataArgs = Args.size() - firstDataArg;
Stephen Hines651f13c2014-04-23 16:59:28 -07004095
4096 // Emit a warning if the string literal is truncated and does not contain an
4097 // embedded null character.
4098 if (TypeSize <= StrRef.size() &&
4099 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4100 CheckFormatHandler::EmitFormatDiagnostic(
4101 *this, inFunctionCall, Args[format_idx],
4102 PDiag(diag::warn_printf_format_string_not_null_terminated),
4103 FExpr->getLocStart(),
4104 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4105 return;
4106 }
4107
Ted Kremeneke0e53132010-01-28 23:39:18 +00004108 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00004109 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00004110 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00004111 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00004112 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4113 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00004114 return;
4115 }
Ted Kremenek826a3452010-07-16 02:11:22 +00004116
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004117 if (Type == FST_Printf || Type == FST_NSString ||
4118 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek826a3452010-07-16 02:11:22 +00004119 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004120 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00004121 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00004122 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00004123
Hans Wennborgd02deeb2011-12-15 10:25:47 +00004124 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00004125 getLangOpts(),
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004126 Context.getTargetInfo(),
4127 Type == FST_FreeBSDKPrintf))
Ted Kremenek826a3452010-07-16 02:11:22 +00004128 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00004129 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00004130 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00004131 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00004132 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00004133
Hans Wennborgd02deeb2011-12-15 10:25:47 +00004134 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00004135 getLangOpts(),
4136 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00004137 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00004138 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00004139}
4140
Stephen Hines176edba2014-12-01 14:53:08 -08004141bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4142 // Str - The format string. NOTE: this is NOT null-terminated!
4143 StringRef StrRef = FExpr->getString();
4144 const char *Str = StrRef.data();
4145 // Account for cases where the string literal is truncated in a declaration.
4146 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4147 assert(T && "String literal not of constant array type!");
4148 size_t TypeSize = T->getSize().getZExtValue();
4149 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4150 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4151 getLangOpts(),
4152 Context.getTargetInfo());
4153}
4154
Stephen Hines651f13c2014-04-23 16:59:28 -07004155//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4156
4157// Returns the related absolute value function that is larger, of 0 if one
4158// does not exist.
4159static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4160 switch (AbsFunction) {
4161 default:
4162 return 0;
4163
4164 case Builtin::BI__builtin_abs:
4165 return Builtin::BI__builtin_labs;
4166 case Builtin::BI__builtin_labs:
4167 return Builtin::BI__builtin_llabs;
4168 case Builtin::BI__builtin_llabs:
4169 return 0;
4170
4171 case Builtin::BI__builtin_fabsf:
4172 return Builtin::BI__builtin_fabs;
4173 case Builtin::BI__builtin_fabs:
4174 return Builtin::BI__builtin_fabsl;
4175 case Builtin::BI__builtin_fabsl:
4176 return 0;
4177
4178 case Builtin::BI__builtin_cabsf:
4179 return Builtin::BI__builtin_cabs;
4180 case Builtin::BI__builtin_cabs:
4181 return Builtin::BI__builtin_cabsl;
4182 case Builtin::BI__builtin_cabsl:
4183 return 0;
4184
4185 case Builtin::BIabs:
4186 return Builtin::BIlabs;
4187 case Builtin::BIlabs:
4188 return Builtin::BIllabs;
4189 case Builtin::BIllabs:
4190 return 0;
4191
4192 case Builtin::BIfabsf:
4193 return Builtin::BIfabs;
4194 case Builtin::BIfabs:
4195 return Builtin::BIfabsl;
4196 case Builtin::BIfabsl:
4197 return 0;
4198
4199 case Builtin::BIcabsf:
4200 return Builtin::BIcabs;
4201 case Builtin::BIcabs:
4202 return Builtin::BIcabsl;
4203 case Builtin::BIcabsl:
4204 return 0;
4205 }
4206}
4207
4208// Returns the argument type of the absolute value function.
4209static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4210 unsigned AbsType) {
4211 if (AbsType == 0)
4212 return QualType();
4213
4214 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4215 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4216 if (Error != ASTContext::GE_None)
4217 return QualType();
4218
4219 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4220 if (!FT)
4221 return QualType();
4222
4223 if (FT->getNumParams() != 1)
4224 return QualType();
4225
4226 return FT->getParamType(0);
4227}
4228
4229// Returns the best absolute value function, or zero, based on type and
4230// current absolute value function.
4231static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4232 unsigned AbsFunctionKind) {
4233 unsigned BestKind = 0;
4234 uint64_t ArgSize = Context.getTypeSize(ArgType);
4235 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4236 Kind = getLargerAbsoluteValueFunction(Kind)) {
4237 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4238 if (Context.getTypeSize(ParamType) >= ArgSize) {
4239 if (BestKind == 0)
4240 BestKind = Kind;
4241 else if (Context.hasSameType(ParamType, ArgType)) {
4242 BestKind = Kind;
4243 break;
4244 }
4245 }
4246 }
4247 return BestKind;
4248}
4249
4250enum AbsoluteValueKind {
4251 AVK_Integer,
4252 AVK_Floating,
4253 AVK_Complex
4254};
4255
4256static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4257 if (T->isIntegralOrEnumerationType())
4258 return AVK_Integer;
4259 if (T->isRealFloatingType())
4260 return AVK_Floating;
4261 if (T->isAnyComplexType())
4262 return AVK_Complex;
4263
4264 llvm_unreachable("Type not integer, floating, or complex");
4265}
4266
4267// Changes the absolute value function to a different type. Preserves whether
4268// the function is a builtin.
4269static unsigned changeAbsFunction(unsigned AbsKind,
4270 AbsoluteValueKind ValueKind) {
4271 switch (ValueKind) {
4272 case AVK_Integer:
4273 switch (AbsKind) {
4274 default:
4275 return 0;
4276 case Builtin::BI__builtin_fabsf:
4277 case Builtin::BI__builtin_fabs:
4278 case Builtin::BI__builtin_fabsl:
4279 case Builtin::BI__builtin_cabsf:
4280 case Builtin::BI__builtin_cabs:
4281 case Builtin::BI__builtin_cabsl:
4282 return Builtin::BI__builtin_abs;
4283 case Builtin::BIfabsf:
4284 case Builtin::BIfabs:
4285 case Builtin::BIfabsl:
4286 case Builtin::BIcabsf:
4287 case Builtin::BIcabs:
4288 case Builtin::BIcabsl:
4289 return Builtin::BIabs;
4290 }
4291 case AVK_Floating:
4292 switch (AbsKind) {
4293 default:
4294 return 0;
4295 case Builtin::BI__builtin_abs:
4296 case Builtin::BI__builtin_labs:
4297 case Builtin::BI__builtin_llabs:
4298 case Builtin::BI__builtin_cabsf:
4299 case Builtin::BI__builtin_cabs:
4300 case Builtin::BI__builtin_cabsl:
4301 return Builtin::BI__builtin_fabsf;
4302 case Builtin::BIabs:
4303 case Builtin::BIlabs:
4304 case Builtin::BIllabs:
4305 case Builtin::BIcabsf:
4306 case Builtin::BIcabs:
4307 case Builtin::BIcabsl:
4308 return Builtin::BIfabsf;
4309 }
4310 case AVK_Complex:
4311 switch (AbsKind) {
4312 default:
4313 return 0;
4314 case Builtin::BI__builtin_abs:
4315 case Builtin::BI__builtin_labs:
4316 case Builtin::BI__builtin_llabs:
4317 case Builtin::BI__builtin_fabsf:
4318 case Builtin::BI__builtin_fabs:
4319 case Builtin::BI__builtin_fabsl:
4320 return Builtin::BI__builtin_cabsf;
4321 case Builtin::BIabs:
4322 case Builtin::BIlabs:
4323 case Builtin::BIllabs:
4324 case Builtin::BIfabsf:
4325 case Builtin::BIfabs:
4326 case Builtin::BIfabsl:
4327 return Builtin::BIcabsf;
4328 }
4329 }
4330 llvm_unreachable("Unable to convert function");
4331}
4332
4333static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
4334 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4335 if (!FnInfo)
4336 return 0;
4337
4338 switch (FDecl->getBuiltinID()) {
4339 default:
4340 return 0;
4341 case Builtin::BI__builtin_abs:
4342 case Builtin::BI__builtin_fabs:
4343 case Builtin::BI__builtin_fabsf:
4344 case Builtin::BI__builtin_fabsl:
4345 case Builtin::BI__builtin_labs:
4346 case Builtin::BI__builtin_llabs:
4347 case Builtin::BI__builtin_cabs:
4348 case Builtin::BI__builtin_cabsf:
4349 case Builtin::BI__builtin_cabsl:
4350 case Builtin::BIabs:
4351 case Builtin::BIlabs:
4352 case Builtin::BIllabs:
4353 case Builtin::BIfabs:
4354 case Builtin::BIfabsf:
4355 case Builtin::BIfabsl:
4356 case Builtin::BIcabs:
4357 case Builtin::BIcabsf:
4358 case Builtin::BIcabsl:
4359 return FDecl->getBuiltinID();
4360 }
4361 llvm_unreachable("Unknown Builtin type");
4362}
4363
4364// If the replacement is valid, emit a note with replacement function.
4365// Additionally, suggest including the proper header if not already included.
4366static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004367 unsigned AbsKind, QualType ArgType) {
4368 bool EmitHeaderHint = true;
4369 const char *HeaderName = nullptr;
4370 const char *FunctionName = nullptr;
4371 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4372 FunctionName = "std::abs";
4373 if (ArgType->isIntegralOrEnumerationType()) {
4374 HeaderName = "cstdlib";
4375 } else if (ArgType->isRealFloatingType()) {
4376 HeaderName = "cmath";
4377 } else {
4378 llvm_unreachable("Invalid Type");
Stephen Hines651f13c2014-04-23 16:59:28 -07004379 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004380
4381 // Lookup all std::abs
4382 if (NamespaceDecl *Std = S.getStdNamespace()) {
4383 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
4384 R.suppressDiagnostics();
4385 S.LookupQualifiedName(R, Std);
4386
4387 for (const auto *I : R) {
4388 const FunctionDecl *FDecl = nullptr;
4389 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4390 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4391 } else {
4392 FDecl = dyn_cast<FunctionDecl>(I);
4393 }
4394 if (!FDecl)
4395 continue;
4396
4397 // Found std::abs(), check that they are the right ones.
4398 if (FDecl->getNumParams() != 1)
4399 continue;
4400
4401 // Check that the parameter type can handle the argument.
4402 QualType ParamType = FDecl->getParamDecl(0)->getType();
4403 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4404 S.Context.getTypeSize(ArgType) <=
4405 S.Context.getTypeSize(ParamType)) {
4406 // Found a function, don't need the header hint.
4407 EmitHeaderHint = false;
4408 break;
4409 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004410 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004411 }
4412 } else {
4413 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4414 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4415
4416 if (HeaderName) {
4417 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4418 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4419 R.suppressDiagnostics();
4420 S.LookupName(R, S.getCurScope());
4421
4422 if (R.isSingleResult()) {
4423 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4424 if (FD && FD->getBuiltinID() == AbsKind) {
4425 EmitHeaderHint = false;
4426 } else {
4427 return;
4428 }
4429 } else if (!R.empty()) {
4430 return;
4431 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004432 }
4433 }
4434
4435 S.Diag(Loc, diag::note_replace_abs_function)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004436 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Stephen Hines651f13c2014-04-23 16:59:28 -07004437
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004438 if (!HeaderName)
4439 return;
4440
4441 if (!EmitHeaderHint)
4442 return;
4443
Stephen Hines176edba2014-12-01 14:53:08 -08004444 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4445 << FunctionName;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004446}
4447
4448static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4449 if (!FDecl)
4450 return false;
4451
4452 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4453 return false;
4454
4455 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4456
4457 while (ND && ND->isInlineNamespace()) {
4458 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Stephen Hines651f13c2014-04-23 16:59:28 -07004459 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004460
4461 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4462 return false;
4463
4464 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4465 return false;
4466
4467 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07004468}
4469
4470// Warn when using the wrong abs() function.
4471void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4472 const FunctionDecl *FDecl,
4473 IdentifierInfo *FnInfo) {
4474 if (Call->getNumArgs() != 1)
4475 return;
4476
4477 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004478 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4479 if (AbsKind == 0 && !IsStdAbs)
Stephen Hines651f13c2014-04-23 16:59:28 -07004480 return;
4481
4482 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4483 QualType ParamType = Call->getArg(0)->getType();
4484
Stephen Hines176edba2014-12-01 14:53:08 -08004485 // Unsigned types cannot be negative. Suggest removing the absolute value
4486 // function call.
Stephen Hines651f13c2014-04-23 16:59:28 -07004487 if (ArgType->isUnsignedIntegerType()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004488 const char *FunctionName =
4489 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Stephen Hines651f13c2014-04-23 16:59:28 -07004490 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4491 Diag(Call->getExprLoc(), diag::note_remove_abs)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004492 << FunctionName
Stephen Hines651f13c2014-04-23 16:59:28 -07004493 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4494 return;
4495 }
4496
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004497 // std::abs has overloads which prevent most of the absolute value problems
4498 // from occurring.
4499 if (IsStdAbs)
4500 return;
4501
Stephen Hines651f13c2014-04-23 16:59:28 -07004502 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4503 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4504
4505 // The argument and parameter are the same kind. Check if they are the right
4506 // size.
4507 if (ArgValueKind == ParamValueKind) {
4508 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4509 return;
4510
4511 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4512 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4513 << FDecl << ArgType << ParamType;
4514
4515 if (NewAbsKind == 0)
4516 return;
4517
4518 emitReplacement(*this, Call->getExprLoc(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004519 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Stephen Hines651f13c2014-04-23 16:59:28 -07004520 return;
4521 }
4522
4523 // ArgValueKind != ParamValueKind
4524 // The wrong type of absolute value function was used. Attempt to find the
4525 // proper one.
4526 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4527 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4528 if (NewAbsKind == 0)
4529 return;
4530
4531 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4532 << FDecl << ParamValueKind << ArgValueKind;
4533
4534 emitReplacement(*this, Call->getExprLoc(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004535 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Stephen Hines651f13c2014-04-23 16:59:28 -07004536 return;
4537}
4538
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004539//===--- CHECK: Standard memory functions ---------------------------------===//
4540
Stephen Hines651f13c2014-04-23 16:59:28 -07004541/// \brief Takes the expression passed to the size_t parameter of functions
4542/// such as memcmp, strncat, etc and warns if it's a comparison.
4543///
4544/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4545static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4546 IdentifierInfo *FnName,
4547 SourceLocation FnLoc,
4548 SourceLocation RParenLoc) {
4549 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4550 if (!Size)
4551 return false;
4552
4553 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4554 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4555 return false;
4556
Stephen Hines651f13c2014-04-23 16:59:28 -07004557 SourceRange SizeRange = Size->getSourceRange();
4558 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4559 << SizeRange << FnName;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004560 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
4561 << FnName << FixItHint::CreateInsertion(
4562 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Stephen Hines651f13c2014-04-23 16:59:28 -07004563 << FixItHint::CreateRemoval(RParenLoc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004564 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Stephen Hines651f13c2014-04-23 16:59:28 -07004565 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004566 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4567 ")");
Stephen Hines651f13c2014-04-23 16:59:28 -07004568
4569 return true;
4570}
4571
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004572/// \brief Determine whether the given type is or contains a dynamic class type
4573/// (e.g., whether it has a vtable).
4574static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4575 bool &IsContained) {
4576 // Look through array types while ignoring qualifiers.
4577 const Type *Ty = T->getBaseElementTypeUnsafe();
4578 IsContained = false;
4579
4580 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4581 RD = RD ? RD->getDefinition() : nullptr;
4582 if (!RD)
4583 return nullptr;
4584
4585 if (RD->isDynamicClass())
4586 return RD;
4587
4588 // Check all the fields. If any bases were dynamic, the class is dynamic.
4589 // It's impossible for a class to transitively contain itself by value, so
4590 // infinite recursion is impossible.
4591 for (auto *FD : RD->fields()) {
4592 bool SubContained;
4593 if (const CXXRecordDecl *ContainedRD =
4594 getContainedDynamicClass(FD->getType(), SubContained)) {
4595 IsContained = true;
4596 return ContainedRD;
4597 }
4598 }
4599
4600 return nullptr;
Douglas Gregor2a053a32011-05-03 20:05:22 +00004601}
4602
Chandler Carrutha72a12f2011-06-21 23:04:20 +00004603/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00004604/// otherwise returns NULL.
4605static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00004606 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00004607 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4608 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4609 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00004610
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004611 return nullptr;
Chandler Carruth000d4282011-06-16 09:09:40 +00004612}
4613
Chandler Carrutha72a12f2011-06-21 23:04:20 +00004614/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00004615static QualType getSizeOfArgType(const Expr* E) {
4616 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4617 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4618 if (SizeOf->getKind() == clang::UETT_SizeOf)
4619 return SizeOf->getTypeOfArgument();
4620
4621 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00004622}
4623
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004624/// \brief Check for dangerous or invalid arguments to memset().
4625///
Chandler Carruth929f0132011-06-03 06:23:57 +00004626/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004627/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4628/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004629///
4630/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004631void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00004632 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004633 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00004634 assert(BId != 0);
4635
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00004636 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00004637 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00004638 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00004639 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00004640 return;
4641
Anna Zaks0a151a12012-01-17 00:37:07 +00004642 unsigned LastArg = (BId == Builtin::BImemset ||
4643 BId == Builtin::BIstrndup ? 1 : 2);
4644 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00004645 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00004646
Stephen Hines651f13c2014-04-23 16:59:28 -07004647 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4648 Call->getLocStart(), Call->getRParenLoc()))
4649 return;
4650
Chandler Carruth000d4282011-06-16 09:09:40 +00004651 // We have special checking when the length is a sizeof expression.
4652 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4653 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4654 llvm::FoldingSetNodeID SizeOfArgID;
4655
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004656 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4657 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00004658 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004659
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004660 QualType DestTy = Dest->getType();
4661 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4662 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00004663
Chandler Carruth000d4282011-06-16 09:09:40 +00004664 // Never warn about void type pointers. This can be used to suppress
4665 // false positives.
4666 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004667 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004668
Chandler Carruth000d4282011-06-16 09:09:40 +00004669 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4670 // actually comparing the expressions for equality. Because computing the
4671 // expression IDs can be expensive, we only do this if the diagnostic is
4672 // enabled.
4673 if (SizeOfArg &&
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004674 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4675 SizeOfArg->getExprLoc())) {
Chandler Carruth000d4282011-06-16 09:09:40 +00004676 // We only compute IDs for expressions if the warning is enabled, and
4677 // cache the sizeof arg's ID.
4678 if (SizeOfArgID == llvm::FoldingSetNodeID())
4679 SizeOfArg->Profile(SizeOfArgID, Context, true);
4680 llvm::FoldingSetNodeID DestID;
4681 Dest->Profile(DestID, Context, true);
4682 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00004683 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4684 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00004685 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00004686 StringRef ReadableName = FnName->getName();
4687
Chandler Carruth000d4282011-06-16 09:09:40 +00004688 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00004689 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00004690 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00004691 if (!PointeeTy->isIncompleteType() &&
4692 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00004693 ActionIdx = 2; // If the pointee's size is sizeof(char),
4694 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00004695
4696 // If the function is defined as a builtin macro, do not show macro
4697 // expansion.
4698 SourceLocation SL = SizeOfArg->getExprLoc();
4699 SourceRange DSR = Dest->getSourceRange();
4700 SourceRange SSR = SizeOfArg->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004701 SourceManager &SM = getSourceManager();
Anna Zaks6fcb3722012-05-30 00:34:21 +00004702
4703 if (SM.isMacroArgExpansion(SL)) {
4704 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4705 SL = SM.getSpellingLoc(SL);
4706 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4707 SM.getSpellingLoc(DSR.getEnd()));
4708 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4709 SM.getSpellingLoc(SSR.getEnd()));
4710 }
4711
Anna Zaks90c78322012-05-30 23:14:52 +00004712 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00004713 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00004714 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00004715 << PointeeTy
4716 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00004717 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00004718 << SSR);
4719 DiagRuntimeBehavior(SL, SizeOfArg,
4720 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4721 << ActionIdx
4722 << SSR);
4723
Chandler Carruth000d4282011-06-16 09:09:40 +00004724 break;
4725 }
4726 }
4727
4728 // Also check for cases where the sizeof argument is the exact same
4729 // type as the memory argument, and where it points to a user-defined
4730 // record type.
4731 if (SizeOfArgTy != QualType()) {
4732 if (PointeeTy->isRecordType() &&
4733 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4734 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4735 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4736 << FnName << SizeOfArgTy << ArgIdx
4737 << PointeeTy << Dest->getSourceRange()
4738 << LenExpr->getSourceRange());
4739 break;
4740 }
Nico Webere4a1c642011-06-14 16:14:58 +00004741 }
4742
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004743 // Always complain about dynamic classes.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004744 bool IsContained;
4745 if (const CXXRecordDecl *ContainedRD =
4746 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks0a151a12012-01-17 00:37:07 +00004747
4748 unsigned OperationType = 0;
4749 // "overwritten" if we're warning about the destination for any call
4750 // but memcmp; otherwise a verb appropriate to the call.
4751 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4752 if (BId == Builtin::BImemcpy)
4753 OperationType = 1;
4754 else if(BId == Builtin::BImemmove)
4755 OperationType = 2;
4756 else if (BId == Builtin::BImemcmp)
4757 OperationType = 3;
4758 }
4759
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00004760 DiagRuntimeBehavior(
4761 Dest->getExprLoc(), Dest,
4762 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00004763 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004764 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00004765 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00004766 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4767 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00004768 DiagRuntimeBehavior(
4769 Dest->getExprLoc(), Dest,
4770 PDiag(diag::warn_arc_object_memaccess)
4771 << ArgIdx << FnName << PointeeTy
4772 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00004773 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004774 continue;
John McCallf85e1932011-06-15 23:02:42 +00004775
4776 DiagRuntimeBehavior(
4777 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00004778 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004779 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4780 break;
4781 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004782 }
4783}
4784
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004785// A little helper routine: ignore addition and subtraction of integer literals.
4786// This intentionally does not ignore all integer constant expressions because
4787// we don't want to remove sizeof().
4788static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4789 Ex = Ex->IgnoreParenCasts();
4790
4791 for (;;) {
4792 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4793 if (!BO || !BO->isAdditiveOp())
4794 break;
4795
4796 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4797 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4798
4799 if (isa<IntegerLiteral>(RHS))
4800 Ex = LHS;
4801 else if (isa<IntegerLiteral>(LHS))
4802 Ex = RHS;
4803 else
4804 break;
4805 }
4806
4807 return Ex;
4808}
4809
Anna Zaks0f38ace2012-08-08 21:42:23 +00004810static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4811 ASTContext &Context) {
4812 // Only handle constant-sized or VLAs, but not flexible members.
4813 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4814 // Only issue the FIXIT for arrays of size > 1.
4815 if (CAT->getSize().getSExtValue() <= 1)
4816 return false;
4817 } else if (!Ty->isVariableArrayType()) {
4818 return false;
4819 }
4820 return true;
4821}
4822
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004823// Warn if the user has made the 'size' argument to strlcpy or strlcat
4824// be the size of the source, instead of the destination.
4825void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4826 IdentifierInfo *FnName) {
4827
4828 // Don't crash if the user has the wrong number of arguments
Stephen Hines176edba2014-12-01 14:53:08 -08004829 unsigned NumArgs = Call->getNumArgs();
4830 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004831 return;
4832
4833 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4834 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004835 const Expr *CompareWithSrc = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004836
4837 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4838 Call->getLocStart(), Call->getRParenLoc()))
4839 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004840
4841 // Look for 'strlcpy(dst, x, sizeof(x))'
4842 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4843 CompareWithSrc = Ex;
4844 else {
4845 // Look for 'strlcpy(dst, x, strlen(x))'
4846 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004847 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4848 SizeCall->getNumArgs() == 1)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004849 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4850 }
4851 }
4852
4853 if (!CompareWithSrc)
4854 return;
4855
4856 // Determine if the argument to sizeof/strlen is equal to the source
4857 // argument. In principle there's all kinds of things you could do
4858 // here, for instance creating an == expression and evaluating it with
4859 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4860 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4861 if (!SrcArgDRE)
4862 return;
4863
4864 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4865 if (!CompareWithSrcDRE ||
4866 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4867 return;
4868
4869 const Expr *OriginalSizeArg = Call->getArg(2);
4870 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4871 << OriginalSizeArg->getSourceRange() << FnName;
4872
4873 // Output a FIXIT hint if the destination is an array (rather than a
4874 // pointer to an array). This could be enhanced to handle some
4875 // pointers if we know the actual size, like if DstArg is 'array+2'
4876 // we could say 'sizeof(array)-2'.
4877 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00004878 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00004879 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00004880
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004881 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00004882 llvm::raw_svector_ostream OS(sizeString);
4883 OS << "sizeof(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004884 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00004885 OS << ")";
4886
4887 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4888 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4889 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004890}
4891
Anna Zaksc36bedc2012-02-01 19:08:57 +00004892/// Check if two expressions refer to the same declaration.
4893static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4894 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4895 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4896 return D1->getDecl() == D2->getDecl();
4897 return false;
4898}
4899
4900static const Expr *getStrlenExprArg(const Expr *E) {
4901 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4902 const FunctionDecl *FD = CE->getDirectCallee();
4903 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004904 return nullptr;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004905 return CE->getArg(0)->IgnoreParenCasts();
4906 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004907 return nullptr;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004908}
4909
4910// Warn on anti-patterns as the 'size' argument to strncat.
4911// The correct size argument should look like following:
4912// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4913void Sema::CheckStrncatArguments(const CallExpr *CE,
4914 IdentifierInfo *FnName) {
4915 // Don't crash if the user has the wrong number of arguments.
4916 if (CE->getNumArgs() < 3)
4917 return;
4918 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4919 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4920 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4921
Stephen Hines651f13c2014-04-23 16:59:28 -07004922 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4923 CE->getRParenLoc()))
4924 return;
4925
Anna Zaksc36bedc2012-02-01 19:08:57 +00004926 // Identify common expressions, which are wrongly used as the size argument
4927 // to strncat and may lead to buffer overflows.
4928 unsigned PatternType = 0;
4929 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4930 // - sizeof(dst)
4931 if (referToTheSameDecl(SizeOfArg, DstArg))
4932 PatternType = 1;
4933 // - sizeof(src)
4934 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4935 PatternType = 2;
4936 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4937 if (BE->getOpcode() == BO_Sub) {
4938 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4939 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4940 // - sizeof(dst) - strlen(dst)
4941 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4942 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4943 PatternType = 1;
4944 // - sizeof(src) - (anything)
4945 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4946 PatternType = 2;
4947 }
4948 }
4949
4950 if (PatternType == 0)
4951 return;
4952
Anna Zaksafdb0412012-02-03 01:27:37 +00004953 // Generate the diagnostic.
4954 SourceLocation SL = LenArg->getLocStart();
4955 SourceRange SR = LenArg->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004956 SourceManager &SM = getSourceManager();
Anna Zaksafdb0412012-02-03 01:27:37 +00004957
4958 // If the function is defined as a builtin macro, do not show macro expansion.
4959 if (SM.isMacroArgExpansion(SL)) {
4960 SL = SM.getSpellingLoc(SL);
4961 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4962 SM.getSpellingLoc(SR.getEnd()));
4963 }
4964
Anna Zaks0f38ace2012-08-08 21:42:23 +00004965 // Check if the destination is an array (rather than a pointer to an array).
4966 QualType DstTy = DstArg->getType();
4967 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4968 Context);
4969 if (!isKnownSizeArray) {
4970 if (PatternType == 1)
4971 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4972 else
4973 Diag(SL, diag::warn_strncat_src_size) << SR;
4974 return;
4975 }
4976
Anna Zaksc36bedc2012-02-01 19:08:57 +00004977 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00004978 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004979 else
Anna Zaksafdb0412012-02-03 01:27:37 +00004980 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004981
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004982 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004983 llvm::raw_svector_ostream OS(sizeString);
4984 OS << "sizeof(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004985 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00004986 OS << ") - ";
4987 OS << "strlen(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004988 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00004989 OS << ") - 1";
4990
Anna Zaksafdb0412012-02-03 01:27:37 +00004991 Diag(SL, diag::note_strncat_wrong_size)
4992 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00004993}
4994
Ted Kremenek06de2762007-08-17 16:46:58 +00004995//===--- CHECK: Return Address of Stack Variable --------------------------===//
4996
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004997static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4998 Decl *ParentDecl);
4999static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5000 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005001
5002/// CheckReturnStackAddr - Check if a return statement returns the address
5003/// of a stack variable.
Stephen Hines651f13c2014-04-23 16:59:28 -07005004static void
5005CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5006 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005007
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005008 Expr *stackE = nullptr;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005009 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005010
5011 // Perform checking for returned stack addresses, local blocks,
5012 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00005013 if (lhsType->isPointerType() ||
Stephen Hines651f13c2014-04-23 16:59:28 -07005014 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005015 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005016 } else if (lhsType->isReferenceType()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005017 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005018 }
5019
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005020 if (!stackE)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005021 return; // Nothing suspicious was found.
5022
5023 SourceLocation diagLoc;
5024 SourceRange diagRange;
5025 if (refVars.empty()) {
5026 diagLoc = stackE->getLocStart();
5027 diagRange = stackE->getSourceRange();
5028 } else {
5029 // We followed through a reference variable. 'stackE' contains the
5030 // problematic expression but we will warn at the return statement pointing
5031 // at the reference variable. We will later display the "trail" of
5032 // reference variables using notes.
5033 diagLoc = refVars[0]->getLocStart();
5034 diagRange = refVars[0]->getSourceRange();
5035 }
5036
5037 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Stephen Hines651f13c2014-04-23 16:59:28 -07005038 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005039 : diag::warn_ret_stack_addr)
5040 << DR->getDecl()->getDeclName() << diagRange;
5041 } else if (isa<BlockExpr>(stackE)) { // local block.
Stephen Hines651f13c2014-04-23 16:59:28 -07005042 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005043 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Stephen Hines651f13c2014-04-23 16:59:28 -07005044 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005045 } else { // local temporary.
Stephen Hines651f13c2014-04-23 16:59:28 -07005046 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5047 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005048 << diagRange;
5049 }
5050
5051 // Display the "trail" of reference variables that we followed until we
5052 // found the problematic expression using notes.
5053 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5054 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5055 // If this var binds to another reference var, show the range of the next
5056 // var, otherwise the var binds to the problematic expression, in which case
5057 // show the range of the expression.
5058 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5059 : stackE->getSourceRange();
Stephen Hines651f13c2014-04-23 16:59:28 -07005060 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5061 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00005062 }
5063}
5064
5065/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5066/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005067/// to a location on the stack, a local block, an address of a label, or a
5068/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00005069/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005070/// encounter a subexpression that (1) clearly does not lead to one of the
5071/// above problematic expressions (2) is something we cannot determine leads to
5072/// a problematic expression based on such local checking.
5073///
5074/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5075/// the expression that they point to. Such variables are added to the
5076/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00005077///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00005078/// EvalAddr processes expressions that are pointers that are used as
5079/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005080/// At the base case of the recursion is a check for the above problematic
5081/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00005082///
5083/// This implementation handles:
5084///
5085/// * pointer-to-pointer casts
5086/// * implicit conversions from array references to pointers
5087/// * taking the address of fields
5088/// * arbitrary interplay between "&" and "*" operators
5089/// * pointer arithmetic from an address of a stack variable
5090/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005091static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5092 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005093 if (E->isTypeDependent())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005094 return nullptr;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005095
Ted Kremenek06de2762007-08-17 16:46:58 +00005096 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00005097 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00005098 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005099 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005100 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00005101
Peter Collingbournef111d932011-04-15 00:35:48 +00005102 E = E->IgnoreParens();
5103
Ted Kremenek06de2762007-08-17 16:46:58 +00005104 // Our "symbolic interpreter" is just a dispatch off the currently
5105 // viewed AST node. We then recursively traverse the AST by calling
5106 // EvalAddr and EvalVal appropriately.
5107 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005108 case Stmt::DeclRefExprClass: {
5109 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5110
Stephen Hines651f13c2014-04-23 16:59:28 -07005111 // If we leave the immediate function, the lifetime isn't about to end.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005112 if (DR->refersToEnclosingVariableOrCapture())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005113 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07005114
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005115 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5116 // If this is a reference variable, follow through to the expression that
5117 // it points to.
5118 if (V->hasLocalStorage() &&
5119 V->getType()->isReferenceType() && V->hasInit()) {
5120 // Add the reference variable to the "trail".
5121 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005122 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005123 }
5124
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005125 return nullptr;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005126 }
Ted Kremenek06de2762007-08-17 16:46:58 +00005127
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005128 case Stmt::UnaryOperatorClass: {
5129 // The only unary operator that make sense to handle here
5130 // is AddrOf. All others don't make sense as pointers.
5131 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005132
John McCall2de56d12010-08-25 11:45:40 +00005133 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005134 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005135 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005136 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00005137 }
Mike Stump1eb44332009-09-09 15:08:12 +00005138
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005139 case Stmt::BinaryOperatorClass: {
5140 // Handle pointer arithmetic. All other binary operators are not valid
5141 // in this context.
5142 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00005143 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00005144
John McCall2de56d12010-08-25 11:45:40 +00005145 if (op != BO_Add && op != BO_Sub)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005146 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +00005147
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005148 Expr *Base = B->getLHS();
5149
5150 // Determine which argument is the real pointer base. It could be
5151 // the RHS argument instead of the LHS.
5152 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00005153
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005154 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005155 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005156 }
Steve Naroff61f40a22008-09-10 19:17:48 +00005157
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005158 // For conditional operators we need to see if either the LHS or RHS are
5159 // valid DeclRefExpr*s. If one of them is valid, we return it.
5160 case Stmt::ConditionalOperatorClass: {
5161 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005162
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005163 // Handle the GNU extension for missing LHS.
Stephen Hines651f13c2014-04-23 16:59:28 -07005164 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5165 if (Expr *LHSExpr = C->getLHS()) {
5166 // In C++, we can have a throw-expression, which has 'void' type.
5167 if (!LHSExpr->getType()->isVoidType())
5168 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00005169 return LHS;
5170 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005171
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00005172 // In C++, we can have a throw-expression, which has 'void' type.
5173 if (C->getRHS()->getType()->isVoidType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005174 return nullptr;
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00005175
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005176 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005177 }
Stephen Hines651f13c2014-04-23 16:59:28 -07005178
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005179 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00005180 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005181 return E; // local block.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005182 return nullptr;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005183
5184 case Stmt::AddrLabelExprClass:
5185 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00005186
John McCall80ee6e82011-11-10 05:35:25 +00005187 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005188 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5189 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00005190
Ted Kremenek54b52742008-08-07 00:49:01 +00005191 // For casts, we need to handle conversions from arrays to
5192 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00005193 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00005194 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005195 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00005196 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00005197 case Stmt::CXXStaticCastExprClass:
5198 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00005199 case Stmt::CXXConstCastExprClass:
5200 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00005201 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5202 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8b9414e2012-02-23 23:04:32 +00005203 case CK_LValueToRValue:
5204 case CK_NoOp:
5205 case CK_BaseToDerived:
5206 case CK_DerivedToBase:
5207 case CK_UncheckedDerivedToBase:
5208 case CK_Dynamic:
5209 case CK_CPointerToObjCPointerCast:
5210 case CK_BlockPointerToObjCPointerCast:
5211 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005212 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00005213
5214 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005215 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00005216
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005217 case CK_BitCast:
5218 if (SubExpr->getType()->isAnyPointerType() ||
5219 SubExpr->getType()->isBlockPointerType() ||
5220 SubExpr->getType()->isObjCQualifiedIdType())
5221 return EvalAddr(SubExpr, refVars, ParentDecl);
5222 else
5223 return nullptr;
5224
Eli Friedman8b9414e2012-02-23 23:04:32 +00005225 default:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005226 return nullptr;
Eli Friedman8b9414e2012-02-23 23:04:32 +00005227 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005228 }
Mike Stump1eb44332009-09-09 15:08:12 +00005229
Douglas Gregor03e80032011-06-21 17:03:29 +00005230 case Stmt::MaterializeTemporaryExprClass:
5231 if (Expr *Result = EvalAddr(
5232 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005233 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00005234 return Result;
5235
5236 return E;
5237
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005238 // Everything else: we simply don't reason about them.
5239 default:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005240 return nullptr;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005241 }
Ted Kremenek06de2762007-08-17 16:46:58 +00005242}
Mike Stump1eb44332009-09-09 15:08:12 +00005243
Ted Kremenek06de2762007-08-17 16:46:58 +00005244
5245/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5246/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005247static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5248 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00005249do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00005250 // We should only be called for evaluating non-pointer expressions, or
5251 // expressions with a pointer type that are not used as references but instead
5252 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00005253
Ted Kremenek06de2762007-08-17 16:46:58 +00005254 // Our "symbolic interpreter" is just a dispatch off the currently
5255 // viewed AST node. We then recursively traverse the AST by calling
5256 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00005257
5258 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00005259 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00005260 case Stmt::ImplicitCastExprClass: {
5261 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00005262 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00005263 E = IE->getSubExpr();
5264 continue;
5265 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005266 return nullptr;
Ted Kremenek68957a92010-08-04 20:01:07 +00005267 }
5268
John McCall80ee6e82011-11-10 05:35:25 +00005269 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005270 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00005271
Douglas Gregora2813ce2009-10-23 18:54:35 +00005272 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005273 // When we hit a DeclRefExpr we are looking at code that refers to a
5274 // variable's name. If it's not a reference variable we check if it has
5275 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00005276 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005277
Stephen Hines651f13c2014-04-23 16:59:28 -07005278 // If we leave the immediate function, the lifetime isn't about to end.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005279 if (DR->refersToEnclosingVariableOrCapture())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005280 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07005281
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005282 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5283 // Check if it refers to itself, e.g. "int& i = i;".
5284 if (V == ParentDecl)
5285 return DR;
5286
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005287 if (V->hasLocalStorage()) {
5288 if (!V->getType()->isReferenceType())
5289 return DR;
5290
5291 // Reference variable, follow through to the expression that
5292 // it points to.
5293 if (V->hasInit()) {
5294 // Add the reference variable to the "trail".
5295 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005296 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005297 }
5298 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005299 }
Mike Stump1eb44332009-09-09 15:08:12 +00005300
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005301 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00005302 }
Mike Stump1eb44332009-09-09 15:08:12 +00005303
Ted Kremenek06de2762007-08-17 16:46:58 +00005304 case Stmt::UnaryOperatorClass: {
5305 // The only unary operator that make sense to handle here
5306 // is Deref. All others don't resolve to a "name." This includes
5307 // handling all sorts of rvalues passed to a unary operator.
5308 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005309
John McCall2de56d12010-08-25 11:45:40 +00005310 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005311 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005312
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005313 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00005314 }
Mike Stump1eb44332009-09-09 15:08:12 +00005315
Ted Kremenek06de2762007-08-17 16:46:58 +00005316 case Stmt::ArraySubscriptExprClass: {
5317 // Array subscripts are potential references to data on the stack. We
5318 // retrieve the DeclRefExpr* for the array variable if it indeed
5319 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005320 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005321 }
Mike Stump1eb44332009-09-09 15:08:12 +00005322
Ted Kremenek06de2762007-08-17 16:46:58 +00005323 case Stmt::ConditionalOperatorClass: {
5324 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005325 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00005326 ConditionalOperator *C = cast<ConditionalOperator>(E);
5327
Anders Carlsson39073232007-11-30 19:04:31 +00005328 // Handle the GNU extension for missing LHS.
Stephen Hines651f13c2014-04-23 16:59:28 -07005329 if (Expr *LHSExpr = C->getLHS()) {
5330 // In C++, we can have a throw-expression, which has 'void' type.
5331 if (!LHSExpr->getType()->isVoidType())
5332 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5333 return LHS;
5334 }
5335
5336 // In C++, we can have a throw-expression, which has 'void' type.
5337 if (C->getRHS()->getType()->isVoidType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005338 return nullptr;
Anders Carlsson39073232007-11-30 19:04:31 +00005339
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005340 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005341 }
Mike Stump1eb44332009-09-09 15:08:12 +00005342
Ted Kremenek06de2762007-08-17 16:46:58 +00005343 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00005344 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00005345 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005346
Ted Kremenek06de2762007-08-17 16:46:58 +00005347 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00005348 if (M->isArrow())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005349 return nullptr;
Ted Kremeneka423e812010-09-02 01:12:13 +00005350
5351 // Check whether the member type is itself a reference, in which case
5352 // we're not going to refer to the member, but to what the member refers to.
5353 if (M->getMemberDecl()->getType()->isReferenceType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005354 return nullptr;
Ted Kremeneka423e812010-09-02 01:12:13 +00005355
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005356 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005357 }
Mike Stump1eb44332009-09-09 15:08:12 +00005358
Douglas Gregor03e80032011-06-21 17:03:29 +00005359 case Stmt::MaterializeTemporaryExprClass:
5360 if (Expr *Result = EvalVal(
5361 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005362 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00005363 return Result;
5364
5365 return E;
5366
Ted Kremenek06de2762007-08-17 16:46:58 +00005367 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005368 // Check that we don't return or take the address of a reference to a
5369 // temporary. This is only useful in C++.
5370 if (!E->isTypeDependent() && E->isRValue())
5371 return E;
5372
5373 // Everything else: we simply don't reason about them.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005374 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00005375 }
Ted Kremenek68957a92010-08-04 20:01:07 +00005376} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00005377}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005378
Stephen Hines651f13c2014-04-23 16:59:28 -07005379void
5380Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5381 SourceLocation ReturnLoc,
5382 bool isObjCMethod,
5383 const AttrVec *Attrs,
5384 const FunctionDecl *FD) {
5385 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5386
5387 // Check if the return value is null but should not be.
5388 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5389 CheckNonNullExpr(*this, RetValExp))
5390 Diag(ReturnLoc, diag::warn_null_ret)
5391 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
5392
5393 // C++11 [basic.stc.dynamic.allocation]p4:
5394 // If an allocation function declared with a non-throwing
5395 // exception-specification fails to allocate storage, it shall return
5396 // a null pointer. Any other allocation function that fails to allocate
5397 // storage shall indicate failure only by throwing an exception [...]
5398 if (FD) {
5399 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5400 if (Op == OO_New || Op == OO_Array_New) {
5401 const FunctionProtoType *Proto
5402 = FD->getType()->castAs<FunctionProtoType>();
5403 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5404 CheckNonNullExpr(*this, RetValExp))
5405 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5406 << FD << getLangOpts().CPlusPlus11;
5407 }
5408 }
5409}
5410
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005411//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5412
5413/// Check for comparisons of floating point operands using != and ==.
5414/// Issue a warning if these are no self-comparisons, as they are not likely
5415/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00005416void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00005417 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5418 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005419
5420 // Special case: check for x == x (which is OK).
5421 // Do not emit warnings for such cases.
5422 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5423 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5424 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00005425 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005426
5427
Ted Kremenek1b500bb2007-11-29 00:59:04 +00005428 // Special case: check for comparisons against literals that can be exactly
5429 // represented by APFloat. In such cases, do not emit a warning. This
5430 // is a heuristic: often comparison against such literals are used to
5431 // detect if a value in a variable has not changed. This clearly can
5432 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00005433 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5434 if (FLL->isExact())
5435 return;
5436 } else
5437 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5438 if (FLR->isExact())
5439 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005440
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005441 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00005442 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Stephen Hines651f13c2014-04-23 16:59:28 -07005443 if (CL->getBuiltinCallee())
David Blaikie980343b2012-07-16 20:47:22 +00005444 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005445
David Blaikie980343b2012-07-16 20:47:22 +00005446 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Stephen Hines651f13c2014-04-23 16:59:28 -07005447 if (CR->getBuiltinCallee())
David Blaikie980343b2012-07-16 20:47:22 +00005448 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005449
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005450 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00005451 Diag(Loc, diag::warn_floatingpoint_eq)
5452 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005453}
John McCallba26e582010-01-04 23:21:16 +00005454
John McCallf2370c92010-01-06 05:24:50 +00005455//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5456//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00005457
John McCallf2370c92010-01-06 05:24:50 +00005458namespace {
John McCallba26e582010-01-04 23:21:16 +00005459
John McCallf2370c92010-01-06 05:24:50 +00005460/// Structure recording the 'active' range of an integer-valued
5461/// expression.
5462struct IntRange {
5463 /// The number of bits active in the int.
5464 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00005465
John McCallf2370c92010-01-06 05:24:50 +00005466 /// True if the int is known not to have negative values.
5467 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00005468
John McCallf2370c92010-01-06 05:24:50 +00005469 IntRange(unsigned Width, bool NonNegative)
5470 : Width(Width), NonNegative(NonNegative)
5471 {}
John McCallba26e582010-01-04 23:21:16 +00005472
John McCall1844a6e2010-11-10 23:38:19 +00005473 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00005474 static IntRange forBoolType() {
5475 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00005476 }
5477
John McCall1844a6e2010-11-10 23:38:19 +00005478 /// Returns the range of an opaque value of the given integral type.
5479 static IntRange forValueOfType(ASTContext &C, QualType T) {
5480 return forValueOfCanonicalType(C,
5481 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00005482 }
5483
John McCall1844a6e2010-11-10 23:38:19 +00005484 /// Returns the range of an opaque value of a canonical integral type.
5485 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00005486 assert(T->isCanonicalUnqualified());
5487
5488 if (const VectorType *VT = dyn_cast<VectorType>(T))
5489 T = VT->getElementType().getTypePtr();
5490 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5491 T = CT->getElementType().getTypePtr();
Stephen Hines176edba2014-12-01 14:53:08 -08005492 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5493 T = AT->getValueType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00005494
David Majnemerf9eaf982013-06-07 22:07:20 +00005495 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00005496 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00005497 EnumDecl *Enum = ET->getDecl();
5498 if (!Enum->isCompleteDefinition())
5499 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00005500
David Majnemerf9eaf982013-06-07 22:07:20 +00005501 unsigned NumPositive = Enum->getNumPositiveBits();
5502 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00005503
David Majnemerf9eaf982013-06-07 22:07:20 +00005504 if (NumNegative == 0)
5505 return IntRange(NumPositive, true/*NonNegative*/);
5506 else
5507 return IntRange(std::max(NumPositive + 1, NumNegative),
5508 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00005509 }
John McCallf2370c92010-01-06 05:24:50 +00005510
5511 const BuiltinType *BT = cast<BuiltinType>(T);
5512 assert(BT->isInteger());
5513
5514 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5515 }
5516
John McCall1844a6e2010-11-10 23:38:19 +00005517 /// Returns the "target" range of a canonical integral type, i.e.
5518 /// the range of values expressible in the type.
5519 ///
5520 /// This matches forValueOfCanonicalType except that enums have the
5521 /// full range of their type, not the range of their enumerators.
5522 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5523 assert(T->isCanonicalUnqualified());
5524
5525 if (const VectorType *VT = dyn_cast<VectorType>(T))
5526 T = VT->getElementType().getTypePtr();
5527 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5528 T = CT->getElementType().getTypePtr();
Stephen Hines176edba2014-12-01 14:53:08 -08005529 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5530 T = AT->getValueType().getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00005531 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00005532 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00005533
5534 const BuiltinType *BT = cast<BuiltinType>(T);
5535 assert(BT->isInteger());
5536
5537 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5538 }
5539
5540 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00005541 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00005542 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00005543 L.NonNegative && R.NonNegative);
5544 }
5545
John McCall1844a6e2010-11-10 23:38:19 +00005546 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00005547 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00005548 return IntRange(std::min(L.Width, R.Width),
5549 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00005550 }
5551};
5552
Ted Kremenek0692a192012-01-31 05:37:37 +00005553static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5554 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00005555 if (value.isSigned() && value.isNegative())
5556 return IntRange(value.getMinSignedBits(), false);
5557
5558 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00005559 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00005560
5561 // isNonNegative() just checks the sign bit without considering
5562 // signedness.
5563 return IntRange(value.getActiveBits(), true);
5564}
5565
Ted Kremenek0692a192012-01-31 05:37:37 +00005566static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5567 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00005568 if (result.isInt())
5569 return GetValueRange(C, result.getInt(), MaxWidth);
5570
5571 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00005572 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5573 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5574 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5575 R = IntRange::join(R, El);
5576 }
John McCallf2370c92010-01-06 05:24:50 +00005577 return R;
5578 }
5579
5580 if (result.isComplexInt()) {
5581 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5582 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5583 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00005584 }
5585
5586 // This can happen with lossless casts to intptr_t of "based" lvalues.
5587 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00005588 // FIXME: The only reason we need to pass the type in here is to get
5589 // the sign right on this one case. It would be nice if APValue
5590 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00005591 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00005592 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00005593}
John McCallf2370c92010-01-06 05:24:50 +00005594
Eli Friedman09bddcf2013-07-08 20:20:06 +00005595static QualType GetExprType(Expr *E) {
5596 QualType Ty = E->getType();
5597 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5598 Ty = AtomicRHS->getValueType();
5599 return Ty;
5600}
5601
John McCallf2370c92010-01-06 05:24:50 +00005602/// Pseudo-evaluate the given integer expression, estimating the
5603/// range of values it might take.
5604///
5605/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00005606static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00005607 E = E->IgnoreParens();
5608
5609 // Try a full evaluation first.
5610 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005611 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00005612 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00005613
5614 // I think we only want to look through implicit casts here; if the
5615 // user has an explicit widening cast, we should treat the value as
5616 // being of the new, wider type.
5617 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00005618 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00005619 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5620
Eli Friedman09bddcf2013-07-08 20:20:06 +00005621 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00005622
John McCall2de56d12010-08-25 11:45:40 +00005623 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00005624
John McCallf2370c92010-01-06 05:24:50 +00005625 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00005626 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00005627 return OutputTypeRange;
5628
5629 IntRange SubRange
5630 = GetExprRange(C, CE->getSubExpr(),
5631 std::min(MaxWidth, OutputTypeRange.Width));
5632
5633 // Bail out if the subexpr's range is as wide as the cast type.
5634 if (SubRange.Width >= OutputTypeRange.Width)
5635 return OutputTypeRange;
5636
5637 // Otherwise, we take the smaller width, and we're non-negative if
5638 // either the output type or the subexpr is.
5639 return IntRange(SubRange.Width,
5640 SubRange.NonNegative || OutputTypeRange.NonNegative);
5641 }
5642
5643 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5644 // If we can fold the condition, just take that operand.
5645 bool CondResult;
5646 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5647 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5648 : CO->getFalseExpr(),
5649 MaxWidth);
5650
5651 // Otherwise, conservatively merge.
5652 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5653 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5654 return IntRange::join(L, R);
5655 }
5656
5657 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5658 switch (BO->getOpcode()) {
5659
5660 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00005661 case BO_LAnd:
5662 case BO_LOr:
5663 case BO_LT:
5664 case BO_GT:
5665 case BO_LE:
5666 case BO_GE:
5667 case BO_EQ:
5668 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00005669 return IntRange::forBoolType();
5670
John McCall862ff872011-07-13 06:35:24 +00005671 // The type of the assignments is the type of the LHS, so the RHS
5672 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00005673 case BO_MulAssign:
5674 case BO_DivAssign:
5675 case BO_RemAssign:
5676 case BO_AddAssign:
5677 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00005678 case BO_XorAssign:
5679 case BO_OrAssign:
5680 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00005681 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00005682
John McCall862ff872011-07-13 06:35:24 +00005683 // Simple assignments just pass through the RHS, which will have
5684 // been coerced to the LHS type.
5685 case BO_Assign:
5686 // TODO: bitfields?
5687 return GetExprRange(C, BO->getRHS(), MaxWidth);
5688
John McCallf2370c92010-01-06 05:24:50 +00005689 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00005690 case BO_PtrMemD:
5691 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00005692 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005693
John McCall60fad452010-01-06 22:07:33 +00005694 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00005695 case BO_And:
5696 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00005697 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5698 GetExprRange(C, BO->getRHS(), MaxWidth));
5699
John McCallf2370c92010-01-06 05:24:50 +00005700 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00005701 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00005702 // ...except that we want to treat '1 << (blah)' as logically
5703 // positive. It's an important idiom.
5704 if (IntegerLiteral *I
5705 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5706 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00005707 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00005708 return IntRange(R.Width, /*NonNegative*/ true);
5709 }
5710 }
5711 // fallthrough
5712
John McCall2de56d12010-08-25 11:45:40 +00005713 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00005714 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005715
John McCall60fad452010-01-06 22:07:33 +00005716 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00005717 case BO_Shr:
5718 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00005719 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5720
5721 // If the shift amount is a positive constant, drop the width by
5722 // that much.
5723 llvm::APSInt shift;
5724 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5725 shift.isNonNegative()) {
5726 unsigned zext = shift.getZExtValue();
5727 if (zext >= L.Width)
5728 L.Width = (L.NonNegative ? 0 : 1);
5729 else
5730 L.Width -= zext;
5731 }
5732
5733 return L;
5734 }
5735
5736 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00005737 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00005738 return GetExprRange(C, BO->getRHS(), MaxWidth);
5739
John McCall60fad452010-01-06 22:07:33 +00005740 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00005741 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00005742 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00005743 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005744 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00005745
John McCall00fe7612011-07-14 22:39:48 +00005746 // The width of a division result is mostly determined by the size
5747 // of the LHS.
5748 case BO_Div: {
5749 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00005750 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005751 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5752
5753 // If the divisor is constant, use that.
5754 llvm::APSInt divisor;
5755 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5756 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5757 if (log2 >= L.Width)
5758 L.Width = (L.NonNegative ? 0 : 1);
5759 else
5760 L.Width = std::min(L.Width - log2, MaxWidth);
5761 return L;
5762 }
5763
5764 // Otherwise, just use the LHS's width.
5765 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5766 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5767 }
5768
5769 // The result of a remainder can't be larger than the result of
5770 // either side.
5771 case BO_Rem: {
5772 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00005773 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005774 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5775 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5776
5777 IntRange meet = IntRange::meet(L, R);
5778 meet.Width = std::min(meet.Width, MaxWidth);
5779 return meet;
5780 }
5781
5782 // The default behavior is okay for these.
5783 case BO_Mul:
5784 case BO_Add:
5785 case BO_Xor:
5786 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00005787 break;
5788 }
5789
John McCall00fe7612011-07-14 22:39:48 +00005790 // The default case is to treat the operation as if it were closed
5791 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00005792 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5793 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5794 return IntRange::join(L, R);
5795 }
5796
5797 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5798 switch (UO->getOpcode()) {
5799 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00005800 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00005801 return IntRange::forBoolType();
5802
5803 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00005804 case UO_Deref:
5805 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00005806 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005807
5808 default:
5809 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5810 }
5811 }
5812
Ted Kremenek728a1fb2013-10-14 18:55:27 +00005813 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5814 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5815
John McCall993f43f2013-05-06 21:39:12 +00005816 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005817 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00005818 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00005819
Eli Friedman09bddcf2013-07-08 20:20:06 +00005820 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005821}
John McCall51313c32010-01-04 23:31:57 +00005822
Ted Kremenek0692a192012-01-31 05:37:37 +00005823static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00005824 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00005825}
5826
John McCall51313c32010-01-04 23:31:57 +00005827/// Checks whether the given value, which currently has the given
5828/// source semantics, has the same value when coerced through the
5829/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00005830static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5831 const llvm::fltSemantics &Src,
5832 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00005833 llvm::APFloat truncated = value;
5834
5835 bool ignored;
5836 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5837 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5838
5839 return truncated.bitwiseIsEqual(value);
5840}
5841
5842/// Checks whether the given value, which currently has the given
5843/// source semantics, has the same value when coerced through the
5844/// target semantics.
5845///
5846/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00005847static bool IsSameFloatAfterCast(const APValue &value,
5848 const llvm::fltSemantics &Src,
5849 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00005850 if (value.isFloat())
5851 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5852
5853 if (value.isVector()) {
5854 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5855 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5856 return false;
5857 return true;
5858 }
5859
5860 assert(value.isComplexFloat());
5861 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5862 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5863}
5864
Ted Kremenek0692a192012-01-31 05:37:37 +00005865static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00005866
Ted Kremeneke3b159c2010-09-23 21:43:44 +00005867static bool IsZero(Sema &S, Expr *E) {
5868 // Suppress cases where we are comparing against an enum constant.
5869 if (const DeclRefExpr *DR =
5870 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5871 if (isa<EnumConstantDecl>(DR->getDecl()))
5872 return false;
5873
5874 // Suppress cases where the '0' value is expanded from a macro.
5875 if (E->getLocStart().isMacroID())
5876 return false;
5877
John McCall323ed742010-05-06 08:58:33 +00005878 llvm::APSInt Value;
5879 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5880}
5881
John McCall372e1032010-10-06 00:25:24 +00005882static bool HasEnumType(Expr *E) {
5883 // Strip off implicit integral promotions.
5884 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00005885 if (ICE->getCastKind() != CK_IntegralCast &&
5886 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00005887 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00005888 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00005889 }
5890
5891 return E->getType()->isEnumeralType();
5892}
5893
Ted Kremenek0692a192012-01-31 05:37:37 +00005894static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieucbc19872013-11-01 21:47:19 +00005895 // Disable warning in template instantiations.
5896 if (!S.ActiveTemplateInstantiations.empty())
5897 return;
5898
John McCall2de56d12010-08-25 11:45:40 +00005899 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00005900 if (E->isValueDependent())
5901 return;
5902
John McCall2de56d12010-08-25 11:45:40 +00005903 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00005904 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005905 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00005906 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005907 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00005908 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005909 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00005910 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005911 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00005912 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005913 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00005914 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005915 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00005916 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005917 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00005918 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5919 }
5920}
5921
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005922static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005923 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005924 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005925 bool RhsConstant) {
Richard Trieu311cb2b2013-11-01 21:19:43 +00005926 // Disable warning in template instantiations.
5927 if (!S.ActiveTemplateInstantiations.empty())
5928 return;
5929
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005930 // TODO: Investigate using GetExprRange() to get tighter bounds
5931 // on the bit ranges.
5932 QualType OtherT = Other->getType();
Stephen Hines176edba2014-12-01 14:53:08 -08005933 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5934 OtherT = AT->getValueType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005935 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5936 unsigned OtherWidth = OtherRange.Width;
5937
5938 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5939
Richard Trieu526e6272012-11-14 22:50:24 +00005940 // 0 values are handled later by CheckTrivialUnsignedComparison().
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005941 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu526e6272012-11-14 22:50:24 +00005942 return;
5943
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005944 BinaryOperatorKind op = E->getOpcode();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005945 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00005946
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005947 // Used for diagnostic printout.
5948 enum {
5949 LiteralConstant = 0,
5950 CXXBoolLiteralTrue,
5951 CXXBoolLiteralFalse
5952 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu526e6272012-11-14 22:50:24 +00005953
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005954 if (!OtherIsBooleanType) {
5955 QualType ConstantT = Constant->getType();
5956 QualType CommonT = E->getLHS()->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00005957
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005958 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5959 return;
5960 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5961 "comparison with non-integer type");
5962
5963 bool ConstantSigned = ConstantT->isSignedIntegerType();
5964 bool CommonSigned = CommonT->isSignedIntegerType();
5965
5966 bool EqualityOnly = false;
5967
5968 if (CommonSigned) {
5969 // The common type is signed, therefore no signed to unsigned conversion.
5970 if (!OtherRange.NonNegative) {
5971 // Check that the constant is representable in type OtherT.
5972 if (ConstantSigned) {
5973 if (OtherWidth >= Value.getMinSignedBits())
5974 return;
5975 } else { // !ConstantSigned
5976 if (OtherWidth >= Value.getActiveBits() + 1)
5977 return;
5978 }
5979 } else { // !OtherSigned
5980 // Check that the constant is representable in type OtherT.
5981 // Negative values are out of range.
5982 if (ConstantSigned) {
5983 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5984 return;
5985 } else { // !ConstantSigned
5986 if (OtherWidth >= Value.getActiveBits())
5987 return;
5988 }
Richard Trieu526e6272012-11-14 22:50:24 +00005989 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005990 } else { // !CommonSigned
5991 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00005992 if (OtherWidth >= Value.getActiveBits())
5993 return;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005994 } else { // OtherSigned
5995 assert(!ConstantSigned &&
5996 "Two signed types converted to unsigned types.");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005997 // Check to see if the constant is representable in OtherT.
5998 if (OtherWidth > Value.getActiveBits())
5999 return;
6000 // Check to see if the constant is equivalent to a negative value
6001 // cast to CommonT.
6002 if (S.Context.getIntWidth(ConstantT) ==
6003 S.Context.getIntWidth(CommonT) &&
6004 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6005 return;
6006 // The constant value rests between values that OtherT can represent
6007 // after conversion. Relational comparison still works, but equality
6008 // comparisons will be tautological.
6009 EqualityOnly = true;
Richard Trieu526e6272012-11-14 22:50:24 +00006010 }
6011 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006012
6013 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6014
6015 if (op == BO_EQ || op == BO_NE) {
6016 IsTrue = op == BO_NE;
6017 } else if (EqualityOnly) {
6018 return;
6019 } else if (RhsConstant) {
6020 if (op == BO_GT || op == BO_GE)
6021 IsTrue = !PositiveConstant;
6022 else // op == BO_LT || op == BO_LE
6023 IsTrue = PositiveConstant;
6024 } else {
6025 if (op == BO_LT || op == BO_LE)
6026 IsTrue = !PositiveConstant;
6027 else // op == BO_GT || op == BO_GE
6028 IsTrue = PositiveConstant;
Richard Trieu526e6272012-11-14 22:50:24 +00006029 }
Fariborz Jahaniana193f202012-09-20 19:36:41 +00006030 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006031 // Other isKnownToHaveBooleanValue
6032 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6033 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6034 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6035
6036 static const struct LinkedConditions {
6037 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6038 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6039 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6040 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6041 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6042 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6043
6044 } TruthTable = {
6045 // Constant on LHS. | Constant on RHS. |
6046 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6047 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6048 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6049 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6050 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6051 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6052 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6053 };
6054
6055 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6056
6057 enum ConstantValue ConstVal = Zero;
6058 if (Value.isUnsigned() || Value.isNonNegative()) {
6059 if (Value == 0) {
6060 LiteralOrBoolConstant =
6061 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6062 ConstVal = Zero;
6063 } else if (Value == 1) {
6064 LiteralOrBoolConstant =
6065 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6066 ConstVal = One;
6067 } else {
6068 LiteralOrBoolConstant = LiteralConstant;
6069 ConstVal = GT_One;
6070 }
6071 } else {
6072 ConstVal = LT_Zero;
6073 }
6074
6075 CompareBoolWithConstantResult CmpRes;
6076
6077 switch (op) {
6078 case BO_LT:
6079 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6080 break;
6081 case BO_GT:
6082 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6083 break;
6084 case BO_LE:
6085 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6086 break;
6087 case BO_GE:
6088 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6089 break;
6090 case BO_EQ:
6091 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6092 break;
6093 case BO_NE:
6094 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6095 break;
6096 default:
6097 CmpRes = Unkwn;
6098 break;
6099 }
6100
6101 if (CmpRes == AFals) {
6102 IsTrue = false;
6103 } else if (CmpRes == ATrue) {
6104 IsTrue = true;
6105 } else {
6106 return;
6107 }
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006108 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00006109
6110 // If this is a comparison to an enum constant, include that
6111 // constant in the diagnostic.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006112 const EnumConstantDecl *ED = nullptr;
Ted Kremenek7adf3a92013-03-15 21:50:10 +00006113 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6114 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6115
6116 SmallString<64> PrettySourceValue;
6117 llvm::raw_svector_ostream OS(PrettySourceValue);
6118 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00006119 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00006120 else
6121 OS << Value;
6122
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006123 S.DiagRuntimeBehavior(
6124 E->getOperatorLoc(), E,
6125 S.PDiag(diag::warn_out_of_range_compare)
6126 << OS.str() << LiteralOrBoolConstant
6127 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6128 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006129}
6130
John McCall323ed742010-05-06 08:58:33 +00006131/// Analyze the operands of the given comparison. Implements the
6132/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00006133static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00006134 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6135 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00006136}
John McCall51313c32010-01-04 23:31:57 +00006137
John McCallba26e582010-01-04 23:21:16 +00006138/// \brief Implements -Wsign-compare.
6139///
Richard Trieudd225092011-09-15 21:56:47 +00006140/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00006141static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00006142 // The type the comparison is being performed in.
6143 QualType T = E->getLHS()->getType();
Stephen Hines176edba2014-12-01 14:53:08 -08006144
6145 // Only analyze comparison operators where both sides have been converted to
6146 // the same type.
6147 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6148 return AnalyzeImpConvsInComparison(S, E);
6149
6150 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00006151 if (E->isValueDependent())
6152 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00006153
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006154 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6155 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006156
6157 bool IsComparisonConstant = false;
6158
Fariborz Jahaniana193f202012-09-20 19:36:41 +00006159 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006160 // of 'true' or 'false'.
6161 if (T->isIntegralType(S.Context)) {
6162 llvm::APSInt RHSValue;
6163 bool IsRHSIntegralLiteral =
6164 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6165 llvm::APSInt LHSValue;
6166 bool IsLHSIntegralLiteral =
6167 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6168 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6169 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6170 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6171 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6172 else
6173 IsComparisonConstant =
6174 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00006175 } else if (!T->hasUnsignedIntegerRepresentation())
6176 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006177
John McCall323ed742010-05-06 08:58:33 +00006178 // We don't do anything special if this isn't an unsigned integral
6179 // comparison: we're only interested in integral comparisons, and
6180 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00006181 //
6182 // We also don't care about value-dependent expressions or expressions
6183 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006184 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00006185 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006186
John McCall323ed742010-05-06 08:58:33 +00006187 // Check to see if one of the (unmodified) operands is of different
6188 // signedness.
6189 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00006190 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6191 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00006192 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00006193 signedOperand = LHS;
6194 unsignedOperand = RHS;
6195 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6196 signedOperand = RHS;
6197 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00006198 } else {
John McCall323ed742010-05-06 08:58:33 +00006199 CheckTrivialUnsignedComparison(S, E);
6200 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00006201 }
6202
John McCall323ed742010-05-06 08:58:33 +00006203 // Otherwise, calculate the effective range of the signed operand.
6204 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00006205
John McCall323ed742010-05-06 08:58:33 +00006206 // Go ahead and analyze implicit conversions in the operands. Note
6207 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00006208 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6209 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00006210
John McCall323ed742010-05-06 08:58:33 +00006211 // If the signed range is non-negative, -Wsign-compare won't fire,
6212 // but we should still check for comparisons which are always true
6213 // or false.
6214 if (signedRange.NonNegative)
6215 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00006216
6217 // For (in)equality comparisons, if the unsigned operand is a
6218 // constant which cannot collide with a overflowed signed operand,
6219 // then reinterpreting the signed operand as unsigned will not
6220 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00006221 if (E->isEqualityOp()) {
6222 unsigned comparisonWidth = S.Context.getIntWidth(T);
6223 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00006224
John McCall323ed742010-05-06 08:58:33 +00006225 // We should never be unable to prove that the unsigned operand is
6226 // non-negative.
6227 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6228
6229 if (unsignedRange.Width < comparisonWidth)
6230 return;
6231 }
6232
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00006233 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6234 S.PDiag(diag::warn_mixed_sign_comparison)
6235 << LHS->getType() << RHS->getType()
6236 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00006237}
6238
John McCall15d7d122010-11-11 03:21:53 +00006239/// Analyzes an attempt to assign the given value to a bitfield.
6240///
6241/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00006242static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6243 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00006244 assert(Bitfield->isBitField());
6245 if (Bitfield->isInvalidDecl())
6246 return false;
6247
John McCall91b60142010-11-11 05:33:51 +00006248 // White-list bool bitfields.
6249 if (Bitfield->getType()->isBooleanType())
6250 return false;
6251
Douglas Gregor46ff3032011-02-04 13:09:01 +00006252 // Ignore value- or type-dependent expressions.
6253 if (Bitfield->getBitWidth()->isValueDependent() ||
6254 Bitfield->getBitWidth()->isTypeDependent() ||
6255 Init->isValueDependent() ||
6256 Init->isTypeDependent())
6257 return false;
6258
John McCall15d7d122010-11-11 03:21:53 +00006259 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6260
Richard Smith80d4b552011-12-28 19:48:30 +00006261 llvm::APSInt Value;
6262 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00006263 return false;
6264
John McCall15d7d122010-11-11 03:21:53 +00006265 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006266 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00006267
6268 if (OriginalWidth <= FieldWidth)
6269 return false;
6270
Eli Friedman3a643af2012-01-26 23:11:39 +00006271 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00006272 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00006273 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00006274
Eli Friedman3a643af2012-01-26 23:11:39 +00006275 // Check whether the stored value is equal to the original value.
6276 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00006277 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00006278 return false;
6279
Eli Friedman3a643af2012-01-26 23:11:39 +00006280 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00006281 // therefore don't strictly fit into a signed bitfield of width 1.
6282 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00006283 return false;
6284
John McCall15d7d122010-11-11 03:21:53 +00006285 std::string PrettyValue = Value.toString(10);
6286 std::string PrettyTrunc = TruncatedValue.toString(10);
6287
6288 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6289 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6290 << Init->getSourceRange();
6291
6292 return true;
6293}
6294
John McCallbeb22aa2010-11-09 23:24:47 +00006295/// Analyze the given simple or compound assignment for warning-worthy
6296/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00006297static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00006298 // Just recurse on the LHS.
6299 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6300
6301 // We want to recurse on the RHS as normal unless we're assigning to
6302 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00006303 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006304 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00006305 E->getOperatorLoc())) {
6306 // Recurse, ignoring any implicit conversions on the RHS.
6307 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6308 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00006309 }
6310 }
6311
6312 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6313}
6314
John McCall51313c32010-01-04 23:31:57 +00006315/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00006316static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00006317 SourceLocation CContext, unsigned diag,
6318 bool pruneControlFlow = false) {
6319 if (pruneControlFlow) {
6320 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6321 S.PDiag(diag)
6322 << SourceType << T << E->getSourceRange()
6323 << SourceRange(CContext));
6324 return;
6325 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006326 S.Diag(E->getExprLoc(), diag)
6327 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6328}
6329
Chandler Carruthe1b02e02011-04-05 06:47:57 +00006330/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00006331static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00006332 SourceLocation CContext, unsigned diag,
6333 bool pruneControlFlow = false) {
6334 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00006335}
6336
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006337/// Diagnose an implicit cast from a literal expression. Does not warn when the
6338/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00006339void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6340 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006341 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00006342 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006343 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00006344 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6345 T->hasUnsignedIntegerRepresentation());
6346 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00006347 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006348 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00006349 return;
6350
Eli Friedman4e1a82c2013-08-29 23:44:43 +00006351 // FIXME: Force the precision of the source value down so we don't print
6352 // digits which are usually useless (we don't really care here if we
6353 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6354 // would automatically print the shortest representation, but it's a bit
6355 // tricky to implement.
David Blaikiebe0ee872012-05-15 16:56:36 +00006356 SmallString<16> PrettySourceValue;
Eli Friedman4e1a82c2013-08-29 23:44:43 +00006357 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6358 precision = (precision * 59 + 195) / 196;
6359 Value.toString(PrettySourceValue, precision);
6360
David Blaikiede7e7b82012-05-15 17:18:27 +00006361 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00006362 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6363 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6364 else
David Blaikiede7e7b82012-05-15 17:18:27 +00006365 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00006366
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006367 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00006368 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6369 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00006370}
6371
John McCall091f23f2010-11-09 22:22:12 +00006372std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6373 if (!Range.Width) return "0";
6374
6375 llvm::APSInt ValueInRange = Value;
6376 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00006377 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00006378 return ValueInRange.toString(10);
6379}
6380
Hans Wennborg88617a22012-08-28 15:44:30 +00006381static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6382 if (!isa<ImplicitCastExpr>(Ex))
6383 return false;
6384
6385 Expr *InnerE = Ex->IgnoreParenImpCasts();
6386 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6387 const Type *Source =
6388 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6389 if (Target->isDependentType())
6390 return false;
6391
6392 const BuiltinType *FloatCandidateBT =
6393 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6394 const Type *BoolCandidateType = ToBool ? Target : Source;
6395
6396 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6397 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6398}
6399
6400void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6401 SourceLocation CC) {
6402 unsigned NumArgs = TheCall->getNumArgs();
6403 for (unsigned i = 0; i < NumArgs; ++i) {
6404 Expr *CurrA = TheCall->getArg(i);
6405 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6406 continue;
6407
6408 bool IsSwapped = ((i > 0) &&
6409 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6410 IsSwapped |= ((i < (NumArgs - 1)) &&
6411 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6412 if (IsSwapped) {
6413 // Warn on this floating-point to bool conversion.
6414 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6415 CurrA->getType(), CC,
6416 diag::warn_impcast_floating_point_to_bool);
6417 }
6418 }
6419}
6420
Stephen Hines176edba2014-12-01 14:53:08 -08006421static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6422 SourceLocation CC) {
6423 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6424 E->getExprLoc()))
6425 return;
6426
6427 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6428 const Expr::NullPointerConstantKind NullKind =
6429 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6430 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6431 return;
6432
6433 // Return if target type is a safe conversion.
6434 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6435 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6436 return;
6437
6438 SourceLocation Loc = E->getSourceRange().getBegin();
6439
6440 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6441 if (NullKind == Expr::NPCK_GNUNull) {
6442 if (Loc.isMacroID())
6443 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6444 }
6445
6446 // Only warn if the null and context location are in the same macro expansion.
6447 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6448 return;
6449
6450 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6451 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6452 << FixItHint::CreateReplacement(Loc,
6453 S.getFixItZeroLiteralForType(T, Loc));
6454}
6455
John McCall323ed742010-05-06 08:58:33 +00006456void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006457 SourceLocation CC, bool *ICContext = nullptr) {
John McCall323ed742010-05-06 08:58:33 +00006458 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00006459
John McCall323ed742010-05-06 08:58:33 +00006460 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6461 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6462 if (Source == Target) return;
6463 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00006464
Chandler Carruth108f7562011-07-26 05:40:03 +00006465 // If the conversion context location is invalid don't complain. We also
6466 // don't want to emit a warning if the issue occurs from the expansion of
6467 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6468 // delay this check as long as possible. Once we detect we are in that
6469 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00006470 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00006471 return;
6472
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006473 // Diagnose implicit casts to bool.
6474 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6475 if (isa<StringLiteral>(E))
6476 // Warn on string literal to bool. Checks for string literals in logical
Stephen Hines651f13c2014-04-23 16:59:28 -07006477 // and expressions, for instance, assert(0 && "error here"), are
6478 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006479 return DiagnoseImpCast(S, E, T, CC,
6480 diag::warn_impcast_string_literal_to_bool);
Stephen Hines651f13c2014-04-23 16:59:28 -07006481 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6482 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6483 // This covers the literal expressions that evaluate to Objective-C
6484 // objects.
6485 return DiagnoseImpCast(S, E, T, CC,
6486 diag::warn_impcast_objective_c_literal_to_bool);
6487 }
6488 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6489 // Warn on pointer to bool conversion that is always true.
6490 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6491 SourceRange(CC));
Lang Hamese14ca9f2011-12-05 20:49:50 +00006492 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006493 }
John McCall51313c32010-01-04 23:31:57 +00006494
6495 // Strip vector types.
6496 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00006497 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006498 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006499 return;
John McCallb4eb64d2010-10-08 02:01:28 +00006500 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00006501 }
Chris Lattnerb792b302011-06-14 04:51:15 +00006502
6503 // If the vector cast is cast between two vectors of the same size, it is
6504 // a bitcast, not a conversion.
6505 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6506 return;
John McCall51313c32010-01-04 23:31:57 +00006507
6508 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6509 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6510 }
Stephen Hines651f13c2014-04-23 16:59:28 -07006511 if (auto VecTy = dyn_cast<VectorType>(Target))
6512 Target = VecTy->getElementType().getTypePtr();
John McCall51313c32010-01-04 23:31:57 +00006513
6514 // Strip complex types.
6515 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00006516 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006517 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006518 return;
6519
John McCallb4eb64d2010-10-08 02:01:28 +00006520 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00006521 }
John McCall51313c32010-01-04 23:31:57 +00006522
6523 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6524 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6525 }
6526
6527 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6528 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6529
6530 // If the source is floating point...
6531 if (SourceBT && SourceBT->isFloatingPoint()) {
6532 // ...and the target is floating point...
6533 if (TargetBT && TargetBT->isFloatingPoint()) {
6534 // ...then warn if we're dropping FP rank.
6535
6536 // Builtin FP kinds are ordered by increasing FP rank.
6537 if (SourceBT->getKind() > TargetBT->getKind()) {
6538 // Don't warn about float constants that are precisely
6539 // representable in the target type.
6540 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00006541 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00006542 // Value might be a float, a float vector, or a float complex.
6543 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00006544 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6545 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00006546 return;
6547 }
6548
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006549 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006550 return;
6551
John McCallb4eb64d2010-10-08 02:01:28 +00006552 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00006553 }
6554 return;
6555 }
6556
Ted Kremenekef9ff882011-03-10 20:03:42 +00006557 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00006558 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006559 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006560 return;
6561
Chandler Carrutha5b93322011-02-17 11:05:49 +00006562 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00006563 // We also want to warn on, e.g., "int i = -1.234"
6564 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6565 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6566 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6567
Chandler Carruthf65076e2011-04-10 08:36:24 +00006568 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6569 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00006570 } else {
6571 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6572 }
6573 }
John McCall51313c32010-01-04 23:31:57 +00006574
Hans Wennborg88617a22012-08-28 15:44:30 +00006575 // If the target is bool, warn if expr is a function or method call.
6576 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6577 isa<CallExpr>(E)) {
6578 // Check last argument of function call to see if it is an
6579 // implicit cast from a type matching the type the result
6580 // is being cast to.
6581 CallExpr *CEx = cast<CallExpr>(E);
6582 unsigned NumArgs = CEx->getNumArgs();
6583 if (NumArgs > 0) {
6584 Expr *LastA = CEx->getArg(NumArgs - 1);
6585 Expr *InnerE = LastA->IgnoreParenImpCasts();
6586 const Type *InnerType =
6587 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6588 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6589 // Warn on this floating-point to bool conversion
6590 DiagnoseImpCast(S, E, T, CC,
6591 diag::warn_impcast_floating_point_to_bool);
6592 }
6593 }
6594 }
John McCall51313c32010-01-04 23:31:57 +00006595 return;
6596 }
6597
Stephen Hines176edba2014-12-01 14:53:08 -08006598 DiagnoseNullConversion(S, E, T, CC);
Richard Trieu1838ca52011-05-29 19:59:02 +00006599
David Blaikieb26331b2012-06-19 21:19:06 +00006600 if (!Source->isIntegerType() || !Target->isIntegerType())
6601 return;
6602
David Blaikiebe0ee872012-05-15 16:56:36 +00006603 // TODO: remove this early return once the false positives for constant->bool
6604 // in templates, macros, etc, are reduced or removed.
6605 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6606 return;
6607
John McCall323ed742010-05-06 08:58:33 +00006608 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00006609 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00006610
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006611 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00006612 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006613 // TODO: this should happen for bitfield stores, too.
6614 llvm::APSInt Value(32);
6615 if (E->isIntegerConstantExpr(Value, S.Context)) {
6616 if (S.SourceMgr.isInSystemMacro(CC))
6617 return;
6618
John McCall091f23f2010-11-09 22:22:12 +00006619 std::string PrettySourceValue = Value.toString(10);
6620 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006621
Ted Kremenek5e745da2011-10-22 02:37:33 +00006622 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6623 S.PDiag(diag::warn_impcast_integer_precision_constant)
6624 << PrettySourceValue << PrettyTargetValue
6625 << E->getType() << T << E->getSourceRange()
6626 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00006627 return;
6628 }
6629
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006630 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6631 if (S.SourceMgr.isInSystemMacro(CC))
6632 return;
6633
David Blaikie37050842012-04-12 22:40:54 +00006634 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00006635 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6636 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00006637 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00006638 }
6639
6640 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6641 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6642 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00006643
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006644 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006645 return;
6646
John McCall323ed742010-05-06 08:58:33 +00006647 unsigned DiagID = diag::warn_impcast_integer_sign;
6648
6649 // Traditionally, gcc has warned about this under -Wsign-compare.
6650 // We also want to warn about it in -Wconversion.
6651 // So if -Wconversion is off, use a completely identical diagnostic
6652 // in the sign-compare group.
6653 // The conditional-checking code will
6654 if (ICContext) {
6655 DiagID = diag::warn_impcast_integer_sign_conditional;
6656 *ICContext = true;
6657 }
6658
John McCallb4eb64d2010-10-08 02:01:28 +00006659 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00006660 }
6661
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006662 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006663 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6664 // type, to give us better diagnostics.
6665 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00006666 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006667 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6668 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6669 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6670 SourceType = S.Context.getTypeDeclType(Enum);
6671 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6672 }
6673 }
6674
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006675 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6676 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00006677 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6678 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00006679 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006680 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006681 return;
6682
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006683 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006684 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00006685 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006686
John McCall51313c32010-01-04 23:31:57 +00006687 return;
6688}
6689
David Blaikie9fb1ac52012-05-15 21:57:38 +00006690void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6691 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00006692
6693void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00006694 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00006695 E = E->IgnoreParenImpCasts();
6696
6697 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00006698 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00006699
John McCallb4eb64d2010-10-08 02:01:28 +00006700 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00006701 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00006702 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00006703 return;
6704}
6705
David Blaikie9fb1ac52012-05-15 21:57:38 +00006706void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6707 SourceLocation CC, QualType T) {
Stephen Hines176edba2014-12-01 14:53:08 -08006708 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCall323ed742010-05-06 08:58:33 +00006709
6710 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00006711 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6712 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00006713
6714 // If -Wconversion would have warned about either of the candidates
6715 // for a signedness conversion to the context type...
6716 if (!Suspicious) return;
6717
6718 // ...but it's currently ignored...
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006719 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00006720 return;
6721
John McCall323ed742010-05-06 08:58:33 +00006722 // ...then check whether it would have warned about either of the
6723 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00006724 if (E->getType() == T) return;
6725
6726 Suspicious = false;
6727 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6728 E->getType(), CC, &Suspicious);
6729 if (!Suspicious)
6730 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00006731 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00006732}
6733
Stephen Hines176edba2014-12-01 14:53:08 -08006734/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6735/// Input argument E is a logical expression.
6736static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6737 if (S.getLangOpts().Bool)
6738 return;
6739 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6740}
6741
John McCall323ed742010-05-06 08:58:33 +00006742/// AnalyzeImplicitConversions - Find and report any interesting
6743/// implicit conversions in the given expression. There are a couple
6744/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00006745void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00006746 QualType T = OrigE->getType();
6747 Expr *E = OrigE->IgnoreParenImpCasts();
6748
Douglas Gregorf8b6e152011-10-10 17:38:18 +00006749 if (E->isTypeDependent() || E->isValueDependent())
6750 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006751
John McCall323ed742010-05-06 08:58:33 +00006752 // For conditional operators, we analyze the arguments as if they
6753 // were being fed directly into the output.
6754 if (isa<ConditionalOperator>(E)) {
6755 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00006756 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00006757 return;
6758 }
6759
Hans Wennborg88617a22012-08-28 15:44:30 +00006760 // Check implicit argument conversions for function calls.
6761 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6762 CheckImplicitArgumentConversions(S, Call, CC);
6763
John McCall323ed742010-05-06 08:58:33 +00006764 // Go ahead and check any implicit conversions we might have skipped.
6765 // The non-canonical typecheck is just an optimization;
6766 // CheckImplicitConversion will filter out dead implicit conversions.
6767 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00006768 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00006769
6770 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00006771
6772 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00006773 if (POE->getResultExpr())
6774 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00006775 }
6776
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006777 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
6778 if (OVE->getSourceExpr())
6779 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6780 return;
6781 }
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00006782
John McCall323ed742010-05-06 08:58:33 +00006783 // Skip past explicit casts.
6784 if (isa<ExplicitCastExpr>(E)) {
6785 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00006786 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00006787 }
6788
John McCallbeb22aa2010-11-09 23:24:47 +00006789 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6790 // Do a somewhat different check with comparison operators.
6791 if (BO->isComparisonOp())
6792 return AnalyzeComparison(S, BO);
6793
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006794 // And with simple assignments.
6795 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00006796 return AnalyzeAssignment(S, BO);
6797 }
John McCall323ed742010-05-06 08:58:33 +00006798
6799 // These break the otherwise-useful invariant below. Fortunately,
6800 // we don't really need to recurse into them, because any internal
6801 // expressions should have been analyzed already when they were
6802 // built into statements.
6803 if (isa<StmtExpr>(E)) return;
6804
6805 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006806 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00006807
6808 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00006809 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006810 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Stephen Hines651f13c2014-04-23 16:59:28 -07006811 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006812 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00006813 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00006814 if (!ChildExpr)
6815 continue;
6816
Stephen Hines651f13c2014-04-23 16:59:28 -07006817 if (IsLogicalAndOperator &&
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006818 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Stephen Hines651f13c2014-04-23 16:59:28 -07006819 // Ignore checking string literals that are in logical and operators.
6820 // This is a common pattern for asserts.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006821 continue;
6822 AnalyzeImplicitConversions(S, ChildExpr, CC);
6823 }
Stephen Hines176edba2014-12-01 14:53:08 -08006824
6825 if (BO && BO->isLogicalOp()) {
6826 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6827 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006828 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Stephen Hines176edba2014-12-01 14:53:08 -08006829
6830 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6831 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006832 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Stephen Hines176edba2014-12-01 14:53:08 -08006833 }
6834
6835 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6836 if (U->getOpcode() == UO_LNot)
6837 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCall323ed742010-05-06 08:58:33 +00006838}
6839
6840} // end anonymous namespace
6841
Stephen Hines651f13c2014-04-23 16:59:28 -07006842enum {
6843 AddressOf,
6844 FunctionPointer,
6845 ArrayPointer
6846};
6847
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006848// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6849// Returns true when emitting a warning about taking the address of a reference.
6850static bool CheckForReference(Sema &SemaRef, const Expr *E,
6851 PartialDiagnostic PD) {
6852 E = E->IgnoreParenImpCasts();
6853
6854 const FunctionDecl *FD = nullptr;
6855
6856 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6857 if (!DRE->getDecl()->getType()->isReferenceType())
6858 return false;
6859 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6860 if (!M->getMemberDecl()->getType()->isReferenceType())
6861 return false;
6862 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006863 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006864 return false;
6865 FD = Call->getDirectCallee();
6866 } else {
6867 return false;
6868 }
6869
6870 SemaRef.Diag(E->getExprLoc(), PD);
6871
6872 // If possible, point to location of function.
6873 if (FD) {
6874 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6875 }
6876
6877 return true;
6878}
6879
Stephen Hines176edba2014-12-01 14:53:08 -08006880// Returns true if the SourceLocation is expanded from any macro body.
6881// Returns false if the SourceLocation is invalid, is from not in a macro
6882// expansion, or is from expanded from a top-level macro argument.
6883static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6884 if (Loc.isInvalid())
6885 return false;
6886
6887 while (Loc.isMacroID()) {
6888 if (SM.isMacroBodyExpansion(Loc))
6889 return true;
6890 Loc = SM.getImmediateMacroCallerLoc(Loc);
6891 }
6892
6893 return false;
6894}
6895
Stephen Hines651f13c2014-04-23 16:59:28 -07006896/// \brief Diagnose pointers that are always non-null.
6897/// \param E the expression containing the pointer
6898/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6899/// compared to a null pointer
6900/// \param IsEqual True when the comparison is equal to a null pointer
6901/// \param Range Extra SourceRange to highlight in the diagnostic
6902void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6903 Expr::NullPointerConstantKind NullKind,
6904 bool IsEqual, SourceRange Range) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006905 if (!E)
6906 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07006907
6908 // Don't warn inside macros.
Stephen Hines176edba2014-12-01 14:53:08 -08006909 if (E->getExprLoc().isMacroID()) {
6910 const SourceManager &SM = getSourceManager();
6911 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6912 IsInAnyMacroBody(SM, Range.getBegin()))
Stephen Hines651f13c2014-04-23 16:59:28 -07006913 return;
Stephen Hines176edba2014-12-01 14:53:08 -08006914 }
Stephen Hines651f13c2014-04-23 16:59:28 -07006915 E = E->IgnoreImpCasts();
6916
6917 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6918
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006919 if (isa<CXXThisExpr>(E)) {
6920 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6921 : diag::warn_this_bool_conversion;
6922 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6923 return;
6924 }
6925
Stephen Hines651f13c2014-04-23 16:59:28 -07006926 bool IsAddressOf = false;
6927
6928 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6929 if (UO->getOpcode() != UO_AddrOf)
6930 return;
6931 IsAddressOf = true;
6932 E = UO->getSubExpr();
6933 }
6934
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006935 if (IsAddressOf) {
6936 unsigned DiagID = IsCompare
6937 ? diag::warn_address_of_reference_null_compare
6938 : diag::warn_address_of_reference_bool_conversion;
6939 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6940 << IsEqual;
6941 if (CheckForReference(*this, E, PD)) {
6942 return;
6943 }
6944 }
6945
Stephen Hines651f13c2014-04-23 16:59:28 -07006946 // Expect to find a single Decl. Skip anything more complicated.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006947 ValueDecl *D = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07006948 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6949 D = R->getDecl();
6950 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6951 D = M->getMemberDecl();
6952 }
6953
6954 // Weak Decls can be null.
6955 if (!D || D->isWeak())
6956 return;
Stephen Hines176edba2014-12-01 14:53:08 -08006957
6958 // Check for parameter decl with nonnull attribute
6959 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6960 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6961 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6962 unsigned NumArgs = FD->getNumParams();
6963 llvm::SmallBitVector AttrNonNull(NumArgs);
6964 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6965 if (!NonNull->args_size()) {
6966 AttrNonNull.set(0, NumArgs);
6967 break;
6968 }
6969 for (unsigned Val : NonNull->args()) {
6970 if (Val >= NumArgs)
6971 continue;
6972 AttrNonNull.set(Val);
6973 }
6974 }
6975 if (!AttrNonNull.empty())
6976 for (unsigned i = 0; i < NumArgs; ++i)
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006977 if (FD->getParamDecl(i) == PV &&
6978 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Stephen Hines176edba2014-12-01 14:53:08 -08006979 std::string Str;
6980 llvm::raw_string_ostream S(Str);
6981 E->printPretty(S, nullptr, getPrintingPolicy());
6982 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
6983 : diag::warn_cast_nonnull_to_bool;
6984 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
6985 << Range << IsEqual;
6986 return;
6987 }
6988 }
6989 }
6990
Stephen Hines651f13c2014-04-23 16:59:28 -07006991 QualType T = D->getType();
6992 const bool IsArray = T->isArrayType();
6993 const bool IsFunction = T->isFunctionType();
6994
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006995 // Address of function is used to silence the function warning.
6996 if (IsAddressOf && IsFunction) {
6997 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07006998 }
6999
7000 // Found nothing.
7001 if (!IsAddressOf && !IsFunction && !IsArray)
7002 return;
7003
7004 // Pretty print the expression for the diagnostic.
7005 std::string Str;
7006 llvm::raw_string_ostream S(Str);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007007 E->printPretty(S, nullptr, getPrintingPolicy());
Stephen Hines651f13c2014-04-23 16:59:28 -07007008
7009 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7010 : diag::warn_impcast_pointer_to_bool;
7011 unsigned DiagType;
7012 if (IsAddressOf)
7013 DiagType = AddressOf;
7014 else if (IsFunction)
7015 DiagType = FunctionPointer;
7016 else if (IsArray)
7017 DiagType = ArrayPointer;
7018 else
7019 llvm_unreachable("Could not determine diagnostic.");
7020 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7021 << Range << IsEqual;
7022
7023 if (!IsFunction)
7024 return;
7025
7026 // Suggest '&' to silence the function warning.
7027 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7028 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7029
7030 // Check to see if '()' fixit should be emitted.
7031 QualType ReturnType;
7032 UnresolvedSet<4> NonTemplateOverloads;
7033 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7034 if (ReturnType.isNull())
7035 return;
7036
7037 if (IsCompare) {
7038 // There are two cases here. If there is null constant, the only suggest
7039 // for a pointer return type. If the null is 0, then suggest if the return
7040 // type is a pointer or an integer type.
7041 if (!ReturnType->isPointerType()) {
7042 if (NullKind == Expr::NPCK_ZeroExpression ||
7043 NullKind == Expr::NPCK_ZeroLiteral) {
7044 if (!ReturnType->isIntegerType())
7045 return;
7046 } else {
7047 return;
7048 }
7049 }
7050 } else { // !IsCompare
7051 // For function to bool, only suggest if the function pointer has bool
7052 // return type.
7053 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7054 return;
7055 }
7056 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007057 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Stephen Hines651f13c2014-04-23 16:59:28 -07007058}
7059
7060
John McCall323ed742010-05-06 08:58:33 +00007061/// Diagnoses "dangerous" implicit conversions within the given
7062/// expression (which is a full expression). Implements -Wconversion
7063/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00007064///
7065/// \param CC the "context" location of the implicit conversion, i.e.
7066/// the most location of the syntactic entity requiring the implicit
7067/// conversion
7068void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00007069 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00007070 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00007071 return;
7072
7073 // Don't diagnose for value- or type-dependent expressions.
7074 if (E->isTypeDependent() || E->isValueDependent())
7075 return;
7076
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007077 // Check for array bounds violations in cases where the check isn't triggered
7078 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7079 // ArraySubscriptExpr is on the RHS of a variable initialization.
7080 CheckArrayAccess(E);
7081
John McCallb4eb64d2010-10-08 02:01:28 +00007082 // This is not the right CC for (e.g.) a variable initialization.
7083 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00007084}
7085
Stephen Hines176edba2014-12-01 14:53:08 -08007086/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7087/// Input argument E is a logical expression.
7088void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7089 ::CheckBoolLikeConversion(*this, E, CC);
7090}
7091
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007092/// Diagnose when expression is an integer constant expression and its evaluation
7093/// results in integer overflow
7094void Sema::CheckForIntOverflow (Expr *E) {
Stephen Hines176edba2014-12-01 14:53:08 -08007095 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7096 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007097}
7098
Richard Smith6c3af3d2013-01-17 01:17:56 +00007099namespace {
7100/// \brief Visitor for expressions which looks for unsequenced operations on the
7101/// same object.
7102class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00007103 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7104
Richard Smith6c3af3d2013-01-17 01:17:56 +00007105 /// \brief A tree of sequenced regions within an expression. Two regions are
7106 /// unsequenced if one is an ancestor or a descendent of the other. When we
7107 /// finish processing an expression with sequencing, such as a comma
7108 /// expression, we fold its tree nodes into its parent, since they are
7109 /// unsequenced with respect to nodes we will visit later.
7110 class SequenceTree {
7111 struct Value {
7112 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7113 unsigned Parent : 31;
7114 bool Merged : 1;
7115 };
Robert Wilhelme7205c02013-08-10 12:33:24 +00007116 SmallVector<Value, 8> Values;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007117
7118 public:
7119 /// \brief A region within an expression which may be sequenced with respect
7120 /// to some other region.
7121 class Seq {
7122 explicit Seq(unsigned N) : Index(N) {}
7123 unsigned Index;
7124 friend class SequenceTree;
7125 public:
7126 Seq() : Index(0) {}
7127 };
7128
7129 SequenceTree() { Values.push_back(Value(0)); }
7130 Seq root() const { return Seq(0); }
7131
7132 /// \brief Create a new sequence of operations, which is an unsequenced
7133 /// subset of \p Parent. This sequence of operations is sequenced with
7134 /// respect to other children of \p Parent.
7135 Seq allocate(Seq Parent) {
7136 Values.push_back(Value(Parent.Index));
7137 return Seq(Values.size() - 1);
7138 }
7139
7140 /// \brief Merge a sequence of operations into its parent.
7141 void merge(Seq S) {
7142 Values[S.Index].Merged = true;
7143 }
7144
7145 /// \brief Determine whether two operations are unsequenced. This operation
7146 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7147 /// should have been merged into its parent as appropriate.
7148 bool isUnsequenced(Seq Cur, Seq Old) {
7149 unsigned C = representative(Cur.Index);
7150 unsigned Target = representative(Old.Index);
7151 while (C >= Target) {
7152 if (C == Target)
7153 return true;
7154 C = Values[C].Parent;
7155 }
7156 return false;
7157 }
7158
7159 private:
7160 /// \brief Pick a representative for a sequence.
7161 unsigned representative(unsigned K) {
7162 if (Values[K].Merged)
7163 // Perform path compression as we go.
7164 return Values[K].Parent = representative(Values[K].Parent);
7165 return K;
7166 }
7167 };
7168
7169 /// An object for which we can track unsequenced uses.
7170 typedef NamedDecl *Object;
7171
7172 /// Different flavors of object usage which we track. We only track the
7173 /// least-sequenced usage of each kind.
7174 enum UsageKind {
7175 /// A read of an object. Multiple unsequenced reads are OK.
7176 UK_Use,
7177 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00007178 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00007179 UK_ModAsValue,
7180 /// A modification of an object which is not sequenced before the value
7181 /// computation of the expression, such as n++.
7182 UK_ModAsSideEffect,
7183
7184 UK_Count = UK_ModAsSideEffect + 1
7185 };
7186
7187 struct Usage {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007188 Usage() : Use(nullptr), Seq() {}
Richard Smith6c3af3d2013-01-17 01:17:56 +00007189 Expr *Use;
7190 SequenceTree::Seq Seq;
7191 };
7192
7193 struct UsageInfo {
7194 UsageInfo() : Diagnosed(false) {}
7195 Usage Uses[UK_Count];
7196 /// Have we issued a diagnostic for this variable already?
7197 bool Diagnosed;
7198 };
7199 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7200
7201 Sema &SemaRef;
7202 /// Sequenced regions within the expression.
7203 SequenceTree Tree;
7204 /// Declaration modifications and references which we have seen.
7205 UsageInfoMap UsageMap;
7206 /// The region we are currently within.
7207 SequenceTree::Seq Region;
7208 /// Filled in with declarations which were modified as a side-effect
7209 /// (that is, post-increment operations).
Robert Wilhelme7205c02013-08-10 12:33:24 +00007210 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00007211 /// Expressions to check later. We defer checking these to reduce
7212 /// stack usage.
Robert Wilhelme7205c02013-08-10 12:33:24 +00007213 SmallVectorImpl<Expr *> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007214
7215 /// RAII object wrapping the visitation of a sequenced subexpression of an
7216 /// expression. At the end of this process, the side-effects of the evaluation
7217 /// become sequenced with respect to the value computation of the result, so
7218 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7219 /// UK_ModAsValue.
7220 struct SequencedSubexpression {
7221 SequencedSubexpression(SequenceChecker &Self)
7222 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7223 Self.ModAsSideEffect = &ModAsSideEffect;
7224 }
7225 ~SequencedSubexpression() {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007226 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7227 MI != ME; ++MI) {
7228 UsageInfo &U = Self.UsageMap[MI->first];
7229 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7230 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7231 SideEffectUsage = MI->second;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007232 }
7233 Self.ModAsSideEffect = OldModAsSideEffect;
7234 }
7235
7236 SequenceChecker &Self;
Robert Wilhelme7205c02013-08-10 12:33:24 +00007237 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7238 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007239 };
7240
Richard Smith67470052013-06-20 22:21:56 +00007241 /// RAII object wrapping the visitation of a subexpression which we might
7242 /// choose to evaluate as a constant. If any subexpression is evaluated and
7243 /// found to be non-constant, this allows us to suppress the evaluation of
7244 /// the outer expression.
7245 class EvaluationTracker {
7246 public:
7247 EvaluationTracker(SequenceChecker &Self)
7248 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7249 Self.EvalTracker = this;
7250 }
7251 ~EvaluationTracker() {
7252 Self.EvalTracker = Prev;
7253 if (Prev)
7254 Prev->EvalOK &= EvalOK;
7255 }
7256
7257 bool evaluate(const Expr *E, bool &Result) {
7258 if (!EvalOK || E->isValueDependent())
7259 return false;
7260 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7261 return EvalOK;
7262 }
7263
7264 private:
7265 SequenceChecker &Self;
7266 EvaluationTracker *Prev;
7267 bool EvalOK;
7268 } *EvalTracker;
7269
Richard Smith6c3af3d2013-01-17 01:17:56 +00007270 /// \brief Find the object which is produced by the specified expression,
7271 /// if any.
7272 Object getObject(Expr *E, bool Mod) const {
7273 E = E->IgnoreParenCasts();
7274 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7275 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7276 return getObject(UO->getSubExpr(), Mod);
7277 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7278 if (BO->getOpcode() == BO_Comma)
7279 return getObject(BO->getRHS(), Mod);
7280 if (Mod && BO->isAssignmentOp())
7281 return getObject(BO->getLHS(), Mod);
7282 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7283 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7284 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7285 return ME->getMemberDecl();
7286 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7287 // FIXME: If this is a reference, map through to its value.
7288 return DRE->getDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007289 return nullptr;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007290 }
7291
7292 /// \brief Note that an object was modified or used by an expression.
7293 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7294 Usage &U = UI.Uses[UK];
7295 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7296 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7297 ModAsSideEffect->push_back(std::make_pair(O, U));
7298 U.Use = Ref;
7299 U.Seq = Region;
7300 }
7301 }
7302 /// \brief Check whether a modification or use conflicts with a prior usage.
7303 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7304 bool IsModMod) {
7305 if (UI.Diagnosed)
7306 return;
7307
7308 const Usage &U = UI.Uses[OtherKind];
7309 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7310 return;
7311
7312 Expr *Mod = U.Use;
7313 Expr *ModOrUse = Ref;
7314 if (OtherKind == UK_Use)
7315 std::swap(Mod, ModOrUse);
7316
7317 SemaRef.Diag(Mod->getExprLoc(),
7318 IsModMod ? diag::warn_unsequenced_mod_mod
7319 : diag::warn_unsequenced_mod_use)
7320 << O << SourceRange(ModOrUse->getExprLoc());
7321 UI.Diagnosed = true;
7322 }
7323
7324 void notePreUse(Object O, Expr *Use) {
7325 UsageInfo &U = UsageMap[O];
7326 // Uses conflict with other modifications.
7327 checkUsage(O, U, Use, UK_ModAsValue, false);
7328 }
7329 void notePostUse(Object O, Expr *Use) {
7330 UsageInfo &U = UsageMap[O];
7331 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7332 addUsage(U, O, Use, UK_Use);
7333 }
7334
7335 void notePreMod(Object O, Expr *Mod) {
7336 UsageInfo &U = UsageMap[O];
7337 // Modifications conflict with other modifications and with uses.
7338 checkUsage(O, U, Mod, UK_ModAsValue, true);
7339 checkUsage(O, U, Mod, UK_Use, false);
7340 }
7341 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7342 UsageInfo &U = UsageMap[O];
7343 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7344 addUsage(U, O, Use, UK);
7345 }
7346
7347public:
Robert Wilhelme7205c02013-08-10 12:33:24 +00007348 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007349 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7350 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00007351 Visit(E);
7352 }
7353
7354 void VisitStmt(Stmt *S) {
7355 // Skip all statements which aren't expressions for now.
7356 }
7357
7358 void VisitExpr(Expr *E) {
7359 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00007360 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007361 }
7362
7363 void VisitCastExpr(CastExpr *E) {
7364 Object O = Object();
7365 if (E->getCastKind() == CK_LValueToRValue)
7366 O = getObject(E->getSubExpr(), false);
7367
7368 if (O)
7369 notePreUse(O, E);
7370 VisitExpr(E);
7371 if (O)
7372 notePostUse(O, E);
7373 }
7374
7375 void VisitBinComma(BinaryOperator *BO) {
7376 // C++11 [expr.comma]p1:
7377 // Every value computation and side effect associated with the left
7378 // expression is sequenced before every value computation and side
7379 // effect associated with the right expression.
7380 SequenceTree::Seq LHS = Tree.allocate(Region);
7381 SequenceTree::Seq RHS = Tree.allocate(Region);
7382 SequenceTree::Seq OldRegion = Region;
7383
7384 {
7385 SequencedSubexpression SeqLHS(*this);
7386 Region = LHS;
7387 Visit(BO->getLHS());
7388 }
7389
7390 Region = RHS;
7391 Visit(BO->getRHS());
7392
7393 Region = OldRegion;
7394
7395 // Forget that LHS and RHS are sequenced. They are both unsequenced
7396 // with respect to other stuff.
7397 Tree.merge(LHS);
7398 Tree.merge(RHS);
7399 }
7400
7401 void VisitBinAssign(BinaryOperator *BO) {
7402 // The modification is sequenced after the value computation of the LHS
7403 // and RHS, so check it before inspecting the operands and update the
7404 // map afterwards.
7405 Object O = getObject(BO->getLHS(), true);
7406 if (!O)
7407 return VisitExpr(BO);
7408
7409 notePreMod(O, BO);
7410
7411 // C++11 [expr.ass]p7:
7412 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7413 // only once.
7414 //
7415 // Therefore, for a compound assignment operator, O is considered used
7416 // everywhere except within the evaluation of E1 itself.
7417 if (isa<CompoundAssignOperator>(BO))
7418 notePreUse(O, BO);
7419
7420 Visit(BO->getLHS());
7421
7422 if (isa<CompoundAssignOperator>(BO))
7423 notePostUse(O, BO);
7424
7425 Visit(BO->getRHS());
7426
Richard Smith418dd3e2013-06-26 23:16:51 +00007427 // C++11 [expr.ass]p1:
7428 // the assignment is sequenced [...] before the value computation of the
7429 // assignment expression.
7430 // C11 6.5.16/3 has no such rule.
7431 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7432 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007433 }
7434 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7435 VisitBinAssign(CAO);
7436 }
7437
7438 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7439 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7440 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7441 Object O = getObject(UO->getSubExpr(), true);
7442 if (!O)
7443 return VisitExpr(UO);
7444
7445 notePreMod(O, UO);
7446 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00007447 // C++11 [expr.pre.incr]p1:
7448 // the expression ++x is equivalent to x+=1
7449 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7450 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007451 }
7452
7453 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7454 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7455 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7456 Object O = getObject(UO->getSubExpr(), true);
7457 if (!O)
7458 return VisitExpr(UO);
7459
7460 notePreMod(O, UO);
7461 Visit(UO->getSubExpr());
7462 notePostMod(O, UO, UK_ModAsSideEffect);
7463 }
7464
7465 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7466 void VisitBinLOr(BinaryOperator *BO) {
7467 // The side-effects of the LHS of an '&&' are sequenced before the
7468 // value computation of the RHS, and hence before the value computation
7469 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7470 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00007471 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007472 {
7473 SequencedSubexpression Sequenced(*this);
7474 Visit(BO->getLHS());
7475 }
7476
7477 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00007478 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00007479 if (!Result)
7480 Visit(BO->getRHS());
7481 } else {
7482 // Check for unsequenced operations in the RHS, treating it as an
7483 // entirely separate evaluation.
7484 //
7485 // FIXME: If there are operations in the RHS which are unsequenced
7486 // with respect to operations outside the RHS, and those operations
7487 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00007488 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00007489 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007490 }
7491 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00007492 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007493 {
7494 SequencedSubexpression Sequenced(*this);
7495 Visit(BO->getLHS());
7496 }
7497
7498 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00007499 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00007500 if (Result)
7501 Visit(BO->getRHS());
7502 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00007503 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00007504 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007505 }
7506
7507 // Only visit the condition, unless we can be sure which subexpression will
7508 // be chosen.
7509 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00007510 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00007511 {
7512 SequencedSubexpression Sequenced(*this);
7513 Visit(CO->getCond());
7514 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007515
7516 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00007517 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00007518 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00007519 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00007520 WorkList.push_back(CO->getTrueExpr());
7521 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00007522 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007523 }
7524
Richard Smith0c0b3902013-06-30 10:40:20 +00007525 void VisitCallExpr(CallExpr *CE) {
7526 // C++11 [intro.execution]p15:
7527 // When calling a function [...], every value computation and side effect
7528 // associated with any argument expression, or with the postfix expression
7529 // designating the called function, is sequenced before execution of every
7530 // expression or statement in the body of the function [and thus before
7531 // the value computation of its result].
7532 SequencedSubexpression Sequenced(*this);
7533 Base::VisitCallExpr(CE);
7534
7535 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7536 }
7537
Richard Smith6c3af3d2013-01-17 01:17:56 +00007538 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00007539 // This is a call, so all subexpressions are sequenced before the result.
7540 SequencedSubexpression Sequenced(*this);
7541
Richard Smith6c3af3d2013-01-17 01:17:56 +00007542 if (!CCE->isListInitialization())
7543 return VisitExpr(CCE);
7544
7545 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00007546 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007547 SequenceTree::Seq Parent = Region;
7548 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7549 E = CCE->arg_end();
7550 I != E; ++I) {
7551 Region = Tree.allocate(Parent);
7552 Elts.push_back(Region);
7553 Visit(*I);
7554 }
7555
7556 // Forget that the initializers are sequenced.
7557 Region = Parent;
7558 for (unsigned I = 0; I < Elts.size(); ++I)
7559 Tree.merge(Elts[I]);
7560 }
7561
7562 void VisitInitListExpr(InitListExpr *ILE) {
7563 if (!SemaRef.getLangOpts().CPlusPlus11)
7564 return VisitExpr(ILE);
7565
7566 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00007567 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007568 SequenceTree::Seq Parent = Region;
7569 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7570 Expr *E = ILE->getInit(I);
7571 if (!E) continue;
7572 Region = Tree.allocate(Parent);
7573 Elts.push_back(Region);
7574 Visit(E);
7575 }
7576
7577 // Forget that the initializers are sequenced.
7578 Region = Parent;
7579 for (unsigned I = 0; I < Elts.size(); ++I)
7580 Tree.merge(Elts[I]);
7581 }
7582};
7583}
7584
7585void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00007586 SmallVector<Expr *, 8> WorkList;
Richard Smith1a2dcd52013-01-17 23:18:09 +00007587 WorkList.push_back(E);
7588 while (!WorkList.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00007589 Expr *Item = WorkList.pop_back_val();
Richard Smith1a2dcd52013-01-17 23:18:09 +00007590 SequenceChecker(*this, Item, WorkList);
7591 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007592}
7593
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007594void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7595 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00007596 CheckImplicitConversions(E, CheckLoc);
7597 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007598 if (!IsConstexpr && !E->isValueDependent())
7599 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007600}
7601
John McCall15d7d122010-11-11 03:21:53 +00007602void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7603 FieldDecl *BitField,
7604 Expr *Init) {
7605 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7606}
7607
Mike Stumpf8c49212010-01-21 03:59:47 +00007608/// CheckParmsForFunctionDef - Check that the parameters of the given
7609/// function are appropriate for the definition of a function. This
7610/// takes care of any checks that cannot be performed on the
7611/// declaration itself, e.g., that the types of each of the function
7612/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00007613bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7614 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00007615 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00007616 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00007617 for (; P != PEnd; ++P) {
7618 ParmVarDecl *Param = *P;
7619
Mike Stumpf8c49212010-01-21 03:59:47 +00007620 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7621 // function declarator that is part of a function definition of
7622 // that function shall not have incomplete type.
7623 //
7624 // This is also C++ [dcl.fct]p6.
7625 if (!Param->isInvalidDecl() &&
7626 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007627 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00007628 Param->setInvalidDecl();
7629 HasInvalidParm = true;
7630 }
7631
7632 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7633 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00007634 if (CheckParameterNames &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007635 Param->getIdentifier() == nullptr &&
Mike Stumpf8c49212010-01-21 03:59:47 +00007636 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00007637 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00007638 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00007639
7640 // C99 6.7.5.3p12:
7641 // If the function declarator is not part of a definition of that
7642 // function, parameters may have incomplete type and may use the [*]
7643 // notation in their sequences of declarator specifiers to specify
7644 // variable length array types.
7645 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00007646 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00007647 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00007648 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00007649 // information is added for it.
7650 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00007651 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00007652 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00007653 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00007654 }
Reid Kleckner9b601952013-06-21 12:45:15 +00007655
7656 // MSVC destroys objects passed by value in the callee. Therefore a
7657 // function definition which takes such a parameter must be able to call the
Stephen Hines651f13c2014-04-23 16:59:28 -07007658 // object's destructor. However, we don't perform any direct access check
7659 // on the dtor.
7660 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7661 .getCXXABI()
7662 .areArgsDestroyedLeftToRightInCallee()) {
7663 if (!Param->isInvalidDecl()) {
7664 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7665 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7666 if (!ClassDecl->isInvalidDecl() &&
7667 !ClassDecl->hasIrrelevantDestructor() &&
7668 !ClassDecl->isDependentContext()) {
7669 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7670 MarkFunctionReferenced(Param->getLocation(), Destructor);
7671 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7672 }
7673 }
7674 }
Reid Kleckner9b601952013-06-21 12:45:15 +00007675 }
Mike Stumpf8c49212010-01-21 03:59:47 +00007676 }
7677
7678 return HasInvalidParm;
7679}
John McCallb7f4ffe2010-08-12 21:44:57 +00007680
7681/// CheckCastAlign - Implements -Wcast-align, which warns when a
7682/// pointer cast increases the alignment requirements.
7683void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7684 // This is actually a lot of work to potentially be doing on every
7685 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007686 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCallb7f4ffe2010-08-12 21:44:57 +00007687 return;
7688
7689 // Ignore dependent types.
7690 if (T->isDependentType() || Op->getType()->isDependentType())
7691 return;
7692
7693 // Require that the destination be a pointer type.
7694 const PointerType *DestPtr = T->getAs<PointerType>();
7695 if (!DestPtr) return;
7696
7697 // If the destination has alignment 1, we're done.
7698 QualType DestPointee = DestPtr->getPointeeType();
7699 if (DestPointee->isIncompleteType()) return;
7700 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7701 if (DestAlign.isOne()) return;
7702
7703 // Require that the source be a pointer type.
7704 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7705 if (!SrcPtr) return;
7706 QualType SrcPointee = SrcPtr->getPointeeType();
7707
7708 // Whitelist casts from cv void*. We already implicitly
7709 // whitelisted casts to cv void*, since they have alignment 1.
7710 // Also whitelist casts involving incomplete types, which implicitly
7711 // includes 'void'.
7712 if (SrcPointee->isIncompleteType()) return;
7713
7714 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7715 if (SrcAlign >= DestAlign) return;
7716
7717 Diag(TRange.getBegin(), diag::warn_cast_align)
7718 << Op->getType() << T
7719 << static_cast<unsigned>(SrcAlign.getQuantity())
7720 << static_cast<unsigned>(DestAlign.getQuantity())
7721 << TRange << Op->getSourceRange();
7722}
7723
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007724static const Type* getElementType(const Expr *BaseExpr) {
7725 const Type* EltType = BaseExpr->getType().getTypePtr();
7726 if (EltType->isAnyPointerType())
7727 return EltType->getPointeeType().getTypePtr();
7728 else if (EltType->isArrayType())
7729 return EltType->getBaseElementTypeUnsafe();
7730 return EltType;
7731}
7732
Chandler Carruthc2684342011-08-05 09:10:50 +00007733/// \brief Check whether this array fits the idiom of a size-one tail padded
7734/// array member of a struct.
7735///
7736/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7737/// commonly used to emulate flexible arrays in C89 code.
7738static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7739 const NamedDecl *ND) {
7740 if (Size != 1 || !ND) return false;
7741
7742 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7743 if (!FD) return false;
7744
7745 // Don't consider sizes resulting from macro expansions or template argument
7746 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00007747
7748 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00007749 while (TInfo) {
7750 TypeLoc TL = TInfo->getTypeLoc();
7751 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00007752 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7753 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00007754 TInfo = TDL->getTypeSourceInfo();
7755 continue;
7756 }
David Blaikie39e6ab42013-02-18 22:06:02 +00007757 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7758 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00007759 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7760 return false;
7761 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00007762 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00007763 }
Chandler Carruthc2684342011-08-05 09:10:50 +00007764
7765 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00007766 if (!RD) return false;
7767 if (RD->isUnion()) return false;
7768 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7769 if (!CRD->isStandardLayout()) return false;
7770 }
Chandler Carruthc2684342011-08-05 09:10:50 +00007771
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00007772 // See if this is the last field decl in the record.
7773 const Decl *D = FD;
7774 while ((D = D->getNextDeclInContext()))
7775 if (isa<FieldDecl>(D))
7776 return false;
7777 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00007778}
7779
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007780void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007781 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00007782 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00007783 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007784 if (IndexExpr->isValueDependent())
7785 return;
7786
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00007787 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007788 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00007789 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007790 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00007791 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00007792 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00007793
Chandler Carruth34064582011-02-17 20:55:08 +00007794 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007795 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00007796 return;
Richard Smith25b009a2011-12-16 19:31:14 +00007797 if (IndexNegated)
7798 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00007799
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007800 const NamedDecl *ND = nullptr;
Chandler Carruthba447122011-08-05 08:07:29 +00007801 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7802 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00007803 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00007804 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00007805
Ted Kremenek9e060ca2011-02-23 23:06:04 +00007806 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00007807 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00007808 if (!size.isStrictlyPositive())
7809 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007810
7811 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00007812 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007813 // Make sure we're comparing apples to apples when comparing index to size
7814 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7815 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00007816 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00007817 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007818 if (ptrarith_typesize != array_typesize) {
7819 // There's a cast to a different size type involved
7820 uint64_t ratio = array_typesize / ptrarith_typesize;
7821 // TODO: Be smarter about handling cases where array_typesize is not a
7822 // multiple of ptrarith_typesize
7823 if (ptrarith_typesize * ratio == array_typesize)
7824 size *= llvm::APInt(size.getBitWidth(), ratio);
7825 }
7826 }
7827
Chandler Carruth34064582011-02-17 20:55:08 +00007828 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00007829 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00007830 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00007831 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00007832
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007833 // For array subscripting the index must be less than size, but for pointer
7834 // arithmetic also allow the index (offset) to be equal to size since
7835 // computing the next address after the end of the array is legal and
7836 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00007837 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00007838 return;
7839
7840 // Also don't warn for arrays of size 1 which are members of some
7841 // structure. These are often used to approximate flexible arrays in C89
7842 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007843 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00007844 return;
Chandler Carruth34064582011-02-17 20:55:08 +00007845
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007846 // Suppress the warning if the subscript expression (as identified by the
7847 // ']' location) and the index expression are both from macro expansions
7848 // within a system header.
7849 if (ASE) {
7850 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7851 ASE->getRBracketLoc());
7852 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7853 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7854 IndexExpr->getLocStart());
Eli Friedman24146972013-08-22 00:27:10 +00007855 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007856 return;
7857 }
7858 }
7859
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007860 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007861 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007862 DiagID = diag::warn_array_index_exceeds_bounds;
7863
7864 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7865 PDiag(DiagID) << index.toString(10, true)
7866 << size.toString(10, true)
7867 << (unsigned)size.getLimitedValue(~0U)
7868 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00007869 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007870 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007871 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007872 DiagID = diag::warn_ptr_arith_precedes_bounds;
7873 if (index.isNegative()) index = -index;
7874 }
7875
7876 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7877 PDiag(DiagID) << index.toString(10, true)
7878 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00007879 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00007880
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00007881 if (!ND) {
7882 // Try harder to find a NamedDecl to point at in the note.
7883 while (const ArraySubscriptExpr *ASE =
7884 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7885 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7886 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7887 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7888 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7889 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7890 }
7891
Chandler Carruth35001ca2011-02-17 21:10:52 +00007892 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007893 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7894 PDiag(diag::note_array_index_out_of_bounds)
7895 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00007896}
7897
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007898void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007899 int AllowOnePastEnd = 0;
7900 while (expr) {
7901 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007902 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007903 case Stmt::ArraySubscriptExprClass: {
7904 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007905 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007906 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007907 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007908 }
7909 case Stmt::UnaryOperatorClass: {
7910 // Only unwrap the * and & unary operators
7911 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7912 expr = UO->getSubExpr();
7913 switch (UO->getOpcode()) {
7914 case UO_AddrOf:
7915 AllowOnePastEnd++;
7916 break;
7917 case UO_Deref:
7918 AllowOnePastEnd--;
7919 break;
7920 default:
7921 return;
7922 }
7923 break;
7924 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007925 case Stmt::ConditionalOperatorClass: {
7926 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7927 if (const Expr *lhs = cond->getLHS())
7928 CheckArrayAccess(lhs);
7929 if (const Expr *rhs = cond->getRHS())
7930 CheckArrayAccess(rhs);
7931 return;
7932 }
7933 default:
7934 return;
7935 }
Peter Collingbournef111d932011-04-15 00:35:48 +00007936 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007937}
John McCallf85e1932011-06-15 23:02:42 +00007938
7939//===--- CHECK: Objective-C retain cycles ----------------------------------//
7940
7941namespace {
7942 struct RetainCycleOwner {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007943 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCallf85e1932011-06-15 23:02:42 +00007944 VarDecl *Variable;
7945 SourceRange Range;
7946 SourceLocation Loc;
7947 bool Indirect;
7948
7949 void setLocsFrom(Expr *e) {
7950 Loc = e->getExprLoc();
7951 Range = e->getSourceRange();
7952 }
7953 };
7954}
7955
7956/// Consider whether capturing the given variable can possibly lead to
7957/// a retain cycle.
7958static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00007959 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00007960 // lifetime. In MRR, it's captured strongly if the variable is
7961 // __block and has an appropriate type.
7962 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7963 return false;
7964
7965 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00007966 if (ref)
7967 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00007968 return true;
7969}
7970
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007971static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00007972 while (true) {
7973 e = e->IgnoreParens();
7974 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7975 switch (cast->getCastKind()) {
7976 case CK_BitCast:
7977 case CK_LValueBitCast:
7978 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00007979 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00007980 e = cast->getSubExpr();
7981 continue;
7982
John McCallf85e1932011-06-15 23:02:42 +00007983 default:
7984 return false;
7985 }
7986 }
7987
7988 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7989 ObjCIvarDecl *ivar = ref->getDecl();
7990 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7991 return false;
7992
7993 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007994 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00007995 return false;
7996
7997 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7998 owner.Indirect = true;
7999 return true;
8000 }
8001
8002 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8003 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8004 if (!var) return false;
8005 return considerVariable(var, ref, owner);
8006 }
8007
John McCallf85e1932011-06-15 23:02:42 +00008008 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8009 if (member->isArrow()) return false;
8010
8011 // Don't count this as an indirect ownership.
8012 e = member->getBase();
8013 continue;
8014 }
8015
John McCall4b9c2d22011-11-06 09:01:30 +00008016 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8017 // Only pay attention to pseudo-objects on property references.
8018 ObjCPropertyRefExpr *pre
8019 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8020 ->IgnoreParens());
8021 if (!pre) return false;
8022 if (pre->isImplicitProperty()) return false;
8023 ObjCPropertyDecl *property = pre->getExplicitProperty();
8024 if (!property->isRetaining() &&
8025 !(property->getPropertyIvarDecl() &&
8026 property->getPropertyIvarDecl()->getType()
8027 .getObjCLifetime() == Qualifiers::OCL_Strong))
8028 return false;
8029
8030 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00008031 if (pre->isSuperReceiver()) {
8032 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8033 if (!owner.Variable)
8034 return false;
8035 owner.Loc = pre->getLocation();
8036 owner.Range = pre->getSourceRange();
8037 return true;
8038 }
John McCall4b9c2d22011-11-06 09:01:30 +00008039 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8040 ->getSourceExpr());
8041 continue;
8042 }
8043
John McCallf85e1932011-06-15 23:02:42 +00008044 // Array ivars?
8045
8046 return false;
8047 }
8048}
8049
8050namespace {
8051 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8052 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8053 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008054 Context(Context), Variable(variable), Capturer(nullptr),
8055 VarWillBeReased(false) {}
8056 ASTContext &Context;
John McCallf85e1932011-06-15 23:02:42 +00008057 VarDecl *Variable;
8058 Expr *Capturer;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008059 bool VarWillBeReased;
John McCallf85e1932011-06-15 23:02:42 +00008060
8061 void VisitDeclRefExpr(DeclRefExpr *ref) {
8062 if (ref->getDecl() == Variable && !Capturer)
8063 Capturer = ref;
8064 }
8065
John McCallf85e1932011-06-15 23:02:42 +00008066 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8067 if (Capturer) return;
8068 Visit(ref->getBase());
8069 if (Capturer && ref->isFreeIvar())
8070 Capturer = ref;
8071 }
8072
8073 void VisitBlockExpr(BlockExpr *block) {
8074 // Look inside nested blocks
8075 if (block->getBlockDecl()->capturesVariable(Variable))
8076 Visit(block->getBlockDecl()->getBody());
8077 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00008078
8079 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8080 if (Capturer) return;
8081 if (OVE->getSourceExpr())
8082 Visit(OVE->getSourceExpr());
8083 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008084 void VisitBinaryOperator(BinaryOperator *BinOp) {
8085 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8086 return;
8087 Expr *LHS = BinOp->getLHS();
8088 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8089 if (DRE->getDecl() != Variable)
8090 return;
8091 if (Expr *RHS = BinOp->getRHS()) {
8092 RHS = RHS->IgnoreParenCasts();
8093 llvm::APSInt Value;
8094 VarWillBeReased =
8095 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8096 }
8097 }
8098 }
John McCallf85e1932011-06-15 23:02:42 +00008099 };
8100}
8101
8102/// Check whether the given argument is a block which captures a
8103/// variable.
8104static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8105 assert(owner.Variable && owner.Loc.isValid());
8106
8107 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00008108
8109 // Look through [^{...} copy] and Block_copy(^{...}).
8110 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8111 Selector Cmd = ME->getSelector();
8112 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8113 e = ME->getInstanceReceiver();
8114 if (!e)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008115 return nullptr;
Jordan Rose1fac58a2012-09-17 17:54:30 +00008116 e = e->IgnoreParenCasts();
8117 }
8118 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8119 if (CE->getNumArgs() == 1) {
8120 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00008121 if (Fn) {
8122 const IdentifierInfo *FnI = Fn->getIdentifier();
8123 if (FnI && FnI->isStr("_Block_copy")) {
8124 e = CE->getArg(0)->IgnoreParenCasts();
8125 }
8126 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00008127 }
8128 }
8129
John McCallf85e1932011-06-15 23:02:42 +00008130 BlockExpr *block = dyn_cast<BlockExpr>(e);
8131 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008132 return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00008133
8134 FindCaptureVisitor visitor(S.Context, owner.Variable);
8135 visitor.Visit(block->getBlockDecl()->getBody());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008136 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCallf85e1932011-06-15 23:02:42 +00008137}
8138
8139static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8140 RetainCycleOwner &owner) {
8141 assert(capturer);
8142 assert(owner.Variable && owner.Loc.isValid());
8143
8144 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8145 << owner.Variable << capturer->getSourceRange();
8146 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8147 << owner.Indirect << owner.Range;
8148}
8149
8150/// Check for a keyword selector that starts with the word 'add' or
8151/// 'set'.
8152static bool isSetterLikeSelector(Selector sel) {
8153 if (sel.isUnarySelector()) return false;
8154
Chris Lattner5f9e2722011-07-23 10:55:15 +00008155 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00008156 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00008157 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00008158 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00008159 else if (str.startswith("add")) {
8160 // Specially whitelist 'addOperationWithBlock:'.
8161 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8162 return false;
8163 str = str.substr(3);
8164 }
John McCallf85e1932011-06-15 23:02:42 +00008165 else
8166 return false;
8167
8168 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00008169 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00008170}
8171
8172/// Check a message send to see if it's likely to cause a retain cycle.
8173void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8174 // Only check instance methods whose selector looks like a setter.
8175 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8176 return;
8177
8178 // Try to find a variable that the receiver is strongly owned by.
8179 RetainCycleOwner owner;
8180 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00008181 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00008182 return;
8183 } else {
8184 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8185 owner.Variable = getCurMethodDecl()->getSelfDecl();
8186 owner.Loc = msg->getSuperLoc();
8187 owner.Range = msg->getSuperLoc();
8188 }
8189
8190 // Check whether the receiver is captured by any of the arguments.
8191 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8192 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8193 return diagnoseRetainCycle(*this, capturer, owner);
8194}
8195
8196/// Check a property assign to see if it's likely to cause a retain cycle.
8197void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8198 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00008199 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00008200 return;
8201
8202 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8203 diagnoseRetainCycle(*this, capturer, owner);
8204}
8205
Jordan Rosee10f4d32012-09-15 02:48:31 +00008206void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8207 RetainCycleOwner Owner;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008208 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosee10f4d32012-09-15 02:48:31 +00008209 return;
8210
8211 // Because we don't have an expression for the variable, we have to set the
8212 // location explicitly here.
8213 Owner.Loc = Var->getLocation();
8214 Owner.Range = Var->getSourceRange();
8215
8216 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8217 diagnoseRetainCycle(*this, Capturer, Owner);
8218}
8219
Ted Kremenek9d084012012-12-21 08:04:28 +00008220static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8221 Expr *RHS, bool isProperty) {
8222 // Check if RHS is an Objective-C object literal, which also can get
8223 // immediately zapped in a weak reference. Note that we explicitly
8224 // allow ObjCStringLiterals, since those are designed to never really die.
8225 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00008226
Ted Kremenekd3292c82012-12-21 22:46:35 +00008227 // This enum needs to match with the 'select' in
8228 // warn_objc_arc_literal_assign (off-by-1).
8229 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8230 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8231 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00008232
8233 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00008234 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00008235 << (isProperty ? 0 : 1)
8236 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00008237
8238 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00008239}
8240
Ted Kremenekb29b30f2012-12-21 19:45:30 +00008241static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8242 Qualifiers::ObjCLifetime LT,
8243 Expr *RHS, bool isProperty) {
8244 // Strip off any implicit cast added to get to the one ARC-specific.
8245 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8246 if (cast->getCastKind() == CK_ARCConsumeObject) {
8247 S.Diag(Loc, diag::warn_arc_retained_assign)
8248 << (LT == Qualifiers::OCL_ExplicitNone)
8249 << (isProperty ? 0 : 1)
8250 << RHS->getSourceRange();
8251 return true;
8252 }
8253 RHS = cast->getSubExpr();
8254 }
8255
8256 if (LT == Qualifiers::OCL_Weak &&
8257 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8258 return true;
8259
8260 return false;
8261}
8262
Ted Kremenekb1ea5102012-12-21 08:04:20 +00008263bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8264 QualType LHS, Expr *RHS) {
8265 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8266
8267 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8268 return false;
8269
8270 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8271 return true;
8272
8273 return false;
8274}
8275
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008276void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8277 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008278 QualType LHSType;
8279 // PropertyRef on LHS type need be directly obtained from
Stephen Hines651f13c2014-04-23 16:59:28 -07008280 // its declaration as it has a PseudoType.
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008281 ObjCPropertyRefExpr *PRE
8282 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8283 if (PRE && !PRE->isImplicitProperty()) {
8284 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8285 if (PD)
8286 LHSType = PD->getType();
8287 }
8288
8289 if (LHSType.isNull())
8290 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00008291
8292 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8293
8294 if (LT == Qualifiers::OCL_Weak) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008295 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose7a270482012-09-28 22:21:35 +00008296 getCurFunction()->markSafeWeakUse(LHS);
8297 }
8298
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008299 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8300 return;
Jordan Rose7a270482012-09-28 22:21:35 +00008301
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008302 // FIXME. Check for other life times.
8303 if (LT != Qualifiers::OCL_None)
8304 return;
8305
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008306 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008307 if (PRE->isImplicitProperty())
8308 return;
8309 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8310 if (!PD)
8311 return;
8312
Bill Wendlingad017fa2012-12-20 19:22:21 +00008313 unsigned Attributes = PD->getPropertyAttributes();
8314 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008315 // when 'assign' attribute was not explicitly specified
8316 // by user, ignore it and rely on property type itself
8317 // for lifetime info.
8318 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8319 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8320 LHSType->isObjCRetainableType())
8321 return;
8322
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008323 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00008324 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008325 Diag(Loc, diag::warn_arc_retained_property_assign)
8326 << RHS->getSourceRange();
8327 return;
8328 }
8329 RHS = cast->getSubExpr();
8330 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008331 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00008332 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00008333 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8334 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00008335 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008336 }
8337}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008338
8339//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8340
8341namespace {
8342bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8343 SourceLocation StmtLoc,
8344 const NullStmt *Body) {
8345 // Do not warn if the body is a macro that expands to nothing, e.g:
8346 //
8347 // #define CALL(x)
8348 // if (condition)
8349 // CALL(0);
8350 //
8351 if (Body->hasLeadingEmptyMacro())
8352 return false;
8353
8354 // Get line numbers of statement and body.
8355 bool StmtLineInvalid;
8356 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8357 &StmtLineInvalid);
8358 if (StmtLineInvalid)
8359 return false;
8360
8361 bool BodyLineInvalid;
8362 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8363 &BodyLineInvalid);
8364 if (BodyLineInvalid)
8365 return false;
8366
8367 // Warn if null statement and body are on the same line.
8368 if (StmtLine != BodyLine)
8369 return false;
8370
8371 return true;
8372}
8373} // Unnamed namespace
8374
8375void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8376 const Stmt *Body,
8377 unsigned DiagID) {
8378 // Since this is a syntactic check, don't emit diagnostic for template
8379 // instantiations, this just adds noise.
8380 if (CurrentInstantiationScope)
8381 return;
8382
8383 // The body should be a null statement.
8384 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8385 if (!NBody)
8386 return;
8387
8388 // Do the usual checks.
8389 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8390 return;
8391
8392 Diag(NBody->getSemiLoc(), DiagID);
8393 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8394}
8395
8396void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8397 const Stmt *PossibleBody) {
8398 assert(!CurrentInstantiationScope); // Ensured by caller
8399
8400 SourceLocation StmtLoc;
8401 const Stmt *Body;
8402 unsigned DiagID;
8403 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8404 StmtLoc = FS->getRParenLoc();
8405 Body = FS->getBody();
8406 DiagID = diag::warn_empty_for_body;
8407 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8408 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8409 Body = WS->getBody();
8410 DiagID = diag::warn_empty_while_body;
8411 } else
8412 return; // Neither `for' nor `while'.
8413
8414 // The body should be a null statement.
8415 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8416 if (!NBody)
8417 return;
8418
8419 // Skip expensive checks if diagnostic is disabled.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008420 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008421 return;
8422
8423 // Do the usual checks.
8424 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8425 return;
8426
8427 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8428 // noise level low, emit diagnostics only if for/while is followed by a
8429 // CompoundStmt, e.g.:
8430 // for (int i = 0; i < n; i++);
8431 // {
8432 // a(i);
8433 // }
8434 // or if for/while is followed by a statement with more indentation
8435 // than for/while itself:
8436 // for (int i = 0; i < n; i++);
8437 // a(i);
8438 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8439 if (!ProbableTypo) {
8440 bool BodyColInvalid;
8441 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8442 PossibleBody->getLocStart(),
8443 &BodyColInvalid);
8444 if (BodyColInvalid)
8445 return;
8446
8447 bool StmtColInvalid;
8448 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8449 S->getLocStart(),
8450 &StmtColInvalid);
8451 if (StmtColInvalid)
8452 return;
8453
8454 if (BodyCol > StmtCol)
8455 ProbableTypo = true;
8456 }
8457
8458 if (ProbableTypo) {
8459 Diag(NBody->getSemiLoc(), DiagID);
8460 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8461 }
8462}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008463
Stephen Hines0e2c34f2015-03-23 12:09:02 -07008464//===--- CHECK: Warn on self move with std::move. -------------------------===//
8465
8466/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8467void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8468 SourceLocation OpLoc) {
8469
8470 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8471 return;
8472
8473 if (!ActiveTemplateInstantiations.empty())
8474 return;
8475
8476 // Strip parens and casts away.
8477 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8478 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8479
8480 // Check for a call expression
8481 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8482 if (!CE || CE->getNumArgs() != 1)
8483 return;
8484
8485 // Check for a call to std::move
8486 const FunctionDecl *FD = CE->getDirectCallee();
8487 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8488 !FD->getIdentifier()->isStr("move"))
8489 return;
8490
8491 // Get argument from std::move
8492 RHSExpr = CE->getArg(0);
8493
8494 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8495 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8496
8497 // Two DeclRefExpr's, check that the decls are the same.
8498 if (LHSDeclRef && RHSDeclRef) {
8499 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8500 return;
8501 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8502 RHSDeclRef->getDecl()->getCanonicalDecl())
8503 return;
8504
8505 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8506 << LHSExpr->getSourceRange()
8507 << RHSExpr->getSourceRange();
8508 return;
8509 }
8510
8511 // Member variables require a different approach to check for self moves.
8512 // MemberExpr's are the same if every nested MemberExpr refers to the same
8513 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8514 // the base Expr's are CXXThisExpr's.
8515 const Expr *LHSBase = LHSExpr;
8516 const Expr *RHSBase = RHSExpr;
8517 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8518 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8519 if (!LHSME || !RHSME)
8520 return;
8521
8522 while (LHSME && RHSME) {
8523 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8524 RHSME->getMemberDecl()->getCanonicalDecl())
8525 return;
8526
8527 LHSBase = LHSME->getBase();
8528 RHSBase = RHSME->getBase();
8529 LHSME = dyn_cast<MemberExpr>(LHSBase);
8530 RHSME = dyn_cast<MemberExpr>(RHSBase);
8531 }
8532
8533 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8534 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8535 if (LHSDeclRef && RHSDeclRef) {
8536 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8537 return;
8538 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8539 RHSDeclRef->getDecl()->getCanonicalDecl())
8540 return;
8541
8542 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8543 << LHSExpr->getSourceRange()
8544 << RHSExpr->getSourceRange();
8545 return;
8546 }
8547
8548 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8549 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8550 << LHSExpr->getSourceRange()
8551 << RHSExpr->getSourceRange();
8552}
8553
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008554//===--- Layout compatibility ----------------------------------------------//
8555
8556namespace {
8557
8558bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8559
8560/// \brief Check if two enumeration types are layout-compatible.
8561bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8562 // C++11 [dcl.enum] p8:
8563 // Two enumeration types are layout-compatible if they have the same
8564 // underlying type.
8565 return ED1->isComplete() && ED2->isComplete() &&
8566 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8567}
8568
8569/// \brief Check if two fields are layout-compatible.
8570bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8571 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8572 return false;
8573
8574 if (Field1->isBitField() != Field2->isBitField())
8575 return false;
8576
8577 if (Field1->isBitField()) {
8578 // Make sure that the bit-fields are the same length.
8579 unsigned Bits1 = Field1->getBitWidthValue(C);
8580 unsigned Bits2 = Field2->getBitWidthValue(C);
8581
8582 if (Bits1 != Bits2)
8583 return false;
8584 }
8585
8586 return true;
8587}
8588
8589/// \brief Check if two standard-layout structs are layout-compatible.
8590/// (C++11 [class.mem] p17)
8591bool isLayoutCompatibleStruct(ASTContext &C,
8592 RecordDecl *RD1,
8593 RecordDecl *RD2) {
8594 // If both records are C++ classes, check that base classes match.
8595 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8596 // If one of records is a CXXRecordDecl we are in C++ mode,
8597 // thus the other one is a CXXRecordDecl, too.
8598 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8599 // Check number of base classes.
8600 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8601 return false;
8602
8603 // Check the base classes.
8604 for (CXXRecordDecl::base_class_const_iterator
8605 Base1 = D1CXX->bases_begin(),
8606 BaseEnd1 = D1CXX->bases_end(),
8607 Base2 = D2CXX->bases_begin();
8608 Base1 != BaseEnd1;
8609 ++Base1, ++Base2) {
8610 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8611 return false;
8612 }
8613 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8614 // If only RD2 is a C++ class, it should have zero base classes.
8615 if (D2CXX->getNumBases() > 0)
8616 return false;
8617 }
8618
8619 // Check the fields.
8620 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8621 Field2End = RD2->field_end(),
8622 Field1 = RD1->field_begin(),
8623 Field1End = RD1->field_end();
8624 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8625 if (!isLayoutCompatible(C, *Field1, *Field2))
8626 return false;
8627 }
8628 if (Field1 != Field1End || Field2 != Field2End)
8629 return false;
8630
8631 return true;
8632}
8633
8634/// \brief Check if two standard-layout unions are layout-compatible.
8635/// (C++11 [class.mem] p18)
8636bool isLayoutCompatibleUnion(ASTContext &C,
8637 RecordDecl *RD1,
8638 RecordDecl *RD2) {
8639 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Stephen Hines651f13c2014-04-23 16:59:28 -07008640 for (auto *Field2 : RD2->fields())
8641 UnmatchedFields.insert(Field2);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008642
Stephen Hines651f13c2014-04-23 16:59:28 -07008643 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008644 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8645 I = UnmatchedFields.begin(),
8646 E = UnmatchedFields.end();
8647
8648 for ( ; I != E; ++I) {
Stephen Hines651f13c2014-04-23 16:59:28 -07008649 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008650 bool Result = UnmatchedFields.erase(*I);
8651 (void) Result;
8652 assert(Result);
8653 break;
8654 }
8655 }
8656 if (I == E)
8657 return false;
8658 }
8659
8660 return UnmatchedFields.empty();
8661}
8662
8663bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8664 if (RD1->isUnion() != RD2->isUnion())
8665 return false;
8666
8667 if (RD1->isUnion())
8668 return isLayoutCompatibleUnion(C, RD1, RD2);
8669 else
8670 return isLayoutCompatibleStruct(C, RD1, RD2);
8671}
8672
8673/// \brief Check if two types are layout-compatible in C++11 sense.
8674bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8675 if (T1.isNull() || T2.isNull())
8676 return false;
8677
8678 // C++11 [basic.types] p11:
8679 // If two types T1 and T2 are the same type, then T1 and T2 are
8680 // layout-compatible types.
8681 if (C.hasSameType(T1, T2))
8682 return true;
8683
8684 T1 = T1.getCanonicalType().getUnqualifiedType();
8685 T2 = T2.getCanonicalType().getUnqualifiedType();
8686
8687 const Type::TypeClass TC1 = T1->getTypeClass();
8688 const Type::TypeClass TC2 = T2->getTypeClass();
8689
8690 if (TC1 != TC2)
8691 return false;
8692
8693 if (TC1 == Type::Enum) {
8694 return isLayoutCompatible(C,
8695 cast<EnumType>(T1)->getDecl(),
8696 cast<EnumType>(T2)->getDecl());
8697 } else if (TC1 == Type::Record) {
8698 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8699 return false;
8700
8701 return isLayoutCompatible(C,
8702 cast<RecordType>(T1)->getDecl(),
8703 cast<RecordType>(T2)->getDecl());
8704 }
8705
8706 return false;
8707}
8708}
8709
8710//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8711
8712namespace {
8713/// \brief Given a type tag expression find the type tag itself.
8714///
8715/// \param TypeExpr Type tag expression, as it appears in user's code.
8716///
8717/// \param VD Declaration of an identifier that appears in a type tag.
8718///
8719/// \param MagicValue Type tag magic value.
8720bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8721 const ValueDecl **VD, uint64_t *MagicValue) {
8722 while(true) {
8723 if (!TypeExpr)
8724 return false;
8725
8726 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8727
8728 switch (TypeExpr->getStmtClass()) {
8729 case Stmt::UnaryOperatorClass: {
8730 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8731 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8732 TypeExpr = UO->getSubExpr();
8733 continue;
8734 }
8735 return false;
8736 }
8737
8738 case Stmt::DeclRefExprClass: {
8739 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8740 *VD = DRE->getDecl();
8741 return true;
8742 }
8743
8744 case Stmt::IntegerLiteralClass: {
8745 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8746 llvm::APInt MagicValueAPInt = IL->getValue();
8747 if (MagicValueAPInt.getActiveBits() <= 64) {
8748 *MagicValue = MagicValueAPInt.getZExtValue();
8749 return true;
8750 } else
8751 return false;
8752 }
8753
8754 case Stmt::BinaryConditionalOperatorClass:
8755 case Stmt::ConditionalOperatorClass: {
8756 const AbstractConditionalOperator *ACO =
8757 cast<AbstractConditionalOperator>(TypeExpr);
8758 bool Result;
8759 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8760 if (Result)
8761 TypeExpr = ACO->getTrueExpr();
8762 else
8763 TypeExpr = ACO->getFalseExpr();
8764 continue;
8765 }
8766 return false;
8767 }
8768
8769 case Stmt::BinaryOperatorClass: {
8770 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8771 if (BO->getOpcode() == BO_Comma) {
8772 TypeExpr = BO->getRHS();
8773 continue;
8774 }
8775 return false;
8776 }
8777
8778 default:
8779 return false;
8780 }
8781 }
8782}
8783
8784/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8785///
8786/// \param TypeExpr Expression that specifies a type tag.
8787///
8788/// \param MagicValues Registered magic values.
8789///
8790/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8791/// kind.
8792///
8793/// \param TypeInfo Information about the corresponding C type.
8794///
8795/// \returns true if the corresponding C type was found.
8796bool GetMatchingCType(
8797 const IdentifierInfo *ArgumentKind,
8798 const Expr *TypeExpr, const ASTContext &Ctx,
8799 const llvm::DenseMap<Sema::TypeTagMagicValue,
8800 Sema::TypeTagData> *MagicValues,
8801 bool &FoundWrongKind,
8802 Sema::TypeTagData &TypeInfo) {
8803 FoundWrongKind = false;
8804
8805 // Variable declaration that has type_tag_for_datatype attribute.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008806 const ValueDecl *VD = nullptr;
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008807
8808 uint64_t MagicValue;
8809
8810 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8811 return false;
8812
8813 if (VD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07008814 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008815 if (I->getArgumentKind() != ArgumentKind) {
8816 FoundWrongKind = true;
8817 return false;
8818 }
8819 TypeInfo.Type = I->getMatchingCType();
8820 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8821 TypeInfo.MustBeNull = I->getMustBeNull();
8822 return true;
8823 }
8824 return false;
8825 }
8826
8827 if (!MagicValues)
8828 return false;
8829
8830 llvm::DenseMap<Sema::TypeTagMagicValue,
8831 Sema::TypeTagData>::const_iterator I =
8832 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8833 if (I == MagicValues->end())
8834 return false;
8835
8836 TypeInfo = I->second;
8837 return true;
8838}
8839} // unnamed namespace
8840
8841void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8842 uint64_t MagicValue, QualType Type,
8843 bool LayoutCompatible,
8844 bool MustBeNull) {
8845 if (!TypeTagForDatatypeMagicValues)
8846 TypeTagForDatatypeMagicValues.reset(
8847 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8848
8849 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8850 (*TypeTagForDatatypeMagicValues)[Magic] =
8851 TypeTagData(Type, LayoutCompatible, MustBeNull);
8852}
8853
8854namespace {
8855bool IsSameCharType(QualType T1, QualType T2) {
8856 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8857 if (!BT1)
8858 return false;
8859
8860 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8861 if (!BT2)
8862 return false;
8863
8864 BuiltinType::Kind T1Kind = BT1->getKind();
8865 BuiltinType::Kind T2Kind = BT2->getKind();
8866
8867 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8868 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8869 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8870 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8871}
8872} // unnamed namespace
8873
8874void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8875 const Expr * const *ExprArgs) {
8876 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8877 bool IsPointerAttr = Attr->getIsPointer();
8878
8879 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8880 bool FoundWrongKind;
8881 TypeTagData TypeInfo;
8882 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8883 TypeTagForDatatypeMagicValues.get(),
8884 FoundWrongKind, TypeInfo)) {
8885 if (FoundWrongKind)
8886 Diag(TypeTagExpr->getExprLoc(),
8887 diag::warn_type_tag_for_datatype_wrong_kind)
8888 << TypeTagExpr->getSourceRange();
8889 return;
8890 }
8891
8892 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8893 if (IsPointerAttr) {
8894 // Skip implicit cast of pointer to `void *' (as a function argument).
8895 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00008896 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00008897 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008898 ArgumentExpr = ICE->getSubExpr();
8899 }
8900 QualType ArgumentType = ArgumentExpr->getType();
8901
8902 // Passing a `void*' pointer shouldn't trigger a warning.
8903 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8904 return;
8905
8906 if (TypeInfo.MustBeNull) {
8907 // Type tag with matching void type requires a null pointer.
8908 if (!ArgumentExpr->isNullPointerConstant(Context,
8909 Expr::NPC_ValueDependentIsNotNull)) {
8910 Diag(ArgumentExpr->getExprLoc(),
8911 diag::warn_type_safety_null_pointer_required)
8912 << ArgumentKind->getName()
8913 << ArgumentExpr->getSourceRange()
8914 << TypeTagExpr->getSourceRange();
8915 }
8916 return;
8917 }
8918
8919 QualType RequiredType = TypeInfo.Type;
8920 if (IsPointerAttr)
8921 RequiredType = Context.getPointerType(RequiredType);
8922
8923 bool mismatch = false;
8924 if (!TypeInfo.LayoutCompatible) {
8925 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8926
8927 // C++11 [basic.fundamental] p1:
8928 // Plain char, signed char, and unsigned char are three distinct types.
8929 //
8930 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8931 // char' depending on the current char signedness mode.
8932 if (mismatch)
8933 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8934 RequiredType->getPointeeType())) ||
8935 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8936 mismatch = false;
8937 } else
8938 if (IsPointerAttr)
8939 mismatch = !isLayoutCompatible(Context,
8940 ArgumentType->getPointeeType(),
8941 RequiredType->getPointeeType());
8942 else
8943 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8944
8945 if (mismatch)
8946 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Stephen Hines651f13c2014-04-23 16:59:28 -07008947 << ArgumentType << ArgumentKind
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008948 << TypeInfo.LayoutCompatible << RequiredType
8949 << ArgumentExpr->getSourceRange()
8950 << TypeTagExpr->getSourceRange();
8951}
Stephen Hines651f13c2014-04-23 16:59:28 -07008952