blob: 550474107c0acd40fe07138b3c992da270c6774b [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000035#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000040#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043
Chris Lattnera26fb342009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000048}
49
John McCallbebede42011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerouge4a5b4442012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith6cbd65d2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000104 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000109 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000110 TheCall->setType(ResultType);
111 return false;
112}
113
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000114static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115 CallExpr *TheCall, unsigned SizeIdx,
116 unsigned DstSizeIdx) {
117 if (TheCall->getNumArgs() <= SizeIdx ||
118 TheCall->getNumArgs() <= DstSizeIdx)
119 return;
120
121 const Expr *SizeArg = TheCall->getArg(SizeIdx);
122 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
123
124 llvm::APSInt Size, DstSize;
125
126 // find out if both sizes are known at compile time
127 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
129 return;
130
131 if (Size.ule(DstSize))
132 return;
133
134 // confirmed overflow so generate the diagnostic.
135 IdentifierInfo *FnName = FDecl->getIdentifier();
136 SourceLocation SL = TheCall->getLocStart();
137 SourceRange SR = TheCall->getSourceRange();
138
139 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
140}
141
Peter Collingbournef7706832014-12-12 23:41:25 +0000142static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
143 if (checkArgCount(S, BuiltinCall, 2))
144 return true;
145
146 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
147 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
148 Expr *Call = BuiltinCall->getArg(0);
149 Expr *Chain = BuiltinCall->getArg(1);
150
151 if (Call->getStmtClass() != Stmt::CallExprClass) {
152 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
153 << Call->getSourceRange();
154 return true;
155 }
156
157 auto CE = cast<CallExpr>(Call);
158 if (CE->getCallee()->getType()->isBlockPointerType()) {
159 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
160 << Call->getSourceRange();
161 return true;
162 }
163
164 const Decl *TargetDecl = CE->getCalleeDecl();
165 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
166 if (FD->getBuiltinID()) {
167 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
168 << Call->getSourceRange();
169 return true;
170 }
171
172 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
173 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
174 << Call->getSourceRange();
175 return true;
176 }
177
178 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
179 if (ChainResult.isInvalid())
180 return true;
181 if (!ChainResult.get()->getType()->isPointerType()) {
182 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
183 << Chain->getSourceRange();
184 return true;
185 }
186
187 QualType ReturnTy = CE->getCallReturnType();
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
John McCalldadc5752010-08-24 06:29:42 +0000205ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000206Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
207 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000208 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000209
Chris Lattner3be167f2010-10-01 23:23:24 +0000210 // Find out if any arguments are required to be integer constant expressions.
211 unsigned ICEArguments = 0;
212 ASTContext::GetBuiltinTypeError Error;
213 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
214 if (Error != ASTContext::GE_None)
215 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
216
217 // If any arguments are required to be ICE's, check and diagnose.
218 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
219 // Skip arguments not required to be ICE's.
220 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
221
222 llvm::APSInt Result;
223 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
224 return true;
225 ICEArguments &= ~(1 << ArgNo);
226 }
227
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000228 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000229 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000230 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000231 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000232 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000233 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000234 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000235 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000236 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000237 if (SemaBuiltinVAStart(TheCall))
238 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000239 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000240 case Builtin::BI__va_start: {
241 switch (Context.getTargetInfo().getTriple().getArch()) {
242 case llvm::Triple::arm:
243 case llvm::Triple::thumb:
244 if (SemaBuiltinVAStartARM(TheCall))
245 return ExprError();
246 break;
247 default:
248 if (SemaBuiltinVAStart(TheCall))
249 return ExprError();
250 break;
251 }
252 break;
253 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000254 case Builtin::BI__builtin_isgreater:
255 case Builtin::BI__builtin_isgreaterequal:
256 case Builtin::BI__builtin_isless:
257 case Builtin::BI__builtin_islessequal:
258 case Builtin::BI__builtin_islessgreater:
259 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000260 if (SemaBuiltinUnorderedCompare(TheCall))
261 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000262 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000263 case Builtin::BI__builtin_fpclassify:
264 if (SemaBuiltinFPClassification(TheCall, 6))
265 return ExprError();
266 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000267 case Builtin::BI__builtin_isfinite:
268 case Builtin::BI__builtin_isinf:
269 case Builtin::BI__builtin_isinf_sign:
270 case Builtin::BI__builtin_isnan:
271 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000272 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000273 return ExprError();
274 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000275 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000276 return SemaBuiltinShuffleVector(TheCall);
277 // TheCall will be freed by the smart pointer here, but that's fine, since
278 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000279 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000280 if (SemaBuiltinPrefetch(TheCall))
281 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000282 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000283 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000284 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000285 if (SemaBuiltinAssume(TheCall))
286 return ExprError();
287 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000288 case Builtin::BI__builtin_assume_aligned:
289 if (SemaBuiltinAssumeAligned(TheCall))
290 return ExprError();
291 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000292 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000293 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000294 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000295 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000296 case Builtin::BI__builtin_longjmp:
297 if (SemaBuiltinLongjmp(TheCall))
298 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000299 break;
John McCallbebede42011-02-26 05:39:39 +0000300
301 case Builtin::BI__builtin_classify_type:
302 if (checkArgCount(*this, TheCall, 1)) return true;
303 TheCall->setType(Context.IntTy);
304 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000305 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000306 if (checkArgCount(*this, TheCall, 1)) return true;
307 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000308 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000309 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000310 case Builtin::BI__sync_fetch_and_add_1:
311 case Builtin::BI__sync_fetch_and_add_2:
312 case Builtin::BI__sync_fetch_and_add_4:
313 case Builtin::BI__sync_fetch_and_add_8:
314 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000315 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000316 case Builtin::BI__sync_fetch_and_sub_1:
317 case Builtin::BI__sync_fetch_and_sub_2:
318 case Builtin::BI__sync_fetch_and_sub_4:
319 case Builtin::BI__sync_fetch_and_sub_8:
320 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000321 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000322 case Builtin::BI__sync_fetch_and_or_1:
323 case Builtin::BI__sync_fetch_and_or_2:
324 case Builtin::BI__sync_fetch_and_or_4:
325 case Builtin::BI__sync_fetch_and_or_8:
326 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000327 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000328 case Builtin::BI__sync_fetch_and_and_1:
329 case Builtin::BI__sync_fetch_and_and_2:
330 case Builtin::BI__sync_fetch_and_and_4:
331 case Builtin::BI__sync_fetch_and_and_8:
332 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000333 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000334 case Builtin::BI__sync_fetch_and_xor_1:
335 case Builtin::BI__sync_fetch_and_xor_2:
336 case Builtin::BI__sync_fetch_and_xor_4:
337 case Builtin::BI__sync_fetch_and_xor_8:
338 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000339 case Builtin::BI__sync_fetch_and_nand:
340 case Builtin::BI__sync_fetch_and_nand_1:
341 case Builtin::BI__sync_fetch_and_nand_2:
342 case Builtin::BI__sync_fetch_and_nand_4:
343 case Builtin::BI__sync_fetch_and_nand_8:
344 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000345 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000346 case Builtin::BI__sync_add_and_fetch_1:
347 case Builtin::BI__sync_add_and_fetch_2:
348 case Builtin::BI__sync_add_and_fetch_4:
349 case Builtin::BI__sync_add_and_fetch_8:
350 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000351 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000352 case Builtin::BI__sync_sub_and_fetch_1:
353 case Builtin::BI__sync_sub_and_fetch_2:
354 case Builtin::BI__sync_sub_and_fetch_4:
355 case Builtin::BI__sync_sub_and_fetch_8:
356 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000357 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000358 case Builtin::BI__sync_and_and_fetch_1:
359 case Builtin::BI__sync_and_and_fetch_2:
360 case Builtin::BI__sync_and_and_fetch_4:
361 case Builtin::BI__sync_and_and_fetch_8:
362 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000363 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000364 case Builtin::BI__sync_or_and_fetch_1:
365 case Builtin::BI__sync_or_and_fetch_2:
366 case Builtin::BI__sync_or_and_fetch_4:
367 case Builtin::BI__sync_or_and_fetch_8:
368 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000369 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000370 case Builtin::BI__sync_xor_and_fetch_1:
371 case Builtin::BI__sync_xor_and_fetch_2:
372 case Builtin::BI__sync_xor_and_fetch_4:
373 case Builtin::BI__sync_xor_and_fetch_8:
374 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000375 case Builtin::BI__sync_nand_and_fetch:
376 case Builtin::BI__sync_nand_and_fetch_1:
377 case Builtin::BI__sync_nand_and_fetch_2:
378 case Builtin::BI__sync_nand_and_fetch_4:
379 case Builtin::BI__sync_nand_and_fetch_8:
380 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000381 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000382 case Builtin::BI__sync_val_compare_and_swap_1:
383 case Builtin::BI__sync_val_compare_and_swap_2:
384 case Builtin::BI__sync_val_compare_and_swap_4:
385 case Builtin::BI__sync_val_compare_and_swap_8:
386 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000387 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000388 case Builtin::BI__sync_bool_compare_and_swap_1:
389 case Builtin::BI__sync_bool_compare_and_swap_2:
390 case Builtin::BI__sync_bool_compare_and_swap_4:
391 case Builtin::BI__sync_bool_compare_and_swap_8:
392 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000393 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000394 case Builtin::BI__sync_lock_test_and_set_1:
395 case Builtin::BI__sync_lock_test_and_set_2:
396 case Builtin::BI__sync_lock_test_and_set_4:
397 case Builtin::BI__sync_lock_test_and_set_8:
398 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000399 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000400 case Builtin::BI__sync_lock_release_1:
401 case Builtin::BI__sync_lock_release_2:
402 case Builtin::BI__sync_lock_release_4:
403 case Builtin::BI__sync_lock_release_8:
404 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000405 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000406 case Builtin::BI__sync_swap_1:
407 case Builtin::BI__sync_swap_2:
408 case Builtin::BI__sync_swap_4:
409 case Builtin::BI__sync_swap_8:
410 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000411 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000412#define BUILTIN(ID, TYPE, ATTRS)
413#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
414 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000415 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000416#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000417 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000418 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000419 return ExprError();
420 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000421 case Builtin::BI__builtin_addressof:
422 if (SemaBuiltinAddressof(*this, TheCall))
423 return ExprError();
424 break;
Richard Smith760520b2014-06-03 23:27:44 +0000425 case Builtin::BI__builtin_operator_new:
426 case Builtin::BI__builtin_operator_delete:
427 if (!getLangOpts().CPlusPlus) {
428 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
429 << (BuiltinID == Builtin::BI__builtin_operator_new
430 ? "__builtin_operator_new"
431 : "__builtin_operator_delete")
432 << "C++";
433 return ExprError();
434 }
435 // CodeGen assumes it can find the global new and delete to call,
436 // so ensure that they are declared.
437 DeclareGlobalNewDelete();
438 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000439
440 // check secure string manipulation functions where overflows
441 // are detectable at compile time
442 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000443 case Builtin::BI__builtin___memmove_chk:
444 case Builtin::BI__builtin___memset_chk:
445 case Builtin::BI__builtin___strlcat_chk:
446 case Builtin::BI__builtin___strlcpy_chk:
447 case Builtin::BI__builtin___strncat_chk:
448 case Builtin::BI__builtin___strncpy_chk:
449 case Builtin::BI__builtin___stpncpy_chk:
450 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
451 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000452 case Builtin::BI__builtin___memccpy_chk:
453 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
454 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000455 case Builtin::BI__builtin___snprintf_chk:
456 case Builtin::BI__builtin___vsnprintf_chk:
457 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
458 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000459
460 case Builtin::BI__builtin_call_with_static_chain:
461 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
462 return ExprError();
463 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000464 }
Richard Smith760520b2014-06-03 23:27:44 +0000465
Nate Begeman4904e322010-06-08 02:47:44 +0000466 // Since the target specific builtins for each arch overlap, only check those
467 // of the arch we are compiling for.
468 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000469 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000470 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000471 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000472 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000473 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000474 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
475 return ExprError();
476 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000477 case llvm::Triple::aarch64:
478 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000479 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000480 return ExprError();
481 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000482 case llvm::Triple::mips:
483 case llvm::Triple::mipsel:
484 case llvm::Triple::mips64:
485 case llvm::Triple::mips64el:
486 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
487 return ExprError();
488 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000489 case llvm::Triple::x86:
490 case llvm::Triple::x86_64:
491 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
492 return ExprError();
493 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000494 default:
495 break;
496 }
497 }
498
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000499 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000500}
501
Nate Begeman91e1fea2010-06-14 05:21:25 +0000502// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000503static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000504 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000505 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000506 switch (Type.getEltType()) {
507 case NeonTypeFlags::Int8:
508 case NeonTypeFlags::Poly8:
509 return shift ? 7 : (8 << IsQuad) - 1;
510 case NeonTypeFlags::Int16:
511 case NeonTypeFlags::Poly16:
512 return shift ? 15 : (4 << IsQuad) - 1;
513 case NeonTypeFlags::Int32:
514 return shift ? 31 : (2 << IsQuad) - 1;
515 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000516 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000517 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000518 case NeonTypeFlags::Poly128:
519 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000520 case NeonTypeFlags::Float16:
521 assert(!shift && "cannot shift float types!");
522 return (4 << IsQuad) - 1;
523 case NeonTypeFlags::Float32:
524 assert(!shift && "cannot shift float types!");
525 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000526 case NeonTypeFlags::Float64:
527 assert(!shift && "cannot shift float types!");
528 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000529 }
David Blaikie8a40f702012-01-17 06:56:22 +0000530 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000531}
532
Bob Wilsone4d77232011-11-08 05:04:11 +0000533/// getNeonEltType - Return the QualType corresponding to the elements of
534/// the vector type specified by the NeonTypeFlags. This is used to check
535/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000536static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000537 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000538 switch (Flags.getEltType()) {
539 case NeonTypeFlags::Int8:
540 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
541 case NeonTypeFlags::Int16:
542 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
543 case NeonTypeFlags::Int32:
544 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
545 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000546 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000547 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
548 else
549 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
550 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000551 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000552 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000553 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000554 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000555 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000556 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000557 case NeonTypeFlags::Poly128:
558 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000559 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000560 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000561 case NeonTypeFlags::Float32:
562 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000563 case NeonTypeFlags::Float64:
564 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000565 }
David Blaikie8a40f702012-01-17 06:56:22 +0000566 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000567}
568
Tim Northover12670412014-02-19 10:37:05 +0000569bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000570 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000571 uint64_t mask = 0;
572 unsigned TV = 0;
573 int PtrArgNum = -1;
574 bool HasConstPtr = false;
575 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000576#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000577#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000578#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000579 }
580
581 // For NEON intrinsics which are overloaded on vector element type, validate
582 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000583 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000584 if (mask) {
585 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
586 return true;
587
588 TV = Result.getLimitedValue(64);
589 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
590 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000591 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000592 }
593
594 if (PtrArgNum >= 0) {
595 // Check that pointer arguments have the specified type.
596 Expr *Arg = TheCall->getArg(PtrArgNum);
597 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
598 Arg = ICE->getSubExpr();
599 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
600 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000601
Tim Northovera2ee4332014-03-29 15:09:45 +0000602 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000603 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000604 bool IsInt64Long =
605 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
606 QualType EltTy =
607 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000608 if (HasConstPtr)
609 EltTy = EltTy.withConst();
610 QualType LHSTy = Context.getPointerType(EltTy);
611 AssignConvertType ConvTy;
612 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
613 if (RHS.isInvalid())
614 return true;
615 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
616 RHS.get(), AA_Assigning))
617 return true;
618 }
619
620 // For NEON intrinsics which take an immediate value as part of the
621 // instruction, range check them here.
622 unsigned i = 0, l = 0, u = 0;
623 switch (BuiltinID) {
624 default:
625 return false;
Tim Northover12670412014-02-19 10:37:05 +0000626#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000627#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000628#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000629 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000630
Richard Sandiford28940af2014-04-16 08:47:51 +0000631 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000632}
633
Tim Northovera2ee4332014-03-29 15:09:45 +0000634bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
635 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000636 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000637 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000638 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000639 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000640 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000641 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
642 BuiltinID == AArch64::BI__builtin_arm_strex ||
643 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000644 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000645 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000646 BuiltinID == ARM::BI__builtin_arm_ldaex ||
647 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
648 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000649
650 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
651
652 // Ensure that we have the proper number of arguments.
653 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
654 return true;
655
656 // Inspect the pointer argument of the atomic builtin. This should always be
657 // a pointer type, whose element is an integral scalar or pointer type.
658 // Because it is a pointer type, we don't have to worry about any implicit
659 // casts here.
660 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
661 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
662 if (PointerArgRes.isInvalid())
663 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000664 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000665
666 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
667 if (!pointerType) {
668 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
669 << PointerArg->getType() << PointerArg->getSourceRange();
670 return true;
671 }
672
673 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
674 // task is to insert the appropriate casts into the AST. First work out just
675 // what the appropriate type is.
676 QualType ValType = pointerType->getPointeeType();
677 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
678 if (IsLdrex)
679 AddrType.addConst();
680
681 // Issue a warning if the cast is dodgy.
682 CastKind CastNeeded = CK_NoOp;
683 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
684 CastNeeded = CK_BitCast;
685 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
686 << PointerArg->getType()
687 << Context.getPointerType(AddrType)
688 << AA_Passing << PointerArg->getSourceRange();
689 }
690
691 // Finally, do the cast and replace the argument with the corrected version.
692 AddrType = Context.getPointerType(AddrType);
693 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
694 if (PointerArgRes.isInvalid())
695 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000696 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000697
698 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
699
700 // In general, we allow ints, floats and pointers to be loaded and stored.
701 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
702 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
703 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
704 << PointerArg->getType() << PointerArg->getSourceRange();
705 return true;
706 }
707
708 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000709 if (Context.getTypeSize(ValType) > MaxWidth) {
710 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000711 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
712 << PointerArg->getType() << PointerArg->getSourceRange();
713 return true;
714 }
715
716 switch (ValType.getObjCLifetime()) {
717 case Qualifiers::OCL_None:
718 case Qualifiers::OCL_ExplicitNone:
719 // okay
720 break;
721
722 case Qualifiers::OCL_Weak:
723 case Qualifiers::OCL_Strong:
724 case Qualifiers::OCL_Autoreleasing:
725 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
726 << ValType << PointerArg->getSourceRange();
727 return true;
728 }
729
730
731 if (IsLdrex) {
732 TheCall->setType(ValType);
733 return false;
734 }
735
736 // Initialize the argument to be stored.
737 ExprResult ValArg = TheCall->getArg(0);
738 InitializedEntity Entity = InitializedEntity::InitializeParameter(
739 Context, ValType, /*consume*/ false);
740 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
741 if (ValArg.isInvalid())
742 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000743 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000744
745 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
746 // but the custom checker bypasses all default analysis.
747 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000748 return false;
749}
750
Nate Begeman4904e322010-06-08 02:47:44 +0000751bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000752 llvm::APSInt Result;
753
Tim Northover6aacd492013-07-16 09:47:53 +0000754 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000755 BuiltinID == ARM::BI__builtin_arm_ldaex ||
756 BuiltinID == ARM::BI__builtin_arm_strex ||
757 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000758 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000759 }
760
Yi Kong26d104a2014-08-13 19:18:14 +0000761 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
762 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
763 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
764 }
765
Tim Northover12670412014-02-19 10:37:05 +0000766 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
767 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000768
Yi Kong4efadfb2014-07-03 16:01:25 +0000769 // For intrinsics which take an immediate value as part of the instruction,
770 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000771 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000772 switch (BuiltinID) {
773 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000774 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
775 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000776 case ARM::BI__builtin_arm_vcvtr_f:
777 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000778 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000779 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000780 case ARM::BI__builtin_arm_isb:
781 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000782 }
Nate Begemand773fe62010-06-13 04:47:52 +0000783
Nate Begemanf568b072010-08-03 21:32:34 +0000784 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000785 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000786}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000787
Tim Northover573cbee2014-05-24 12:52:07 +0000788bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000789 CallExpr *TheCall) {
790 llvm::APSInt Result;
791
Tim Northover573cbee2014-05-24 12:52:07 +0000792 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000793 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
794 BuiltinID == AArch64::BI__builtin_arm_strex ||
795 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000796 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
797 }
798
Yi Konga5548432014-08-13 19:18:20 +0000799 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
800 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
801 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
802 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
803 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
804 }
805
Tim Northovera2ee4332014-03-29 15:09:45 +0000806 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
807 return true;
808
Yi Kong19a29ac2014-07-17 10:52:06 +0000809 // For intrinsics which take an immediate value as part of the instruction,
810 // range check them here.
811 unsigned i = 0, l = 0, u = 0;
812 switch (BuiltinID) {
813 default: return false;
814 case AArch64::BI__builtin_arm_dmb:
815 case AArch64::BI__builtin_arm_dsb:
816 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
817 }
818
Yi Kong19a29ac2014-07-17 10:52:06 +0000819 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000820}
821
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000822bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
823 unsigned i = 0, l = 0, u = 0;
824 switch (BuiltinID) {
825 default: return false;
826 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
827 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000828 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
829 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
830 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
831 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
832 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000833 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000834
Richard Sandiford28940af2014-04-16 08:47:51 +0000835 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000836}
837
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000838bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
839 switch (BuiltinID) {
840 case X86::BI_mm_prefetch:
Richard Sandiford28940af2014-04-16 08:47:51 +0000841 // This is declared to take (const char*, int)
842 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000843 }
844 return false;
845}
846
Richard Smith55ce3522012-06-25 20:30:08 +0000847/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
848/// parameter with the FormatAttr's correct format_idx and firstDataArg.
849/// Returns true when the format fits the function and the FormatStringInfo has
850/// been populated.
851bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
852 FormatStringInfo *FSI) {
853 FSI->HasVAListArg = Format->getFirstArg() == 0;
854 FSI->FormatIdx = Format->getFormatIdx() - 1;
855 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000856
Richard Smith55ce3522012-06-25 20:30:08 +0000857 // The way the format attribute works in GCC, the implicit this argument
858 // of member functions is counted. However, it doesn't appear in our own
859 // lists, so decrement format_idx in that case.
860 if (IsCXXMember) {
861 if(FSI->FormatIdx == 0)
862 return false;
863 --FSI->FormatIdx;
864 if (FSI->FirstDataArg != 0)
865 --FSI->FirstDataArg;
866 }
867 return true;
868}
Mike Stump11289f42009-09-09 15:08:12 +0000869
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000870/// Checks if a the given expression evaluates to null.
871///
872/// \brief Returns true if the value evaluates to null.
873static bool CheckNonNullExpr(Sema &S,
874 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000875 // As a special case, transparent unions initialized with zero are
876 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000877 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000878 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
879 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000880 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000881 if (const InitListExpr *ILE =
882 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000883 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000884 }
885
886 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000887 return (!Expr->isValueDependent() &&
888 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
889 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000890}
891
892static void CheckNonNullArgument(Sema &S,
893 const Expr *ArgExpr,
894 SourceLocation CallSiteLoc) {
895 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000896 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
897}
898
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000899bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
900 FormatStringInfo FSI;
901 if ((GetFormatStringType(Format) == FST_NSString) &&
902 getFormatStringInfo(Format, false, &FSI)) {
903 Idx = FSI.FormatIdx;
904 return true;
905 }
906 return false;
907}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000908/// \brief Diagnose use of %s directive in an NSString which is being passed
909/// as formatting string to formatting method.
910static void
911DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
912 const NamedDecl *FDecl,
913 Expr **Args,
914 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000915 unsigned Idx = 0;
916 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000917 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
918 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000919 Idx = 2;
920 Format = true;
921 }
922 else
923 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
924 if (S.GetFormatNSStringIdx(I, Idx)) {
925 Format = true;
926 break;
927 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000928 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000929 if (!Format || NumArgs <= Idx)
930 return;
931 const Expr *FormatExpr = Args[Idx];
932 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
933 FormatExpr = CSCE->getSubExpr();
934 const StringLiteral *FormatString;
935 if (const ObjCStringLiteral *OSL =
936 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
937 FormatString = OSL->getString();
938 else
939 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
940 if (!FormatString)
941 return;
942 if (S.FormatStringHasSArg(FormatString)) {
943 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
944 << "%s" << 1 << 1;
945 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
946 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000947 }
948}
949
Ted Kremenek2bc73332014-01-17 06:24:43 +0000950static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000951 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +0000952 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000953 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000954 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +0000955 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000956 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +0000957 if (!NonNull->args_size()) {
958 // Easy case: all pointer arguments are nonnull.
959 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +0000960 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +0000961 CheckNonNullArgument(S, Arg, CallSiteLoc);
962 return;
963 }
964
965 for (unsigned Val : NonNull->args()) {
966 if (Val >= Args.size())
967 continue;
968 if (NonNullArgs.empty())
969 NonNullArgs.resize(Args.size());
970 NonNullArgs.set(Val);
971 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000972 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000973
974 // Check the attributes on the parameters.
975 ArrayRef<ParmVarDecl*> parms;
976 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
977 parms = FD->parameters();
978 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
979 parms = MD->parameters();
980
Richard Smith588bd9b2014-08-27 04:59:42 +0000981 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +0000982 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +0000983 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000984 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +0000985 if (PVD->hasAttr<NonNullAttr>() ||
986 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
987 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +0000988 }
Richard Smith588bd9b2014-08-27 04:59:42 +0000989
990 // In case this is a variadic call, check any remaining arguments.
991 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
992 if (NonNullArgs[ArgIndex])
993 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000994}
995
Richard Smith55ce3522012-06-25 20:30:08 +0000996/// Handles the checks for format strings, non-POD arguments to vararg
997/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000998void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
999 unsigned NumParams, bool IsMemberFunction,
1000 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001001 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001002 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001003 if (CurContext->isDependentContext())
1004 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001005
Ted Kremenekb8176da2010-09-09 04:33:05 +00001006 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001007 llvm::SmallBitVector CheckedVarArgs;
1008 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001009 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001010 // Only create vector if there are format attributes.
1011 CheckedVarArgs.resize(Args.size());
1012
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001013 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001014 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001015 }
Richard Smithd7293d72013-08-05 18:49:43 +00001016 }
Richard Smith55ce3522012-06-25 20:30:08 +00001017
1018 // Refuse POD arguments that weren't caught by the format string
1019 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001020 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001021 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001022 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001023 if (const Expr *Arg = Args[ArgIdx]) {
1024 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1025 checkVariadicArgument(Arg, CallType);
1026 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001027 }
Richard Smithd7293d72013-08-05 18:49:43 +00001028 }
Mike Stump11289f42009-09-09 15:08:12 +00001029
Richard Trieu41bc0992013-06-22 00:20:41 +00001030 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001031 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001032
Richard Trieu41bc0992013-06-22 00:20:41 +00001033 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001034 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1035 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001036 }
Richard Smith55ce3522012-06-25 20:30:08 +00001037}
1038
1039/// CheckConstructorCall - Check a constructor call for correctness and safety
1040/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001041void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1042 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001043 const FunctionProtoType *Proto,
1044 SourceLocation Loc) {
1045 VariadicCallType CallType =
1046 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +00001047 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +00001048 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1049}
1050
1051/// CheckFunctionCall - Check a direct function call for various correctness
1052/// and safety properties not strictly enforced by the C type system.
1053bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1054 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001055 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1056 isa<CXXMethodDecl>(FDecl);
1057 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1058 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001059 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1060 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001061 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +00001062 Expr** Args = TheCall->getArgs();
1063 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001064 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001065 // If this is a call to a member operator, hide the first argument
1066 // from checkCall.
1067 // FIXME: Our choice of AST representation here is less than ideal.
1068 ++Args;
1069 --NumArgs;
1070 }
Craig Topper8c2a2a02014-08-30 16:55:39 +00001071 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +00001072 IsMemberFunction, TheCall->getRParenLoc(),
1073 TheCall->getCallee()->getSourceRange(), CallType);
1074
1075 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1076 // None of the checks below are needed for functions that don't have
1077 // simple names (e.g., C++ conversion functions).
1078 if (!FnInfo)
1079 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001080
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001081 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001082 if (getLangOpts().ObjC1)
1083 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001084
Anna Zaks22122702012-01-17 00:37:07 +00001085 unsigned CMId = FDecl->getMemoryFunctionKind();
1086 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001087 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001088
Anna Zaks201d4892012-01-13 21:52:01 +00001089 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001090 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001091 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001092 else if (CMId == Builtin::BIstrncat)
1093 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001094 else
Anna Zaks22122702012-01-17 00:37:07 +00001095 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001096
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001097 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001098}
1099
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001100bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001101 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001102 VariadicCallType CallType =
1103 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001104
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001105 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001106 /*IsMemberFunction=*/false,
1107 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001108
1109 return false;
1110}
1111
Richard Trieu664c4c62013-06-20 21:03:13 +00001112bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1113 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001114 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1115 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001116 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001117
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001118 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +00001119 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001120 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001121
Richard Trieu664c4c62013-06-20 21:03:13 +00001122 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001123 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001124 CallType = VariadicDoesNotApply;
1125 } else if (Ty->isBlockPointerType()) {
1126 CallType = VariadicBlock;
1127 } else { // Ty->isFunctionPointerType()
1128 CallType = VariadicFunction;
1129 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001130 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001131
Craig Topper8c2a2a02014-08-30 16:55:39 +00001132 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1133 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001134 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001135 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001136
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001137 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001138}
1139
Richard Trieu41bc0992013-06-22 00:20:41 +00001140/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1141/// such as function pointers returned from functions.
1142bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001143 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001144 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001145 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001146
Craig Topperc3ec1492014-05-26 06:22:03 +00001147 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001148 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001149 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001150 TheCall->getCallee()->getSourceRange(), CallType);
1151
1152 return false;
1153}
1154
Tim Northovere94a34c2014-03-11 10:49:14 +00001155static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1156 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1157 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1158 return false;
1159
1160 switch (Op) {
1161 case AtomicExpr::AO__c11_atomic_init:
1162 llvm_unreachable("There is no ordering argument for an init");
1163
1164 case AtomicExpr::AO__c11_atomic_load:
1165 case AtomicExpr::AO__atomic_load_n:
1166 case AtomicExpr::AO__atomic_load:
1167 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1168 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1169
1170 case AtomicExpr::AO__c11_atomic_store:
1171 case AtomicExpr::AO__atomic_store:
1172 case AtomicExpr::AO__atomic_store_n:
1173 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1174 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1175 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1176
1177 default:
1178 return true;
1179 }
1180}
1181
Richard Smithfeea8832012-04-12 05:08:17 +00001182ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1183 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001184 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1185 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001186
Richard Smithfeea8832012-04-12 05:08:17 +00001187 // All these operations take one of the following forms:
1188 enum {
1189 // C __c11_atomic_init(A *, C)
1190 Init,
1191 // C __c11_atomic_load(A *, int)
1192 Load,
1193 // void __atomic_load(A *, CP, int)
1194 Copy,
1195 // C __c11_atomic_add(A *, M, int)
1196 Arithmetic,
1197 // C __atomic_exchange_n(A *, CP, int)
1198 Xchg,
1199 // void __atomic_exchange(A *, C *, CP, int)
1200 GNUXchg,
1201 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1202 C11CmpXchg,
1203 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1204 GNUCmpXchg
1205 } Form = Init;
1206 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1207 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1208 // where:
1209 // C is an appropriate type,
1210 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1211 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1212 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1213 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001214
Richard Smithfeea8832012-04-12 05:08:17 +00001215 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1216 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1217 && "need to update code for modified C11 atomics");
1218 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1219 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1220 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1221 Op == AtomicExpr::AO__atomic_store_n ||
1222 Op == AtomicExpr::AO__atomic_exchange_n ||
1223 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1224 bool IsAddSub = false;
1225
1226 switch (Op) {
1227 case AtomicExpr::AO__c11_atomic_init:
1228 Form = Init;
1229 break;
1230
1231 case AtomicExpr::AO__c11_atomic_load:
1232 case AtomicExpr::AO__atomic_load_n:
1233 Form = Load;
1234 break;
1235
1236 case AtomicExpr::AO__c11_atomic_store:
1237 case AtomicExpr::AO__atomic_load:
1238 case AtomicExpr::AO__atomic_store:
1239 case AtomicExpr::AO__atomic_store_n:
1240 Form = Copy;
1241 break;
1242
1243 case AtomicExpr::AO__c11_atomic_fetch_add:
1244 case AtomicExpr::AO__c11_atomic_fetch_sub:
1245 case AtomicExpr::AO__atomic_fetch_add:
1246 case AtomicExpr::AO__atomic_fetch_sub:
1247 case AtomicExpr::AO__atomic_add_fetch:
1248 case AtomicExpr::AO__atomic_sub_fetch:
1249 IsAddSub = true;
1250 // Fall through.
1251 case AtomicExpr::AO__c11_atomic_fetch_and:
1252 case AtomicExpr::AO__c11_atomic_fetch_or:
1253 case AtomicExpr::AO__c11_atomic_fetch_xor:
1254 case AtomicExpr::AO__atomic_fetch_and:
1255 case AtomicExpr::AO__atomic_fetch_or:
1256 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001257 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001258 case AtomicExpr::AO__atomic_and_fetch:
1259 case AtomicExpr::AO__atomic_or_fetch:
1260 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001261 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001262 Form = Arithmetic;
1263 break;
1264
1265 case AtomicExpr::AO__c11_atomic_exchange:
1266 case AtomicExpr::AO__atomic_exchange_n:
1267 Form = Xchg;
1268 break;
1269
1270 case AtomicExpr::AO__atomic_exchange:
1271 Form = GNUXchg;
1272 break;
1273
1274 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1275 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1276 Form = C11CmpXchg;
1277 break;
1278
1279 case AtomicExpr::AO__atomic_compare_exchange:
1280 case AtomicExpr::AO__atomic_compare_exchange_n:
1281 Form = GNUCmpXchg;
1282 break;
1283 }
1284
1285 // Check we have the right number of arguments.
1286 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001287 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001288 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001289 << TheCall->getCallee()->getSourceRange();
1290 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001291 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1292 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001293 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001294 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001295 << TheCall->getCallee()->getSourceRange();
1296 return ExprError();
1297 }
1298
Richard Smithfeea8832012-04-12 05:08:17 +00001299 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001300 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001301 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1302 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1303 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001304 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001305 << Ptr->getType() << Ptr->getSourceRange();
1306 return ExprError();
1307 }
1308
Richard Smithfeea8832012-04-12 05:08:17 +00001309 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1310 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1311 QualType ValType = AtomTy; // 'C'
1312 if (IsC11) {
1313 if (!AtomTy->isAtomicType()) {
1314 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1315 << Ptr->getType() << Ptr->getSourceRange();
1316 return ExprError();
1317 }
Richard Smithe00921a2012-09-15 06:09:58 +00001318 if (AtomTy.isConstQualified()) {
1319 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1320 << Ptr->getType() << Ptr->getSourceRange();
1321 return ExprError();
1322 }
Richard Smithfeea8832012-04-12 05:08:17 +00001323 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001324 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001325
Richard Smithfeea8832012-04-12 05:08:17 +00001326 // For an arithmetic operation, the implied arithmetic must be well-formed.
1327 if (Form == Arithmetic) {
1328 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1329 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1330 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1331 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1332 return ExprError();
1333 }
1334 if (!IsAddSub && !ValType->isIntegerType()) {
1335 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1336 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1337 return ExprError();
1338 }
1339 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1340 // For __atomic_*_n operations, the value type must be a scalar integral or
1341 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001342 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001343 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1344 return ExprError();
1345 }
1346
Eli Friedmanaa769812013-09-11 03:49:34 +00001347 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1348 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001349 // For GNU atomics, require a trivially-copyable type. This is not part of
1350 // the GNU atomics specification, but we enforce it for sanity.
1351 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001352 << Ptr->getType() << Ptr->getSourceRange();
1353 return ExprError();
1354 }
1355
Richard Smithfeea8832012-04-12 05:08:17 +00001356 // FIXME: For any builtin other than a load, the ValType must not be
1357 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001358
1359 switch (ValType.getObjCLifetime()) {
1360 case Qualifiers::OCL_None:
1361 case Qualifiers::OCL_ExplicitNone:
1362 // okay
1363 break;
1364
1365 case Qualifiers::OCL_Weak:
1366 case Qualifiers::OCL_Strong:
1367 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001368 // FIXME: Can this happen? By this point, ValType should be known
1369 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001370 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1371 << ValType << Ptr->getSourceRange();
1372 return ExprError();
1373 }
1374
1375 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001376 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001377 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001378 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001379 ResultType = Context.BoolTy;
1380
Richard Smithfeea8832012-04-12 05:08:17 +00001381 // The type of a parameter passed 'by value'. In the GNU atomics, such
1382 // arguments are actually passed as pointers.
1383 QualType ByValType = ValType; // 'CP'
1384 if (!IsC11 && !IsN)
1385 ByValType = Ptr->getType();
1386
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001387 // The first argument --- the pointer --- has a fixed type; we
1388 // deduce the types of the rest of the arguments accordingly. Walk
1389 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001390 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001391 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001392 if (i < NumVals[Form] + 1) {
1393 switch (i) {
1394 case 1:
1395 // The second argument is the non-atomic operand. For arithmetic, this
1396 // is always passed by value, and for a compare_exchange it is always
1397 // passed by address. For the rest, GNU uses by-address and C11 uses
1398 // by-value.
1399 assert(Form != Load);
1400 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1401 Ty = ValType;
1402 else if (Form == Copy || Form == Xchg)
1403 Ty = ByValType;
1404 else if (Form == Arithmetic)
1405 Ty = Context.getPointerDiffType();
1406 else
1407 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1408 break;
1409 case 2:
1410 // The third argument to compare_exchange / GNU exchange is a
1411 // (pointer to a) desired value.
1412 Ty = ByValType;
1413 break;
1414 case 3:
1415 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1416 Ty = Context.BoolTy;
1417 break;
1418 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001419 } else {
1420 // The order(s) are always converted to int.
1421 Ty = Context.IntTy;
1422 }
Richard Smithfeea8832012-04-12 05:08:17 +00001423
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001424 InitializedEntity Entity =
1425 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001426 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001427 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1428 if (Arg.isInvalid())
1429 return true;
1430 TheCall->setArg(i, Arg.get());
1431 }
1432
Richard Smithfeea8832012-04-12 05:08:17 +00001433 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001434 SmallVector<Expr*, 5> SubExprs;
1435 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001436 switch (Form) {
1437 case Init:
1438 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001439 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001440 break;
1441 case Load:
1442 SubExprs.push_back(TheCall->getArg(1)); // Order
1443 break;
1444 case Copy:
1445 case Arithmetic:
1446 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001447 SubExprs.push_back(TheCall->getArg(2)); // Order
1448 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001449 break;
1450 case GNUXchg:
1451 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1452 SubExprs.push_back(TheCall->getArg(3)); // Order
1453 SubExprs.push_back(TheCall->getArg(1)); // Val1
1454 SubExprs.push_back(TheCall->getArg(2)); // Val2
1455 break;
1456 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001457 SubExprs.push_back(TheCall->getArg(3)); // Order
1458 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001459 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001460 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001461 break;
1462 case GNUCmpXchg:
1463 SubExprs.push_back(TheCall->getArg(4)); // Order
1464 SubExprs.push_back(TheCall->getArg(1)); // Val1
1465 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1466 SubExprs.push_back(TheCall->getArg(2)); // Val2
1467 SubExprs.push_back(TheCall->getArg(3)); // Weak
1468 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001469 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001470
1471 if (SubExprs.size() >= 2 && Form != Init) {
1472 llvm::APSInt Result(32);
1473 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1474 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001475 Diag(SubExprs[1]->getLocStart(),
1476 diag::warn_atomic_op_has_invalid_memory_order)
1477 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001478 }
1479
Fariborz Jahanian615de762013-05-28 17:37:39 +00001480 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1481 SubExprs, ResultType, Op,
1482 TheCall->getRParenLoc());
1483
1484 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1485 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1486 Context.AtomicUsesUnsupportedLibcall(AE))
1487 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1488 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001489
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001490 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001491}
1492
1493
John McCall29ad95b2011-08-27 01:09:30 +00001494/// checkBuiltinArgument - Given a call to a builtin function, perform
1495/// normal type-checking on the given argument, updating the call in
1496/// place. This is useful when a builtin function requires custom
1497/// type-checking for some of its arguments but not necessarily all of
1498/// them.
1499///
1500/// Returns true on error.
1501static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1502 FunctionDecl *Fn = E->getDirectCallee();
1503 assert(Fn && "builtin call without direct callee!");
1504
1505 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1506 InitializedEntity Entity =
1507 InitializedEntity::InitializeParameter(S.Context, Param);
1508
1509 ExprResult Arg = E->getArg(0);
1510 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1511 if (Arg.isInvalid())
1512 return true;
1513
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001514 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001515 return false;
1516}
1517
Chris Lattnerdc046542009-05-08 06:58:22 +00001518/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1519/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1520/// type of its first argument. The main ActOnCallExpr routines have already
1521/// promoted the types of arguments because all of these calls are prototyped as
1522/// void(...).
1523///
1524/// This function goes through and does final semantic checking for these
1525/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001526ExprResult
1527Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001528 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001529 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1530 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1531
1532 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001533 if (TheCall->getNumArgs() < 1) {
1534 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1535 << 0 << 1 << TheCall->getNumArgs()
1536 << TheCall->getCallee()->getSourceRange();
1537 return ExprError();
1538 }
Mike Stump11289f42009-09-09 15:08:12 +00001539
Chris Lattnerdc046542009-05-08 06:58:22 +00001540 // Inspect the first argument of the atomic builtin. This should always be
1541 // a pointer type, whose element is an integral scalar or pointer type.
1542 // Because it is a pointer type, we don't have to worry about any implicit
1543 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001544 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001545 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001546 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1547 if (FirstArgResult.isInvalid())
1548 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001549 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001550 TheCall->setArg(0, FirstArg);
1551
John McCall31168b02011-06-15 23:02:42 +00001552 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1553 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001554 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1555 << FirstArg->getType() << FirstArg->getSourceRange();
1556 return ExprError();
1557 }
Mike Stump11289f42009-09-09 15:08:12 +00001558
John McCall31168b02011-06-15 23:02:42 +00001559 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001560 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001561 !ValType->isBlockPointerType()) {
1562 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1563 << FirstArg->getType() << FirstArg->getSourceRange();
1564 return ExprError();
1565 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001566
John McCall31168b02011-06-15 23:02:42 +00001567 switch (ValType.getObjCLifetime()) {
1568 case Qualifiers::OCL_None:
1569 case Qualifiers::OCL_ExplicitNone:
1570 // okay
1571 break;
1572
1573 case Qualifiers::OCL_Weak:
1574 case Qualifiers::OCL_Strong:
1575 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001576 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001577 << ValType << FirstArg->getSourceRange();
1578 return ExprError();
1579 }
1580
John McCallb50451a2011-10-05 07:41:44 +00001581 // Strip any qualifiers off ValType.
1582 ValType = ValType.getUnqualifiedType();
1583
Chandler Carruth3973af72010-07-18 20:54:12 +00001584 // The majority of builtins return a value, but a few have special return
1585 // types, so allow them to override appropriately below.
1586 QualType ResultType = ValType;
1587
Chris Lattnerdc046542009-05-08 06:58:22 +00001588 // We need to figure out which concrete builtin this maps onto. For example,
1589 // __sync_fetch_and_add with a 2 byte object turns into
1590 // __sync_fetch_and_add_2.
1591#define BUILTIN_ROW(x) \
1592 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1593 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001594
Chris Lattnerdc046542009-05-08 06:58:22 +00001595 static const unsigned BuiltinIndices[][5] = {
1596 BUILTIN_ROW(__sync_fetch_and_add),
1597 BUILTIN_ROW(__sync_fetch_and_sub),
1598 BUILTIN_ROW(__sync_fetch_and_or),
1599 BUILTIN_ROW(__sync_fetch_and_and),
1600 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001601 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001602
Chris Lattnerdc046542009-05-08 06:58:22 +00001603 BUILTIN_ROW(__sync_add_and_fetch),
1604 BUILTIN_ROW(__sync_sub_and_fetch),
1605 BUILTIN_ROW(__sync_and_and_fetch),
1606 BUILTIN_ROW(__sync_or_and_fetch),
1607 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001608 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001609
Chris Lattnerdc046542009-05-08 06:58:22 +00001610 BUILTIN_ROW(__sync_val_compare_and_swap),
1611 BUILTIN_ROW(__sync_bool_compare_and_swap),
1612 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001613 BUILTIN_ROW(__sync_lock_release),
1614 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001615 };
Mike Stump11289f42009-09-09 15:08:12 +00001616#undef BUILTIN_ROW
1617
Chris Lattnerdc046542009-05-08 06:58:22 +00001618 // Determine the index of the size.
1619 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001620 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001621 case 1: SizeIndex = 0; break;
1622 case 2: SizeIndex = 1; break;
1623 case 4: SizeIndex = 2; break;
1624 case 8: SizeIndex = 3; break;
1625 case 16: SizeIndex = 4; break;
1626 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001627 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1628 << FirstArg->getType() << FirstArg->getSourceRange();
1629 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001630 }
Mike Stump11289f42009-09-09 15:08:12 +00001631
Chris Lattnerdc046542009-05-08 06:58:22 +00001632 // Each of these builtins has one pointer argument, followed by some number of
1633 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1634 // that we ignore. Find out which row of BuiltinIndices to read from as well
1635 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001636 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001637 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001638 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001639 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001640 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001641 case Builtin::BI__sync_fetch_and_add:
1642 case Builtin::BI__sync_fetch_and_add_1:
1643 case Builtin::BI__sync_fetch_and_add_2:
1644 case Builtin::BI__sync_fetch_and_add_4:
1645 case Builtin::BI__sync_fetch_and_add_8:
1646 case Builtin::BI__sync_fetch_and_add_16:
1647 BuiltinIndex = 0;
1648 break;
1649
1650 case Builtin::BI__sync_fetch_and_sub:
1651 case Builtin::BI__sync_fetch_and_sub_1:
1652 case Builtin::BI__sync_fetch_and_sub_2:
1653 case Builtin::BI__sync_fetch_and_sub_4:
1654 case Builtin::BI__sync_fetch_and_sub_8:
1655 case Builtin::BI__sync_fetch_and_sub_16:
1656 BuiltinIndex = 1;
1657 break;
1658
1659 case Builtin::BI__sync_fetch_and_or:
1660 case Builtin::BI__sync_fetch_and_or_1:
1661 case Builtin::BI__sync_fetch_and_or_2:
1662 case Builtin::BI__sync_fetch_and_or_4:
1663 case Builtin::BI__sync_fetch_and_or_8:
1664 case Builtin::BI__sync_fetch_and_or_16:
1665 BuiltinIndex = 2;
1666 break;
1667
1668 case Builtin::BI__sync_fetch_and_and:
1669 case Builtin::BI__sync_fetch_and_and_1:
1670 case Builtin::BI__sync_fetch_and_and_2:
1671 case Builtin::BI__sync_fetch_and_and_4:
1672 case Builtin::BI__sync_fetch_and_and_8:
1673 case Builtin::BI__sync_fetch_and_and_16:
1674 BuiltinIndex = 3;
1675 break;
Mike Stump11289f42009-09-09 15:08:12 +00001676
Douglas Gregor73722482011-11-28 16:30:08 +00001677 case Builtin::BI__sync_fetch_and_xor:
1678 case Builtin::BI__sync_fetch_and_xor_1:
1679 case Builtin::BI__sync_fetch_and_xor_2:
1680 case Builtin::BI__sync_fetch_and_xor_4:
1681 case Builtin::BI__sync_fetch_and_xor_8:
1682 case Builtin::BI__sync_fetch_and_xor_16:
1683 BuiltinIndex = 4;
1684 break;
1685
Hal Finkeld2208b52014-10-02 20:53:50 +00001686 case Builtin::BI__sync_fetch_and_nand:
1687 case Builtin::BI__sync_fetch_and_nand_1:
1688 case Builtin::BI__sync_fetch_and_nand_2:
1689 case Builtin::BI__sync_fetch_and_nand_4:
1690 case Builtin::BI__sync_fetch_and_nand_8:
1691 case Builtin::BI__sync_fetch_and_nand_16:
1692 BuiltinIndex = 5;
1693 WarnAboutSemanticsChange = true;
1694 break;
1695
Douglas Gregor73722482011-11-28 16:30:08 +00001696 case Builtin::BI__sync_add_and_fetch:
1697 case Builtin::BI__sync_add_and_fetch_1:
1698 case Builtin::BI__sync_add_and_fetch_2:
1699 case Builtin::BI__sync_add_and_fetch_4:
1700 case Builtin::BI__sync_add_and_fetch_8:
1701 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001702 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00001703 break;
1704
1705 case Builtin::BI__sync_sub_and_fetch:
1706 case Builtin::BI__sync_sub_and_fetch_1:
1707 case Builtin::BI__sync_sub_and_fetch_2:
1708 case Builtin::BI__sync_sub_and_fetch_4:
1709 case Builtin::BI__sync_sub_and_fetch_8:
1710 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001711 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00001712 break;
1713
1714 case Builtin::BI__sync_and_and_fetch:
1715 case Builtin::BI__sync_and_and_fetch_1:
1716 case Builtin::BI__sync_and_and_fetch_2:
1717 case Builtin::BI__sync_and_and_fetch_4:
1718 case Builtin::BI__sync_and_and_fetch_8:
1719 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001720 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00001721 break;
1722
1723 case Builtin::BI__sync_or_and_fetch:
1724 case Builtin::BI__sync_or_and_fetch_1:
1725 case Builtin::BI__sync_or_and_fetch_2:
1726 case Builtin::BI__sync_or_and_fetch_4:
1727 case Builtin::BI__sync_or_and_fetch_8:
1728 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001729 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00001730 break;
1731
1732 case Builtin::BI__sync_xor_and_fetch:
1733 case Builtin::BI__sync_xor_and_fetch_1:
1734 case Builtin::BI__sync_xor_and_fetch_2:
1735 case Builtin::BI__sync_xor_and_fetch_4:
1736 case Builtin::BI__sync_xor_and_fetch_8:
1737 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001738 BuiltinIndex = 10;
1739 break;
1740
1741 case Builtin::BI__sync_nand_and_fetch:
1742 case Builtin::BI__sync_nand_and_fetch_1:
1743 case Builtin::BI__sync_nand_and_fetch_2:
1744 case Builtin::BI__sync_nand_and_fetch_4:
1745 case Builtin::BI__sync_nand_and_fetch_8:
1746 case Builtin::BI__sync_nand_and_fetch_16:
1747 BuiltinIndex = 11;
1748 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00001749 break;
Mike Stump11289f42009-09-09 15:08:12 +00001750
Chris Lattnerdc046542009-05-08 06:58:22 +00001751 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001752 case Builtin::BI__sync_val_compare_and_swap_1:
1753 case Builtin::BI__sync_val_compare_and_swap_2:
1754 case Builtin::BI__sync_val_compare_and_swap_4:
1755 case Builtin::BI__sync_val_compare_and_swap_8:
1756 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001757 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00001758 NumFixed = 2;
1759 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001760
Chris Lattnerdc046542009-05-08 06:58:22 +00001761 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001762 case Builtin::BI__sync_bool_compare_and_swap_1:
1763 case Builtin::BI__sync_bool_compare_and_swap_2:
1764 case Builtin::BI__sync_bool_compare_and_swap_4:
1765 case Builtin::BI__sync_bool_compare_and_swap_8:
1766 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001767 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001768 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001769 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001770 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001771
1772 case Builtin::BI__sync_lock_test_and_set:
1773 case Builtin::BI__sync_lock_test_and_set_1:
1774 case Builtin::BI__sync_lock_test_and_set_2:
1775 case Builtin::BI__sync_lock_test_and_set_4:
1776 case Builtin::BI__sync_lock_test_and_set_8:
1777 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001778 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00001779 break;
1780
Chris Lattnerdc046542009-05-08 06:58:22 +00001781 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001782 case Builtin::BI__sync_lock_release_1:
1783 case Builtin::BI__sync_lock_release_2:
1784 case Builtin::BI__sync_lock_release_4:
1785 case Builtin::BI__sync_lock_release_8:
1786 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001787 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00001788 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001789 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001790 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001791
1792 case Builtin::BI__sync_swap:
1793 case Builtin::BI__sync_swap_1:
1794 case Builtin::BI__sync_swap_2:
1795 case Builtin::BI__sync_swap_4:
1796 case Builtin::BI__sync_swap_8:
1797 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001798 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00001799 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001800 }
Mike Stump11289f42009-09-09 15:08:12 +00001801
Chris Lattnerdc046542009-05-08 06:58:22 +00001802 // Now that we know how many fixed arguments we expect, first check that we
1803 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001804 if (TheCall->getNumArgs() < 1+NumFixed) {
1805 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1806 << 0 << 1+NumFixed << TheCall->getNumArgs()
1807 << TheCall->getCallee()->getSourceRange();
1808 return ExprError();
1809 }
Mike Stump11289f42009-09-09 15:08:12 +00001810
Hal Finkeld2208b52014-10-02 20:53:50 +00001811 if (WarnAboutSemanticsChange) {
1812 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1813 << TheCall->getCallee()->getSourceRange();
1814 }
1815
Chris Lattner5b9241b2009-05-08 15:36:58 +00001816 // Get the decl for the concrete builtin from this, we can tell what the
1817 // concrete integer type we should convert to is.
1818 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1819 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001820 FunctionDecl *NewBuiltinDecl;
1821 if (NewBuiltinID == BuiltinID)
1822 NewBuiltinDecl = FDecl;
1823 else {
1824 // Perform builtin lookup to avoid redeclaring it.
1825 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1826 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1827 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1828 assert(Res.getFoundDecl());
1829 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001830 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001831 return ExprError();
1832 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001833
John McCallcf142162010-08-07 06:22:56 +00001834 // The first argument --- the pointer --- has a fixed type; we
1835 // deduce the types of the rest of the arguments accordingly. Walk
1836 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001837 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001838 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001839
Chris Lattnerdc046542009-05-08 06:58:22 +00001840 // GCC does an implicit conversion to the pointer or integer ValType. This
1841 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001842 // Initialize the argument.
1843 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1844 ValType, /*consume*/ false);
1845 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001846 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001847 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001848
Chris Lattnerdc046542009-05-08 06:58:22 +00001849 // Okay, we have something that *can* be converted to the right type. Check
1850 // to see if there is a potentially weird extension going on here. This can
1851 // happen when you do an atomic operation on something like an char* and
1852 // pass in 42. The 42 gets converted to char. This is even more strange
1853 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001854 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001855 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001856 }
Mike Stump11289f42009-09-09 15:08:12 +00001857
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001858 ASTContext& Context = this->getASTContext();
1859
1860 // Create a new DeclRefExpr to refer to the new decl.
1861 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1862 Context,
1863 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001864 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001865 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001866 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001867 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001868 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001869 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001870
Chris Lattnerdc046542009-05-08 06:58:22 +00001871 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001872 // FIXME: This loses syntactic information.
1873 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1874 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1875 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001876 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001877
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001878 // Change the result type of the call to match the original value type. This
1879 // is arbitrary, but the codegen for these builtins ins design to handle it
1880 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001881 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001882
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001883 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001884}
1885
Chris Lattner6436fb62009-02-18 06:01:06 +00001886/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001887/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001888/// Note: It might also make sense to do the UTF-16 conversion here (would
1889/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001890bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001891 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001892 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1893
Douglas Gregorfb65e592011-07-27 05:40:30 +00001894 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001895 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1896 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001897 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001898 }
Mike Stump11289f42009-09-09 15:08:12 +00001899
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001900 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001901 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001902 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001903 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001904 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001905 UTF16 *ToPtr = &ToBuf[0];
1906
1907 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1908 &ToPtr, ToPtr + NumBytes,
1909 strictConversion);
1910 // Check for conversion failure.
1911 if (Result != conversionOK)
1912 Diag(Arg->getLocStart(),
1913 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1914 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001915 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001916}
1917
Chris Lattnere202e6a2007-12-20 00:05:45 +00001918/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1919/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001920bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1921 Expr *Fn = TheCall->getCallee();
1922 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001923 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001924 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001925 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1926 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001927 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001928 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001929 return true;
1930 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001931
1932 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001933 return Diag(TheCall->getLocEnd(),
1934 diag::err_typecheck_call_too_few_args_at_least)
1935 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001936 }
1937
John McCall29ad95b2011-08-27 01:09:30 +00001938 // Type-check the first argument normally.
1939 if (checkBuiltinArgument(*this, TheCall, 0))
1940 return true;
1941
Chris Lattnere202e6a2007-12-20 00:05:45 +00001942 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001943 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001944 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001945 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001946 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001947 else if (FunctionDecl *FD = getCurFunctionDecl())
1948 isVariadic = FD->isVariadic();
1949 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001950 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001951
Chris Lattnere202e6a2007-12-20 00:05:45 +00001952 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001953 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1954 return true;
1955 }
Mike Stump11289f42009-09-09 15:08:12 +00001956
Chris Lattner43be2e62007-12-19 23:59:04 +00001957 // Verify that the second argument to the builtin is the last argument of the
1958 // current function or method.
1959 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001960 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001961
Nico Weber9eea7642013-05-24 23:31:57 +00001962 // These are valid if SecondArgIsLastNamedArgument is false after the next
1963 // block.
1964 QualType Type;
1965 SourceLocation ParamLoc;
1966
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001967 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1968 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001969 // FIXME: This isn't correct for methods (results in bogus warning).
1970 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001971 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001972 if (CurBlock)
1973 LastArg = *(CurBlock->TheDecl->param_end()-1);
1974 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001975 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001976 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001977 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001978 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001979
1980 Type = PV->getType();
1981 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001982 }
1983 }
Mike Stump11289f42009-09-09 15:08:12 +00001984
Chris Lattner43be2e62007-12-19 23:59:04 +00001985 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001986 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001987 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001988 else if (Type->isReferenceType()) {
1989 Diag(Arg->getLocStart(),
1990 diag::warn_va_start_of_reference_type_is_undefined);
1991 Diag(ParamLoc, diag::note_parameter_type) << Type;
1992 }
1993
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001994 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001995 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001996}
Chris Lattner43be2e62007-12-19 23:59:04 +00001997
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00001998bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
1999 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2000 // const char *named_addr);
2001
2002 Expr *Func = Call->getCallee();
2003
2004 if (Call->getNumArgs() < 3)
2005 return Diag(Call->getLocEnd(),
2006 diag::err_typecheck_call_too_few_args_at_least)
2007 << 0 /*function call*/ << 3 << Call->getNumArgs();
2008
2009 // Determine whether the current function is variadic or not.
2010 bool IsVariadic;
2011 if (BlockScopeInfo *CurBlock = getCurBlock())
2012 IsVariadic = CurBlock->TheDecl->isVariadic();
2013 else if (FunctionDecl *FD = getCurFunctionDecl())
2014 IsVariadic = FD->isVariadic();
2015 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2016 IsVariadic = MD->isVariadic();
2017 else
2018 llvm_unreachable("unexpected statement type");
2019
2020 if (!IsVariadic) {
2021 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2022 return true;
2023 }
2024
2025 // Type-check the first argument normally.
2026 if (checkBuiltinArgument(*this, Call, 0))
2027 return true;
2028
2029 static const struct {
2030 unsigned ArgNo;
2031 QualType Type;
2032 } ArgumentTypes[] = {
2033 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2034 { 2, Context.getSizeType() },
2035 };
2036
2037 for (const auto &AT : ArgumentTypes) {
2038 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2039 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2040 continue;
2041 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2042 << Arg->getType() << AT.Type << 1 /* different class */
2043 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2044 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2045 }
2046
2047 return false;
2048}
2049
Chris Lattner2da14fb2007-12-20 00:26:33 +00002050/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2051/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002052bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2053 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002054 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002055 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002056 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002057 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002058 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002059 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002060 << SourceRange(TheCall->getArg(2)->getLocStart(),
2061 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002062
John Wiegley01296292011-04-08 18:41:53 +00002063 ExprResult OrigArg0 = TheCall->getArg(0);
2064 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002065
Chris Lattner2da14fb2007-12-20 00:26:33 +00002066 // Do standard promotions between the two arguments, returning their common
2067 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002068 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002069 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2070 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002071
2072 // Make sure any conversions are pushed back into the call; this is
2073 // type safe since unordered compare builtins are declared as "_Bool
2074 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002075 TheCall->setArg(0, OrigArg0.get());
2076 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002077
John Wiegley01296292011-04-08 18:41:53 +00002078 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002079 return false;
2080
Chris Lattner2da14fb2007-12-20 00:26:33 +00002081 // If the common type isn't a real floating type, then the arguments were
2082 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002083 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002084 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002085 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002086 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2087 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002088
Chris Lattner2da14fb2007-12-20 00:26:33 +00002089 return false;
2090}
2091
Benjamin Kramer634fc102010-02-15 22:42:31 +00002092/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2093/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002094/// to check everything. We expect the last argument to be a floating point
2095/// value.
2096bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2097 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002098 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002099 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002100 if (TheCall->getNumArgs() > NumArgs)
2101 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002102 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002103 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002104 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002105 (*(TheCall->arg_end()-1))->getLocEnd());
2106
Benjamin Kramer64aae502010-02-16 10:07:31 +00002107 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002108
Eli Friedman7e4faac2009-08-31 20:06:00 +00002109 if (OrigArg->isTypeDependent())
2110 return false;
2111
Chris Lattner68784ef2010-05-06 05:50:07 +00002112 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002113 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002114 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002115 diag::err_typecheck_call_invalid_unary_fp)
2116 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002117
Chris Lattner68784ef2010-05-06 05:50:07 +00002118 // If this is an implicit conversion from float -> double, remove it.
2119 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2120 Expr *CastArg = Cast->getSubExpr();
2121 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2122 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2123 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002124 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002125 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002126 }
2127 }
2128
Eli Friedman7e4faac2009-08-31 20:06:00 +00002129 return false;
2130}
2131
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002132/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2133// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002134ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002135 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002136 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002137 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002138 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2139 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002140
Nate Begemana0110022010-06-08 00:16:34 +00002141 // Determine which of the following types of shufflevector we're checking:
2142 // 1) unary, vector mask: (lhs, mask)
2143 // 2) binary, vector mask: (lhs, rhs, mask)
2144 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2145 QualType resType = TheCall->getArg(0)->getType();
2146 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002147
Douglas Gregorc25f7662009-05-19 22:10:17 +00002148 if (!TheCall->getArg(0)->isTypeDependent() &&
2149 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002150 QualType LHSType = TheCall->getArg(0)->getType();
2151 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002152
Craig Topperbaca3892013-07-29 06:47:04 +00002153 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2154 return ExprError(Diag(TheCall->getLocStart(),
2155 diag::err_shufflevector_non_vector)
2156 << SourceRange(TheCall->getArg(0)->getLocStart(),
2157 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002158
Nate Begemana0110022010-06-08 00:16:34 +00002159 numElements = LHSType->getAs<VectorType>()->getNumElements();
2160 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002161
Nate Begemana0110022010-06-08 00:16:34 +00002162 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2163 // with mask. If so, verify that RHS is an integer vector type with the
2164 // same number of elts as lhs.
2165 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002166 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002167 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002168 return ExprError(Diag(TheCall->getLocStart(),
2169 diag::err_shufflevector_incompatible_vector)
2170 << SourceRange(TheCall->getArg(1)->getLocStart(),
2171 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002172 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002173 return ExprError(Diag(TheCall->getLocStart(),
2174 diag::err_shufflevector_incompatible_vector)
2175 << SourceRange(TheCall->getArg(0)->getLocStart(),
2176 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002177 } else if (numElements != numResElements) {
2178 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002179 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002180 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002181 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002182 }
2183
2184 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002185 if (TheCall->getArg(i)->isTypeDependent() ||
2186 TheCall->getArg(i)->isValueDependent())
2187 continue;
2188
Nate Begemana0110022010-06-08 00:16:34 +00002189 llvm::APSInt Result(32);
2190 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2191 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002192 diag::err_shufflevector_nonconstant_argument)
2193 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002194
Craig Topper50ad5b72013-08-03 17:40:38 +00002195 // Allow -1 which will be translated to undef in the IR.
2196 if (Result.isSigned() && Result.isAllOnesValue())
2197 continue;
2198
Chris Lattner7ab824e2008-08-10 02:05:13 +00002199 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002200 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002201 diag::err_shufflevector_argument_too_large)
2202 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002203 }
2204
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002205 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002206
Chris Lattner7ab824e2008-08-10 02:05:13 +00002207 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002208 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002209 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002210 }
2211
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002212 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2213 TheCall->getCallee()->getLocStart(),
2214 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002215}
Chris Lattner43be2e62007-12-19 23:59:04 +00002216
Hal Finkelc4d7c822013-09-18 03:29:45 +00002217/// SemaConvertVectorExpr - Handle __builtin_convertvector
2218ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2219 SourceLocation BuiltinLoc,
2220 SourceLocation RParenLoc) {
2221 ExprValueKind VK = VK_RValue;
2222 ExprObjectKind OK = OK_Ordinary;
2223 QualType DstTy = TInfo->getType();
2224 QualType SrcTy = E->getType();
2225
2226 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2227 return ExprError(Diag(BuiltinLoc,
2228 diag::err_convertvector_non_vector)
2229 << E->getSourceRange());
2230 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2231 return ExprError(Diag(BuiltinLoc,
2232 diag::err_convertvector_non_vector_type));
2233
2234 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2235 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2236 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2237 if (SrcElts != DstElts)
2238 return ExprError(Diag(BuiltinLoc,
2239 diag::err_convertvector_incompatible_vector)
2240 << E->getSourceRange());
2241 }
2242
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002243 return new (Context)
2244 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002245}
2246
Daniel Dunbarb7257262008-07-21 22:59:13 +00002247/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2248// This is declared to take (const void*, ...) and can take two
2249// optional constant int args.
2250bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002251 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002252
Chris Lattner3b054132008-11-19 05:08:23 +00002253 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002254 return Diag(TheCall->getLocEnd(),
2255 diag::err_typecheck_call_too_many_args_at_most)
2256 << 0 /*function call*/ << 3 << NumArgs
2257 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002258
2259 // Argument 0 is checked for us and the remaining arguments must be
2260 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002261 for (unsigned i = 1; i != NumArgs; ++i)
2262 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002263 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002264
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002265 return false;
2266}
2267
Hal Finkelf0417332014-07-17 14:25:55 +00002268/// SemaBuiltinAssume - Handle __assume (MS Extension).
2269// __assume does not evaluate its arguments, and should warn if its argument
2270// has side effects.
2271bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2272 Expr *Arg = TheCall->getArg(0);
2273 if (Arg->isInstantiationDependent()) return false;
2274
2275 if (Arg->HasSideEffects(Context))
2276 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002277 << Arg->getSourceRange()
2278 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2279
2280 return false;
2281}
2282
2283/// Handle __builtin_assume_aligned. This is declared
2284/// as (const void*, size_t, ...) and can take one optional constant int arg.
2285bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2286 unsigned NumArgs = TheCall->getNumArgs();
2287
2288 if (NumArgs > 3)
2289 return Diag(TheCall->getLocEnd(),
2290 diag::err_typecheck_call_too_many_args_at_most)
2291 << 0 /*function call*/ << 3 << NumArgs
2292 << TheCall->getSourceRange();
2293
2294 // The alignment must be a constant integer.
2295 Expr *Arg = TheCall->getArg(1);
2296
2297 // We can't check the value of a dependent argument.
2298 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2299 llvm::APSInt Result;
2300 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2301 return true;
2302
2303 if (!Result.isPowerOf2())
2304 return Diag(TheCall->getLocStart(),
2305 diag::err_alignment_not_power_of_two)
2306 << Arg->getSourceRange();
2307 }
2308
2309 if (NumArgs > 2) {
2310 ExprResult Arg(TheCall->getArg(2));
2311 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2312 Context.getSizeType(), false);
2313 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2314 if (Arg.isInvalid()) return true;
2315 TheCall->setArg(2, Arg.get());
2316 }
Hal Finkelf0417332014-07-17 14:25:55 +00002317
2318 return false;
2319}
2320
Eric Christopher8d0c6212010-04-17 02:26:23 +00002321/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2322/// TheCall is a constant expression.
2323bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2324 llvm::APSInt &Result) {
2325 Expr *Arg = TheCall->getArg(ArgNum);
2326 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2327 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2328
2329 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2330
2331 if (!Arg->isIntegerConstantExpr(Result, Context))
2332 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002333 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002334
Chris Lattnerd545ad12009-09-23 06:06:36 +00002335 return false;
2336}
2337
Richard Sandiford28940af2014-04-16 08:47:51 +00002338/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2339/// TheCall is a constant expression in the range [Low, High].
2340bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2341 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002342 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002343
2344 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002345 Expr *Arg = TheCall->getArg(ArgNum);
2346 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002347 return false;
2348
Eric Christopher8d0c6212010-04-17 02:26:23 +00002349 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002350 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002351 return true;
2352
Richard Sandiford28940af2014-04-16 08:47:51 +00002353 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002354 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002355 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002356
2357 return false;
2358}
2359
Eli Friedmanc97d0142009-05-03 06:04:26 +00002360/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002361/// This checks that val is a constant 1.
2362bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2363 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002364 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002365
Eric Christopher8d0c6212010-04-17 02:26:23 +00002366 // TODO: This is less than ideal. Overload this to take a value.
2367 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2368 return true;
2369
2370 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002371 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2372 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2373
2374 return false;
2375}
2376
Richard Smithd7293d72013-08-05 18:49:43 +00002377namespace {
2378enum StringLiteralCheckType {
2379 SLCT_NotALiteral,
2380 SLCT_UncheckedLiteral,
2381 SLCT_CheckedLiteral
2382};
2383}
2384
Richard Smith55ce3522012-06-25 20:30:08 +00002385// Determine if an expression is a string literal or constant string.
2386// If this function returns false on the arguments to a function expecting a
2387// format string, we will usually need to emit a warning.
2388// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002389static StringLiteralCheckType
2390checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2391 bool HasVAListArg, unsigned format_idx,
2392 unsigned firstDataArg, Sema::FormatStringType Type,
2393 Sema::VariadicCallType CallType, bool InFunctionCall,
2394 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002395 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002396 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002397 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002398
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002399 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002400
Richard Smithd7293d72013-08-05 18:49:43 +00002401 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002402 // Technically -Wformat-nonliteral does not warn about this case.
2403 // The behavior of printf and friends in this case is implementation
2404 // dependent. Ideally if the format string cannot be null then
2405 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002406 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002407
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002408 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002409 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002410 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002411 // The expression is a literal if both sub-expressions were, and it was
2412 // completely checked only if both sub-expressions were checked.
2413 const AbstractConditionalOperator *C =
2414 cast<AbstractConditionalOperator>(E);
2415 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002416 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002417 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002418 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002419 if (Left == SLCT_NotALiteral)
2420 return SLCT_NotALiteral;
2421 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002422 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002423 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002424 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002425 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002426 }
2427
2428 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002429 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2430 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002431 }
2432
John McCallc07a0c72011-02-17 10:25:35 +00002433 case Stmt::OpaqueValueExprClass:
2434 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2435 E = src;
2436 goto tryAgain;
2437 }
Richard Smith55ce3522012-06-25 20:30:08 +00002438 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002439
Ted Kremeneka8890832011-02-24 23:03:04 +00002440 case Stmt::PredefinedExprClass:
2441 // While __func__, etc., are technically not string literals, they
2442 // cannot contain format specifiers and thus are not a security
2443 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002444 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002445
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002446 case Stmt::DeclRefExprClass: {
2447 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002448
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002449 // As an exception, do not flag errors for variables binding to
2450 // const string literals.
2451 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2452 bool isConstant = false;
2453 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002454
Richard Smithd7293d72013-08-05 18:49:43 +00002455 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2456 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002457 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002458 isConstant = T.isConstant(S.Context) &&
2459 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002460 } else if (T->isObjCObjectPointerType()) {
2461 // In ObjC, there is usually no "const ObjectPointer" type,
2462 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002463 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002464 }
Mike Stump11289f42009-09-09 15:08:12 +00002465
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002466 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002467 if (const Expr *Init = VD->getAnyInitializer()) {
2468 // Look through initializers like const char c[] = { "foo" }
2469 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2470 if (InitList->isStringLiteralInit())
2471 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2472 }
Richard Smithd7293d72013-08-05 18:49:43 +00002473 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002474 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002475 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002476 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002477 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002478 }
Mike Stump11289f42009-09-09 15:08:12 +00002479
Anders Carlssonb012ca92009-06-28 19:55:58 +00002480 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2481 // special check to see if the format string is a function parameter
2482 // of the function calling the printf function. If the function
2483 // has an attribute indicating it is a printf-like function, then we
2484 // should suppress warnings concerning non-literals being used in a call
2485 // to a vprintf function. For example:
2486 //
2487 // void
2488 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2489 // va_list ap;
2490 // va_start(ap, fmt);
2491 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2492 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002493 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002494 if (HasVAListArg) {
2495 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2496 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2497 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002498 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002499 // adjust for implicit parameter
2500 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2501 if (MD->isInstance())
2502 ++PVIndex;
2503 // We also check if the formats are compatible.
2504 // We can't pass a 'scanf' string to a 'printf' function.
2505 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002506 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002507 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002508 }
2509 }
2510 }
2511 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002512 }
Mike Stump11289f42009-09-09 15:08:12 +00002513
Richard Smith55ce3522012-06-25 20:30:08 +00002514 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002515 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002516
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002517 case Stmt::CallExprClass:
2518 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002519 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002520 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2521 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2522 unsigned ArgIndex = FA->getFormatIdx();
2523 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2524 if (MD->isInstance())
2525 --ArgIndex;
2526 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002527
Richard Smithd7293d72013-08-05 18:49:43 +00002528 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002529 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002530 Type, CallType, InFunctionCall,
2531 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002532 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2533 unsigned BuiltinID = FD->getBuiltinID();
2534 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2535 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2536 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002537 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002538 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002539 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002540 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002541 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002542 }
2543 }
Mike Stump11289f42009-09-09 15:08:12 +00002544
Richard Smith55ce3522012-06-25 20:30:08 +00002545 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002546 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002547 case Stmt::ObjCStringLiteralClass:
2548 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002549 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002550
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002551 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002552 StrE = ObjCFExpr->getString();
2553 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002554 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002555
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002556 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002557 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2558 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002559 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002560 }
Mike Stump11289f42009-09-09 15:08:12 +00002561
Richard Smith55ce3522012-06-25 20:30:08 +00002562 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002563 }
Mike Stump11289f42009-09-09 15:08:12 +00002564
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002565 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002566 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002567 }
2568}
2569
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002570Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002571 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002572 .Case("scanf", FST_Scanf)
2573 .Cases("printf", "printf0", FST_Printf)
2574 .Cases("NSString", "CFString", FST_NSString)
2575 .Case("strftime", FST_Strftime)
2576 .Case("strfmon", FST_Strfmon)
2577 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2578 .Default(FST_Unknown);
2579}
2580
Jordan Rose3e0ec582012-07-19 18:10:23 +00002581/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002582/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002583/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002584bool Sema::CheckFormatArguments(const FormatAttr *Format,
2585 ArrayRef<const Expr *> Args,
2586 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002587 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002588 SourceLocation Loc, SourceRange Range,
2589 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002590 FormatStringInfo FSI;
2591 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002592 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002593 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002594 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002595 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002596}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002597
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002598bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002599 bool HasVAListArg, unsigned format_idx,
2600 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002601 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002602 SourceLocation Loc, SourceRange Range,
2603 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002604 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002605 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002606 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002607 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002608 }
Mike Stump11289f42009-09-09 15:08:12 +00002609
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002610 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002611
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002612 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002613 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002614 // Dynamically generated format strings are difficult to
2615 // automatically vet at compile time. Requiring that format strings
2616 // are string literals: (1) permits the checking of format strings by
2617 // the compiler and thereby (2) can practically remove the source of
2618 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002619
Mike Stump11289f42009-09-09 15:08:12 +00002620 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002621 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002622 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002623 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002624 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002625 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2626 format_idx, firstDataArg, Type, CallType,
2627 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002628 if (CT != SLCT_NotALiteral)
2629 // Literal format string found, check done!
2630 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002631
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002632 // Strftime is particular as it always uses a single 'time' argument,
2633 // so it is safe to pass a non-literal string.
2634 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002635 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002636
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002637 // Do not emit diag when the string param is a macro expansion and the
2638 // format is either NSString or CFString. This is a hack to prevent
2639 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2640 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002641 if (Type == FST_NSString &&
2642 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002643 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002644
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002645 // If there are no arguments specified, warn with -Wformat-security, otherwise
2646 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002647 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002648 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002649 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002650 << OrigFormatExpr->getSourceRange();
2651 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002652 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002653 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002654 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002655 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002656}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002657
Ted Kremenekab278de2010-01-28 23:39:18 +00002658namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002659class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2660protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002661 Sema &S;
2662 const StringLiteral *FExpr;
2663 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002664 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002665 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002666 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002667 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002668 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002669 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002670 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002671 bool usesPositionalArgs;
2672 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002673 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002674 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002675 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002676public:
Ted Kremenek02087932010-07-16 02:11:22 +00002677 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002678 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002679 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002680 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002681 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002682 Sema::VariadicCallType callType,
2683 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002684 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002685 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2686 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002687 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002688 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002689 inFunctionCall(inFunctionCall), CallType(callType),
2690 CheckedVarArgs(CheckedVarArgs) {
2691 CoveredArgs.resize(numDataArgs);
2692 CoveredArgs.reset();
2693 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002694
Ted Kremenek019d2242010-01-29 01:50:07 +00002695 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002696
Ted Kremenek02087932010-07-16 02:11:22 +00002697 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002698 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002699
Jordan Rose92303592012-09-08 04:00:03 +00002700 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002701 const analyze_format_string::FormatSpecifier &FS,
2702 const analyze_format_string::ConversionSpecifier &CS,
2703 const char *startSpecifier, unsigned specifierLen,
2704 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002705
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002706 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002707 const analyze_format_string::FormatSpecifier &FS,
2708 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002709
2710 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002711 const analyze_format_string::ConversionSpecifier &CS,
2712 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002713
Craig Toppere14c0f82014-03-12 04:55:44 +00002714 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002715
Craig Toppere14c0f82014-03-12 04:55:44 +00002716 void HandleInvalidPosition(const char *startSpecifier,
2717 unsigned specifierLen,
2718 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002719
Craig Toppere14c0f82014-03-12 04:55:44 +00002720 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002721
Craig Toppere14c0f82014-03-12 04:55:44 +00002722 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002723
Richard Trieu03cf7b72011-10-28 00:41:25 +00002724 template <typename Range>
2725 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2726 const Expr *ArgumentExpr,
2727 PartialDiagnostic PDiag,
2728 SourceLocation StringLoc,
2729 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002730 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002731
Ted Kremenek02087932010-07-16 02:11:22 +00002732protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002733 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2734 const char *startSpec,
2735 unsigned specifierLen,
2736 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002737
2738 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2739 const char *startSpec,
2740 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002741
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002742 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002743 CharSourceRange getSpecifierRange(const char *startSpecifier,
2744 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002745 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002746
Ted Kremenek5739de72010-01-29 01:06:55 +00002747 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002748
2749 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2750 const analyze_format_string::ConversionSpecifier &CS,
2751 const char *startSpecifier, unsigned specifierLen,
2752 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002753
2754 template <typename Range>
2755 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2756 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002757 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002758};
2759}
2760
Ted Kremenek02087932010-07-16 02:11:22 +00002761SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002762 return OrigFormatExpr->getSourceRange();
2763}
2764
Ted Kremenek02087932010-07-16 02:11:22 +00002765CharSourceRange CheckFormatHandler::
2766getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002767 SourceLocation Start = getLocationOfByte(startSpecifier);
2768 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2769
2770 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002771 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002772
2773 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002774}
2775
Ted Kremenek02087932010-07-16 02:11:22 +00002776SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002777 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002778}
2779
Ted Kremenek02087932010-07-16 02:11:22 +00002780void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2781 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002782 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2783 getLocationOfByte(startSpecifier),
2784 /*IsStringLocation*/true,
2785 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002786}
2787
Jordan Rose92303592012-09-08 04:00:03 +00002788void CheckFormatHandler::HandleInvalidLengthModifier(
2789 const analyze_format_string::FormatSpecifier &FS,
2790 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002791 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002792 using namespace analyze_format_string;
2793
2794 const LengthModifier &LM = FS.getLengthModifier();
2795 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2796
2797 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002798 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002799 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002800 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002801 getLocationOfByte(LM.getStart()),
2802 /*IsStringLocation*/true,
2803 getSpecifierRange(startSpecifier, specifierLen));
2804
2805 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2806 << FixedLM->toString()
2807 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2808
2809 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002810 FixItHint Hint;
2811 if (DiagID == diag::warn_format_nonsensical_length)
2812 Hint = FixItHint::CreateRemoval(LMRange);
2813
2814 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002815 getLocationOfByte(LM.getStart()),
2816 /*IsStringLocation*/true,
2817 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002818 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002819 }
2820}
2821
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002822void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002823 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002824 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002825 using namespace analyze_format_string;
2826
2827 const LengthModifier &LM = FS.getLengthModifier();
2828 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2829
2830 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002831 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002832 if (FixedLM) {
2833 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2834 << LM.toString() << 0,
2835 getLocationOfByte(LM.getStart()),
2836 /*IsStringLocation*/true,
2837 getSpecifierRange(startSpecifier, specifierLen));
2838
2839 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2840 << FixedLM->toString()
2841 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2842
2843 } else {
2844 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2845 << LM.toString() << 0,
2846 getLocationOfByte(LM.getStart()),
2847 /*IsStringLocation*/true,
2848 getSpecifierRange(startSpecifier, specifierLen));
2849 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002850}
2851
2852void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2853 const analyze_format_string::ConversionSpecifier &CS,
2854 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002855 using namespace analyze_format_string;
2856
2857 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002858 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002859 if (FixedCS) {
2860 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2861 << CS.toString() << /*conversion specifier*/1,
2862 getLocationOfByte(CS.getStart()),
2863 /*IsStringLocation*/true,
2864 getSpecifierRange(startSpecifier, specifierLen));
2865
2866 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2867 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2868 << FixedCS->toString()
2869 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2870 } else {
2871 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2872 << CS.toString() << /*conversion specifier*/1,
2873 getLocationOfByte(CS.getStart()),
2874 /*IsStringLocation*/true,
2875 getSpecifierRange(startSpecifier, specifierLen));
2876 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002877}
2878
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002879void CheckFormatHandler::HandlePosition(const char *startPos,
2880 unsigned posLen) {
2881 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2882 getLocationOfByte(startPos),
2883 /*IsStringLocation*/true,
2884 getSpecifierRange(startPos, posLen));
2885}
2886
Ted Kremenekd1668192010-02-27 01:41:03 +00002887void
Ted Kremenek02087932010-07-16 02:11:22 +00002888CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2889 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002890 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2891 << (unsigned) p,
2892 getLocationOfByte(startPos), /*IsStringLocation*/true,
2893 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002894}
2895
Ted Kremenek02087932010-07-16 02:11:22 +00002896void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002897 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002898 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2899 getLocationOfByte(startPos),
2900 /*IsStringLocation*/true,
2901 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002902}
2903
Ted Kremenek02087932010-07-16 02:11:22 +00002904void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002905 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002906 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002907 EmitFormatDiagnostic(
2908 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2909 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2910 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002911 }
Ted Kremenek02087932010-07-16 02:11:22 +00002912}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002913
Jordan Rose58bbe422012-07-19 18:10:08 +00002914// Note that this may return NULL if there was an error parsing or building
2915// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002916const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002917 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002918}
2919
2920void CheckFormatHandler::DoneProcessing() {
2921 // Does the number of data arguments exceed the number of
2922 // format conversions in the format string?
2923 if (!HasVAListArg) {
2924 // Find any arguments that weren't covered.
2925 CoveredArgs.flip();
2926 signed notCoveredArg = CoveredArgs.find_first();
2927 if (notCoveredArg >= 0) {
2928 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002929 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2930 SourceLocation Loc = E->getLocStart();
2931 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2932 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2933 Loc, /*IsStringLocation*/false,
2934 getFormatStringRange());
2935 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002936 }
Ted Kremenek02087932010-07-16 02:11:22 +00002937 }
2938 }
2939}
2940
Ted Kremenekce815422010-07-19 21:25:57 +00002941bool
2942CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2943 SourceLocation Loc,
2944 const char *startSpec,
2945 unsigned specifierLen,
2946 const char *csStart,
2947 unsigned csLen) {
2948
2949 bool keepGoing = true;
2950 if (argIndex < NumDataArgs) {
2951 // Consider the argument coverered, even though the specifier doesn't
2952 // make sense.
2953 CoveredArgs.set(argIndex);
2954 }
2955 else {
2956 // If argIndex exceeds the number of data arguments we
2957 // don't issue a warning because that is just a cascade of warnings (and
2958 // they may have intended '%%' anyway). We don't want to continue processing
2959 // the format string after this point, however, as we will like just get
2960 // gibberish when trying to match arguments.
2961 keepGoing = false;
2962 }
2963
Richard Trieu03cf7b72011-10-28 00:41:25 +00002964 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2965 << StringRef(csStart, csLen),
2966 Loc, /*IsStringLocation*/true,
2967 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002968
2969 return keepGoing;
2970}
2971
Richard Trieu03cf7b72011-10-28 00:41:25 +00002972void
2973CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2974 const char *startSpec,
2975 unsigned specifierLen) {
2976 EmitFormatDiagnostic(
2977 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2978 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2979}
2980
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002981bool
2982CheckFormatHandler::CheckNumArgs(
2983 const analyze_format_string::FormatSpecifier &FS,
2984 const analyze_format_string::ConversionSpecifier &CS,
2985 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2986
2987 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002988 PartialDiagnostic PDiag = FS.usesPositionalArg()
2989 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2990 << (argIndex+1) << NumDataArgs)
2991 : S.PDiag(diag::warn_printf_insufficient_data_args);
2992 EmitFormatDiagnostic(
2993 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2994 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002995 return false;
2996 }
2997 return true;
2998}
2999
Richard Trieu03cf7b72011-10-28 00:41:25 +00003000template<typename Range>
3001void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3002 SourceLocation Loc,
3003 bool IsStringLocation,
3004 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003005 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003006 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003007 Loc, IsStringLocation, StringRange, FixIt);
3008}
3009
3010/// \brief If the format string is not within the funcion call, emit a note
3011/// so that the function call and string are in diagnostic messages.
3012///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003013/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003014/// call and only one diagnostic message will be produced. Otherwise, an
3015/// extra note will be emitted pointing to location of the format string.
3016///
3017/// \param ArgumentExpr the expression that is passed as the format string
3018/// argument in the function call. Used for getting locations when two
3019/// diagnostics are emitted.
3020///
3021/// \param PDiag the callee should already have provided any strings for the
3022/// diagnostic message. This function only adds locations and fixits
3023/// to diagnostics.
3024///
3025/// \param Loc primary location for diagnostic. If two diagnostics are
3026/// required, one will be at Loc and a new SourceLocation will be created for
3027/// the other one.
3028///
3029/// \param IsStringLocation if true, Loc points to the format string should be
3030/// used for the note. Otherwise, Loc points to the argument list and will
3031/// be used with PDiag.
3032///
3033/// \param StringRange some or all of the string to highlight. This is
3034/// templated so it can accept either a CharSourceRange or a SourceRange.
3035///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003036/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003037template<typename Range>
3038void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3039 const Expr *ArgumentExpr,
3040 PartialDiagnostic PDiag,
3041 SourceLocation Loc,
3042 bool IsStringLocation,
3043 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003044 ArrayRef<FixItHint> FixIt) {
3045 if (InFunctionCall) {
3046 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3047 D << StringRange;
3048 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3049 I != E; ++I) {
3050 D << *I;
3051 }
3052 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003053 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3054 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003055
3056 const Sema::SemaDiagnosticBuilder &Note =
3057 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3058 diag::note_format_string_defined);
3059
3060 Note << StringRange;
3061 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3062 I != E; ++I) {
3063 Note << *I;
3064 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00003065 }
3066}
3067
Ted Kremenek02087932010-07-16 02:11:22 +00003068//===--- CHECK: Printf format string checking ------------------------------===//
3069
3070namespace {
3071class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003072 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003073public:
3074 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3075 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003076 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003077 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003078 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003079 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003080 Sema::VariadicCallType CallType,
3081 llvm::SmallBitVector &CheckedVarArgs)
3082 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3083 numDataArgs, beg, hasVAListArg, Args,
3084 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3085 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003086 {}
3087
Craig Toppere14c0f82014-03-12 04:55:44 +00003088
Ted Kremenek02087932010-07-16 02:11:22 +00003089 bool HandleInvalidPrintfConversionSpecifier(
3090 const analyze_printf::PrintfSpecifier &FS,
3091 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003092 unsigned specifierLen) override;
3093
Ted Kremenek02087932010-07-16 02:11:22 +00003094 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3095 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003096 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003097 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3098 const char *StartSpecifier,
3099 unsigned SpecifierLen,
3100 const Expr *E);
3101
Ted Kremenek02087932010-07-16 02:11:22 +00003102 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3103 const char *startSpecifier, unsigned specifierLen);
3104 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3105 const analyze_printf::OptionalAmount &Amt,
3106 unsigned type,
3107 const char *startSpecifier, unsigned specifierLen);
3108 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3109 const analyze_printf::OptionalFlag &flag,
3110 const char *startSpecifier, unsigned specifierLen);
3111 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3112 const analyze_printf::OptionalFlag &ignoredFlag,
3113 const analyze_printf::OptionalFlag &flag,
3114 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003115 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003116 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003117
Ted Kremenek02087932010-07-16 02:11:22 +00003118};
3119}
3120
3121bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3122 const analyze_printf::PrintfSpecifier &FS,
3123 const char *startSpecifier,
3124 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003125 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003126 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003127
Ted Kremenekce815422010-07-19 21:25:57 +00003128 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3129 getLocationOfByte(CS.getStart()),
3130 startSpecifier, specifierLen,
3131 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003132}
3133
Ted Kremenek02087932010-07-16 02:11:22 +00003134bool CheckPrintfHandler::HandleAmount(
3135 const analyze_format_string::OptionalAmount &Amt,
3136 unsigned k, const char *startSpecifier,
3137 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003138
3139 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003140 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003141 unsigned argIndex = Amt.getArgIndex();
3142 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003143 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3144 << k,
3145 getLocationOfByte(Amt.getStart()),
3146 /*IsStringLocation*/true,
3147 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003148 // Don't do any more checking. We will just emit
3149 // spurious errors.
3150 return false;
3151 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003152
Ted Kremenek5739de72010-01-29 01:06:55 +00003153 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003154 // Although not in conformance with C99, we also allow the argument to be
3155 // an 'unsigned int' as that is a reasonably safe case. GCC also
3156 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003157 CoveredArgs.set(argIndex);
3158 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003159 if (!Arg)
3160 return false;
3161
Ted Kremenek5739de72010-01-29 01:06:55 +00003162 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003163
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003164 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3165 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003166
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003167 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003168 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003169 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003170 << T << Arg->getSourceRange(),
3171 getLocationOfByte(Amt.getStart()),
3172 /*IsStringLocation*/true,
3173 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003174 // Don't do any more checking. We will just emit
3175 // spurious errors.
3176 return false;
3177 }
3178 }
3179 }
3180 return true;
3181}
Ted Kremenek5739de72010-01-29 01:06:55 +00003182
Tom Careb49ec692010-06-17 19:00:27 +00003183void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003184 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003185 const analyze_printf::OptionalAmount &Amt,
3186 unsigned type,
3187 const char *startSpecifier,
3188 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003189 const analyze_printf::PrintfConversionSpecifier &CS =
3190 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003191
Richard Trieu03cf7b72011-10-28 00:41:25 +00003192 FixItHint fixit =
3193 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3194 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3195 Amt.getConstantLength()))
3196 : FixItHint();
3197
3198 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3199 << type << CS.toString(),
3200 getLocationOfByte(Amt.getStart()),
3201 /*IsStringLocation*/true,
3202 getSpecifierRange(startSpecifier, specifierLen),
3203 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003204}
3205
Ted Kremenek02087932010-07-16 02:11:22 +00003206void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003207 const analyze_printf::OptionalFlag &flag,
3208 const char *startSpecifier,
3209 unsigned specifierLen) {
3210 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003211 const analyze_printf::PrintfConversionSpecifier &CS =
3212 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003213 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3214 << flag.toString() << CS.toString(),
3215 getLocationOfByte(flag.getPosition()),
3216 /*IsStringLocation*/true,
3217 getSpecifierRange(startSpecifier, specifierLen),
3218 FixItHint::CreateRemoval(
3219 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003220}
3221
3222void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003223 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003224 const analyze_printf::OptionalFlag &ignoredFlag,
3225 const analyze_printf::OptionalFlag &flag,
3226 const char *startSpecifier,
3227 unsigned specifierLen) {
3228 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003229 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3230 << ignoredFlag.toString() << flag.toString(),
3231 getLocationOfByte(ignoredFlag.getPosition()),
3232 /*IsStringLocation*/true,
3233 getSpecifierRange(startSpecifier, specifierLen),
3234 FixItHint::CreateRemoval(
3235 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003236}
3237
Richard Smith55ce3522012-06-25 20:30:08 +00003238// Determines if the specified is a C++ class or struct containing
3239// a member with the specified name and kind (e.g. a CXXMethodDecl named
3240// "c_str()").
3241template<typename MemberKind>
3242static llvm::SmallPtrSet<MemberKind*, 1>
3243CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3244 const RecordType *RT = Ty->getAs<RecordType>();
3245 llvm::SmallPtrSet<MemberKind*, 1> Results;
3246
3247 if (!RT)
3248 return Results;
3249 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003250 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003251 return Results;
3252
Alp Tokerb6cc5922014-05-03 03:45:55 +00003253 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003254 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003255 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003256
3257 // We just need to include all members of the right kind turned up by the
3258 // filter, at this point.
3259 if (S.LookupQualifiedName(R, RT->getDecl()))
3260 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3261 NamedDecl *decl = (*I)->getUnderlyingDecl();
3262 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3263 Results.insert(FK);
3264 }
3265 return Results;
3266}
3267
Richard Smith2868a732014-02-28 01:36:39 +00003268/// Check if we could call '.c_str()' on an object.
3269///
3270/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3271/// allow the call, or if it would be ambiguous).
3272bool Sema::hasCStrMethod(const Expr *E) {
3273 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3274 MethodSet Results =
3275 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3276 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3277 MI != ME; ++MI)
3278 if ((*MI)->getMinRequiredArguments() == 0)
3279 return true;
3280 return false;
3281}
3282
Richard Smith55ce3522012-06-25 20:30:08 +00003283// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003284// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003285// Returns true when a c_str() conversion method is found.
3286bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003287 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003288 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3289
3290 MethodSet Results =
3291 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3292
3293 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3294 MI != ME; ++MI) {
3295 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003296 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003297 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003298 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003299 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003300 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3301 << "c_str()"
3302 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3303 return true;
3304 }
3305 }
3306
3307 return false;
3308}
3309
Ted Kremenekab278de2010-01-28 23:39:18 +00003310bool
Ted Kremenek02087932010-07-16 02:11:22 +00003311CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003312 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003313 const char *startSpecifier,
3314 unsigned specifierLen) {
3315
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003316 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003317 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003318 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003319
Ted Kremenek6cd69422010-07-19 22:01:06 +00003320 if (FS.consumesDataArgument()) {
3321 if (atFirstArg) {
3322 atFirstArg = false;
3323 usesPositionalArgs = FS.usesPositionalArg();
3324 }
3325 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003326 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3327 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003328 return false;
3329 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003330 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003331
Ted Kremenekd1668192010-02-27 01:41:03 +00003332 // First check if the field width, precision, and conversion specifier
3333 // have matching data arguments.
3334 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3335 startSpecifier, specifierLen)) {
3336 return false;
3337 }
3338
3339 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3340 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003341 return false;
3342 }
3343
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003344 if (!CS.consumesDataArgument()) {
3345 // FIXME: Technically specifying a precision or field width here
3346 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003347 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003348 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003349
Ted Kremenek4a49d982010-02-26 19:18:41 +00003350 // Consume the argument.
3351 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003352 if (argIndex < NumDataArgs) {
3353 // The check to see if the argIndex is valid will come later.
3354 // We set the bit here because we may exit early from this
3355 // function if we encounter some other error.
3356 CoveredArgs.set(argIndex);
3357 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003358
3359 // Check for using an Objective-C specific conversion specifier
3360 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003361 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003362 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3363 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003364 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003365
Tom Careb49ec692010-06-17 19:00:27 +00003366 // Check for invalid use of field width
3367 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003368 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003369 startSpecifier, specifierLen);
3370 }
3371
3372 // Check for invalid use of precision
3373 if (!FS.hasValidPrecision()) {
3374 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3375 startSpecifier, specifierLen);
3376 }
3377
3378 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003379 if (!FS.hasValidThousandsGroupingPrefix())
3380 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003381 if (!FS.hasValidLeadingZeros())
3382 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3383 if (!FS.hasValidPlusPrefix())
3384 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003385 if (!FS.hasValidSpacePrefix())
3386 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003387 if (!FS.hasValidAlternativeForm())
3388 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3389 if (!FS.hasValidLeftJustified())
3390 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3391
3392 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003393 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3394 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3395 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003396 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3397 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3398 startSpecifier, specifierLen);
3399
3400 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003401 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003402 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3403 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003404 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003405 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003406 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003407 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3408 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003409
Jordan Rose92303592012-09-08 04:00:03 +00003410 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3411 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3412
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003413 // The remaining checks depend on the data arguments.
3414 if (HasVAListArg)
3415 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003416
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003417 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003418 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003419
Jordan Rose58bbe422012-07-19 18:10:08 +00003420 const Expr *Arg = getDataArg(argIndex);
3421 if (!Arg)
3422 return true;
3423
3424 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003425}
3426
Jordan Roseaee34382012-09-05 22:56:26 +00003427static bool requiresParensToAddCast(const Expr *E) {
3428 // FIXME: We should have a general way to reason about operator
3429 // precedence and whether parens are actually needed here.
3430 // Take care of a few common cases where they aren't.
3431 const Expr *Inside = E->IgnoreImpCasts();
3432 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3433 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3434
3435 switch (Inside->getStmtClass()) {
3436 case Stmt::ArraySubscriptExprClass:
3437 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003438 case Stmt::CharacterLiteralClass:
3439 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003440 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003441 case Stmt::FloatingLiteralClass:
3442 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003443 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003444 case Stmt::ObjCArrayLiteralClass:
3445 case Stmt::ObjCBoolLiteralExprClass:
3446 case Stmt::ObjCBoxedExprClass:
3447 case Stmt::ObjCDictionaryLiteralClass:
3448 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003449 case Stmt::ObjCIvarRefExprClass:
3450 case Stmt::ObjCMessageExprClass:
3451 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003452 case Stmt::ObjCStringLiteralClass:
3453 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003454 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003455 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003456 case Stmt::UnaryOperatorClass:
3457 return false;
3458 default:
3459 return true;
3460 }
3461}
3462
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003463static std::pair<QualType, StringRef>
3464shouldNotPrintDirectly(const ASTContext &Context,
3465 QualType IntendedTy,
3466 const Expr *E) {
3467 // Use a 'while' to peel off layers of typedefs.
3468 QualType TyTy = IntendedTy;
3469 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3470 StringRef Name = UserTy->getDecl()->getName();
3471 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3472 .Case("NSInteger", Context.LongTy)
3473 .Case("NSUInteger", Context.UnsignedLongTy)
3474 .Case("SInt32", Context.IntTy)
3475 .Case("UInt32", Context.UnsignedIntTy)
3476 .Default(QualType());
3477
3478 if (!CastTy.isNull())
3479 return std::make_pair(CastTy, Name);
3480
3481 TyTy = UserTy->desugar();
3482 }
3483
3484 // Strip parens if necessary.
3485 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3486 return shouldNotPrintDirectly(Context,
3487 PE->getSubExpr()->getType(),
3488 PE->getSubExpr());
3489
3490 // If this is a conditional expression, then its result type is constructed
3491 // via usual arithmetic conversions and thus there might be no necessary
3492 // typedef sugar there. Recurse to operands to check for NSInteger &
3493 // Co. usage condition.
3494 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3495 QualType TrueTy, FalseTy;
3496 StringRef TrueName, FalseName;
3497
3498 std::tie(TrueTy, TrueName) =
3499 shouldNotPrintDirectly(Context,
3500 CO->getTrueExpr()->getType(),
3501 CO->getTrueExpr());
3502 std::tie(FalseTy, FalseName) =
3503 shouldNotPrintDirectly(Context,
3504 CO->getFalseExpr()->getType(),
3505 CO->getFalseExpr());
3506
3507 if (TrueTy == FalseTy)
3508 return std::make_pair(TrueTy, TrueName);
3509 else if (TrueTy.isNull())
3510 return std::make_pair(FalseTy, FalseName);
3511 else if (FalseTy.isNull())
3512 return std::make_pair(TrueTy, TrueName);
3513 }
3514
3515 return std::make_pair(QualType(), StringRef());
3516}
3517
Richard Smith55ce3522012-06-25 20:30:08 +00003518bool
3519CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3520 const char *StartSpecifier,
3521 unsigned SpecifierLen,
3522 const Expr *E) {
3523 using namespace analyze_format_string;
3524 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003525 // Now type check the data expression that matches the
3526 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003527 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3528 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003529 if (!AT.isValid())
3530 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003531
Jordan Rose598ec092012-12-05 18:44:40 +00003532 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003533 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3534 ExprTy = TET->getUnderlyingExpr()->getType();
3535 }
3536
Jordan Rose598ec092012-12-05 18:44:40 +00003537 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003538 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003539
Jordan Rose22b74712012-09-05 22:56:19 +00003540 // Look through argument promotions for our error message's reported type.
3541 // This includes the integral and floating promotions, but excludes array
3542 // and function pointer decay; seeing that an argument intended to be a
3543 // string has type 'char [6]' is probably more confusing than 'char *'.
3544 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3545 if (ICE->getCastKind() == CK_IntegralCast ||
3546 ICE->getCastKind() == CK_FloatingCast) {
3547 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003548 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003549
3550 // Check if we didn't match because of an implicit cast from a 'char'
3551 // or 'short' to an 'int'. This is done because printf is a varargs
3552 // function.
3553 if (ICE->getType() == S.Context.IntTy ||
3554 ICE->getType() == S.Context.UnsignedIntTy) {
3555 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003556 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003557 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003558 }
Jordan Rose98709982012-06-04 22:48:57 +00003559 }
Jordan Rose598ec092012-12-05 18:44:40 +00003560 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3561 // Special case for 'a', which has type 'int' in C.
3562 // Note, however, that we do /not/ want to treat multibyte constants like
3563 // 'MooV' as characters! This form is deprecated but still exists.
3564 if (ExprTy == S.Context.IntTy)
3565 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3566 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003567 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003568
Jordan Rosebc53ed12014-05-31 04:12:14 +00003569 // Look through enums to their underlying type.
3570 bool IsEnum = false;
3571 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3572 ExprTy = EnumTy->getDecl()->getIntegerType();
3573 IsEnum = true;
3574 }
3575
Jordan Rose0e5badd2012-12-05 18:44:49 +00003576 // %C in an Objective-C context prints a unichar, not a wchar_t.
3577 // If the argument is an integer of some kind, believe the %C and suggest
3578 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003579 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003580 if (ObjCContext &&
3581 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3582 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3583 !ExprTy->isCharType()) {
3584 // 'unichar' is defined as a typedef of unsigned short, but we should
3585 // prefer using the typedef if it is visible.
3586 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003587
3588 // While we are here, check if the value is an IntegerLiteral that happens
3589 // to be within the valid range.
3590 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3591 const llvm::APInt &V = IL->getValue();
3592 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3593 return true;
3594 }
3595
Jordan Rose0e5badd2012-12-05 18:44:49 +00003596 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3597 Sema::LookupOrdinaryName);
3598 if (S.LookupName(Result, S.getCurScope())) {
3599 NamedDecl *ND = Result.getFoundDecl();
3600 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3601 if (TD->getUnderlyingType() == IntendedTy)
3602 IntendedTy = S.Context.getTypedefType(TD);
3603 }
3604 }
3605 }
3606
3607 // Special-case some of Darwin's platform-independence types by suggesting
3608 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003609 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00003610 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003611 QualType CastTy;
3612 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3613 if (!CastTy.isNull()) {
3614 IntendedTy = CastTy;
3615 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00003616 }
3617 }
3618
Jordan Rose22b74712012-09-05 22:56:19 +00003619 // We may be able to offer a FixItHint if it is a supported type.
3620 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003621 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003622 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003623
Jordan Rose22b74712012-09-05 22:56:19 +00003624 if (success) {
3625 // Get the fix string from the fixed format specifier
3626 SmallString<16> buf;
3627 llvm::raw_svector_ostream os(buf);
3628 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003629
Jordan Roseaee34382012-09-05 22:56:26 +00003630 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3631
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003632 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Jordan Rose0e5badd2012-12-05 18:44:49 +00003633 // In this case, the specifier is wrong and should be changed to match
3634 // the argument.
3635 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003636 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3637 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003638 << E->getSourceRange(),
3639 E->getLocStart(),
3640 /*IsStringLocation*/false,
3641 SpecRange,
3642 FixItHint::CreateReplacement(SpecRange, os.str()));
3643
3644 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003645 // The canonical type for formatting this value is different from the
3646 // actual type of the expression. (This occurs, for example, with Darwin's
3647 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3648 // should be printed as 'long' for 64-bit compatibility.)
3649 // Rather than emitting a normal format/argument mismatch, we want to
3650 // add a cast to the recommended type (and correct the format string
3651 // if necessary).
3652 SmallString<16> CastBuf;
3653 llvm::raw_svector_ostream CastFix(CastBuf);
3654 CastFix << "(";
3655 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3656 CastFix << ")";
3657
3658 SmallVector<FixItHint,4> Hints;
3659 if (!AT.matchesType(S.Context, IntendedTy))
3660 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3661
3662 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3663 // If there's already a cast present, just replace it.
3664 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3665 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3666
3667 } else if (!requiresParensToAddCast(E)) {
3668 // If the expression has high enough precedence,
3669 // just write the C-style cast.
3670 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3671 CastFix.str()));
3672 } else {
3673 // Otherwise, add parens around the expression as well as the cast.
3674 CastFix << "(";
3675 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3676 CastFix.str()));
3677
Alp Tokerb6cc5922014-05-03 03:45:55 +00003678 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003679 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3680 }
3681
Jordan Rose0e5badd2012-12-05 18:44:49 +00003682 if (ShouldNotPrintDirectly) {
3683 // The expression has a type that should not be printed directly.
3684 // We extract the name from the typedef because we don't want to show
3685 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003686 StringRef Name;
3687 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3688 Name = TypedefTy->getDecl()->getName();
3689 else
3690 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003691 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003692 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003693 << E->getSourceRange(),
3694 E->getLocStart(), /*IsStringLocation=*/false,
3695 SpecRange, Hints);
3696 } else {
3697 // In this case, the expression could be printed using a different
3698 // specifier, but we've decided that the specifier is probably correct
3699 // and we should cast instead. Just use the normal warning message.
3700 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003701 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3702 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003703 << E->getSourceRange(),
3704 E->getLocStart(), /*IsStringLocation*/false,
3705 SpecRange, Hints);
3706 }
Jordan Roseaee34382012-09-05 22:56:26 +00003707 }
Jordan Rose22b74712012-09-05 22:56:19 +00003708 } else {
3709 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3710 SpecifierLen);
3711 // Since the warning for passing non-POD types to variadic functions
3712 // was deferred until now, we emit a warning for non-POD
3713 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003714 switch (S.isValidVarArgType(ExprTy)) {
3715 case Sema::VAK_Valid:
3716 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003717 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003718 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3719 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003720 << CSR
3721 << E->getSourceRange(),
3722 E->getLocStart(), /*IsStringLocation*/false, CSR);
3723 break;
3724
3725 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00003726 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00003727 EmitFormatDiagnostic(
3728 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003729 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003730 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003731 << CallType
3732 << AT.getRepresentativeTypeName(S.Context)
3733 << CSR
3734 << E->getSourceRange(),
3735 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003736 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003737 break;
3738
3739 case Sema::VAK_Invalid:
3740 if (ExprTy->isObjCObjectType())
3741 EmitFormatDiagnostic(
3742 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3743 << S.getLangOpts().CPlusPlus11
3744 << ExprTy
3745 << CallType
3746 << AT.getRepresentativeTypeName(S.Context)
3747 << CSR
3748 << E->getSourceRange(),
3749 E->getLocStart(), /*IsStringLocation*/false, CSR);
3750 else
3751 // FIXME: If this is an initializer list, suggest removing the braces
3752 // or inserting a cast to the target type.
3753 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3754 << isa<InitListExpr>(E) << ExprTy << CallType
3755 << AT.getRepresentativeTypeName(S.Context)
3756 << E->getSourceRange();
3757 break;
3758 }
3759
3760 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3761 "format string specifier index out of range");
3762 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003763 }
3764
Ted Kremenekab278de2010-01-28 23:39:18 +00003765 return true;
3766}
3767
Ted Kremenek02087932010-07-16 02:11:22 +00003768//===--- CHECK: Scanf format string checking ------------------------------===//
3769
3770namespace {
3771class CheckScanfHandler : public CheckFormatHandler {
3772public:
3773 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3774 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003775 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003776 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003777 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003778 Sema::VariadicCallType CallType,
3779 llvm::SmallBitVector &CheckedVarArgs)
3780 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3781 numDataArgs, beg, hasVAListArg,
3782 Args, formatIdx, inFunctionCall, CallType,
3783 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003784 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003785
3786 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3787 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003788 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003789
3790 bool HandleInvalidScanfConversionSpecifier(
3791 const analyze_scanf::ScanfSpecifier &FS,
3792 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003793 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003794
Craig Toppere14c0f82014-03-12 04:55:44 +00003795 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003796};
Ted Kremenek019d2242010-01-29 01:50:07 +00003797}
Ted Kremenekab278de2010-01-28 23:39:18 +00003798
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003799void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3800 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003801 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3802 getLocationOfByte(end), /*IsStringLocation*/true,
3803 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003804}
3805
Ted Kremenekce815422010-07-19 21:25:57 +00003806bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3807 const analyze_scanf::ScanfSpecifier &FS,
3808 const char *startSpecifier,
3809 unsigned specifierLen) {
3810
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003811 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003812 FS.getConversionSpecifier();
3813
3814 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3815 getLocationOfByte(CS.getStart()),
3816 startSpecifier, specifierLen,
3817 CS.getStart(), CS.getLength());
3818}
3819
Ted Kremenek02087932010-07-16 02:11:22 +00003820bool CheckScanfHandler::HandleScanfSpecifier(
3821 const analyze_scanf::ScanfSpecifier &FS,
3822 const char *startSpecifier,
3823 unsigned specifierLen) {
3824
3825 using namespace analyze_scanf;
3826 using namespace analyze_format_string;
3827
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003828 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003829
Ted Kremenek6cd69422010-07-19 22:01:06 +00003830 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3831 // be used to decide if we are using positional arguments consistently.
3832 if (FS.consumesDataArgument()) {
3833 if (atFirstArg) {
3834 atFirstArg = false;
3835 usesPositionalArgs = FS.usesPositionalArg();
3836 }
3837 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003838 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3839 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003840 return false;
3841 }
Ted Kremenek02087932010-07-16 02:11:22 +00003842 }
3843
3844 // Check if the field with is non-zero.
3845 const OptionalAmount &Amt = FS.getFieldWidth();
3846 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3847 if (Amt.getConstantAmount() == 0) {
3848 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3849 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003850 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3851 getLocationOfByte(Amt.getStart()),
3852 /*IsStringLocation*/true, R,
3853 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003854 }
3855 }
3856
3857 if (!FS.consumesDataArgument()) {
3858 // FIXME: Technically specifying a precision or field width here
3859 // makes no sense. Worth issuing a warning at some point.
3860 return true;
3861 }
3862
3863 // Consume the argument.
3864 unsigned argIndex = FS.getArgIndex();
3865 if (argIndex < NumDataArgs) {
3866 // The check to see if the argIndex is valid will come later.
3867 // We set the bit here because we may exit early from this
3868 // function if we encounter some other error.
3869 CoveredArgs.set(argIndex);
3870 }
3871
Ted Kremenek4407ea42010-07-20 20:04:47 +00003872 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003873 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003874 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3875 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003876 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003877 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003878 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003879 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3880 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003881
Jordan Rose92303592012-09-08 04:00:03 +00003882 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3883 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3884
Ted Kremenek02087932010-07-16 02:11:22 +00003885 // The remaining checks depend on the data arguments.
3886 if (HasVAListArg)
3887 return true;
3888
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003889 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003890 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003891
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003892 // Check that the argument type matches the format specifier.
3893 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003894 if (!Ex)
3895 return true;
3896
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003897 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3898 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003899 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003900 bool success = fixedFS.fixType(Ex->getType(),
3901 Ex->IgnoreImpCasts()->getType(),
3902 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003903
3904 if (success) {
3905 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003906 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003907 llvm::raw_svector_ostream os(buf);
3908 fixedFS.toString(os);
3909
3910 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003911 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3912 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003913 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003914 Ex->getLocStart(),
3915 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003916 getSpecifierRange(startSpecifier, specifierLen),
3917 FixItHint::CreateReplacement(
3918 getSpecifierRange(startSpecifier, specifierLen),
3919 os.str()));
3920 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003921 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003922 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3923 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003924 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003925 Ex->getLocStart(),
3926 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003927 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003928 }
3929 }
3930
Ted Kremenek02087932010-07-16 02:11:22 +00003931 return true;
3932}
3933
3934void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003935 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003936 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003937 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003938 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003939 bool inFunctionCall, VariadicCallType CallType,
3940 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003941
Ted Kremenekab278de2010-01-28 23:39:18 +00003942 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003943 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003944 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003945 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003946 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3947 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003948 return;
3949 }
Ted Kremenek02087932010-07-16 02:11:22 +00003950
Ted Kremenekab278de2010-01-28 23:39:18 +00003951 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003952 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003953 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003954 // Account for cases where the string literal is truncated in a declaration.
3955 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3956 assert(T && "String literal not of constant array type!");
3957 size_t TypeSize = T->getSize().getZExtValue();
3958 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003959 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003960
3961 // Emit a warning if the string literal is truncated and does not contain an
3962 // embedded null character.
3963 if (TypeSize <= StrRef.size() &&
3964 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3965 CheckFormatHandler::EmitFormatDiagnostic(
3966 *this, inFunctionCall, Args[format_idx],
3967 PDiag(diag::warn_printf_format_string_not_null_terminated),
3968 FExpr->getLocStart(),
3969 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3970 return;
3971 }
3972
Ted Kremenekab278de2010-01-28 23:39:18 +00003973 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003974 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003975 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003976 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003977 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3978 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003979 return;
3980 }
Ted Kremenek02087932010-07-16 02:11:22 +00003981
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003982 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003983 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003984 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003985 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003986 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003987
Hans Wennborg23926bd2011-12-15 10:25:47 +00003988 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003989 getLangOpts(),
3990 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003991 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003992 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003993 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003994 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003995 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003996
Hans Wennborg23926bd2011-12-15 10:25:47 +00003997 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003998 getLangOpts(),
3999 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004000 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004001 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004002}
4003
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004004bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4005 // Str - The format string. NOTE: this is NOT null-terminated!
4006 StringRef StrRef = FExpr->getString();
4007 const char *Str = StrRef.data();
4008 // Account for cases where the string literal is truncated in a declaration.
4009 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4010 assert(T && "String literal not of constant array type!");
4011 size_t TypeSize = T->getSize().getZExtValue();
4012 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4013 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4014 getLangOpts(),
4015 Context.getTargetInfo());
4016}
4017
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004018//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4019
4020// Returns the related absolute value function that is larger, of 0 if one
4021// does not exist.
4022static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4023 switch (AbsFunction) {
4024 default:
4025 return 0;
4026
4027 case Builtin::BI__builtin_abs:
4028 return Builtin::BI__builtin_labs;
4029 case Builtin::BI__builtin_labs:
4030 return Builtin::BI__builtin_llabs;
4031 case Builtin::BI__builtin_llabs:
4032 return 0;
4033
4034 case Builtin::BI__builtin_fabsf:
4035 return Builtin::BI__builtin_fabs;
4036 case Builtin::BI__builtin_fabs:
4037 return Builtin::BI__builtin_fabsl;
4038 case Builtin::BI__builtin_fabsl:
4039 return 0;
4040
4041 case Builtin::BI__builtin_cabsf:
4042 return Builtin::BI__builtin_cabs;
4043 case Builtin::BI__builtin_cabs:
4044 return Builtin::BI__builtin_cabsl;
4045 case Builtin::BI__builtin_cabsl:
4046 return 0;
4047
4048 case Builtin::BIabs:
4049 return Builtin::BIlabs;
4050 case Builtin::BIlabs:
4051 return Builtin::BIllabs;
4052 case Builtin::BIllabs:
4053 return 0;
4054
4055 case Builtin::BIfabsf:
4056 return Builtin::BIfabs;
4057 case Builtin::BIfabs:
4058 return Builtin::BIfabsl;
4059 case Builtin::BIfabsl:
4060 return 0;
4061
4062 case Builtin::BIcabsf:
4063 return Builtin::BIcabs;
4064 case Builtin::BIcabs:
4065 return Builtin::BIcabsl;
4066 case Builtin::BIcabsl:
4067 return 0;
4068 }
4069}
4070
4071// Returns the argument type of the absolute value function.
4072static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4073 unsigned AbsType) {
4074 if (AbsType == 0)
4075 return QualType();
4076
4077 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4078 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4079 if (Error != ASTContext::GE_None)
4080 return QualType();
4081
4082 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4083 if (!FT)
4084 return QualType();
4085
4086 if (FT->getNumParams() != 1)
4087 return QualType();
4088
4089 return FT->getParamType(0);
4090}
4091
4092// Returns the best absolute value function, or zero, based on type and
4093// current absolute value function.
4094static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4095 unsigned AbsFunctionKind) {
4096 unsigned BestKind = 0;
4097 uint64_t ArgSize = Context.getTypeSize(ArgType);
4098 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4099 Kind = getLargerAbsoluteValueFunction(Kind)) {
4100 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4101 if (Context.getTypeSize(ParamType) >= ArgSize) {
4102 if (BestKind == 0)
4103 BestKind = Kind;
4104 else if (Context.hasSameType(ParamType, ArgType)) {
4105 BestKind = Kind;
4106 break;
4107 }
4108 }
4109 }
4110 return BestKind;
4111}
4112
4113enum AbsoluteValueKind {
4114 AVK_Integer,
4115 AVK_Floating,
4116 AVK_Complex
4117};
4118
4119static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4120 if (T->isIntegralOrEnumerationType())
4121 return AVK_Integer;
4122 if (T->isRealFloatingType())
4123 return AVK_Floating;
4124 if (T->isAnyComplexType())
4125 return AVK_Complex;
4126
4127 llvm_unreachable("Type not integer, floating, or complex");
4128}
4129
4130// Changes the absolute value function to a different type. Preserves whether
4131// the function is a builtin.
4132static unsigned changeAbsFunction(unsigned AbsKind,
4133 AbsoluteValueKind ValueKind) {
4134 switch (ValueKind) {
4135 case AVK_Integer:
4136 switch (AbsKind) {
4137 default:
4138 return 0;
4139 case Builtin::BI__builtin_fabsf:
4140 case Builtin::BI__builtin_fabs:
4141 case Builtin::BI__builtin_fabsl:
4142 case Builtin::BI__builtin_cabsf:
4143 case Builtin::BI__builtin_cabs:
4144 case Builtin::BI__builtin_cabsl:
4145 return Builtin::BI__builtin_abs;
4146 case Builtin::BIfabsf:
4147 case Builtin::BIfabs:
4148 case Builtin::BIfabsl:
4149 case Builtin::BIcabsf:
4150 case Builtin::BIcabs:
4151 case Builtin::BIcabsl:
4152 return Builtin::BIabs;
4153 }
4154 case AVK_Floating:
4155 switch (AbsKind) {
4156 default:
4157 return 0;
4158 case Builtin::BI__builtin_abs:
4159 case Builtin::BI__builtin_labs:
4160 case Builtin::BI__builtin_llabs:
4161 case Builtin::BI__builtin_cabsf:
4162 case Builtin::BI__builtin_cabs:
4163 case Builtin::BI__builtin_cabsl:
4164 return Builtin::BI__builtin_fabsf;
4165 case Builtin::BIabs:
4166 case Builtin::BIlabs:
4167 case Builtin::BIllabs:
4168 case Builtin::BIcabsf:
4169 case Builtin::BIcabs:
4170 case Builtin::BIcabsl:
4171 return Builtin::BIfabsf;
4172 }
4173 case AVK_Complex:
4174 switch (AbsKind) {
4175 default:
4176 return 0;
4177 case Builtin::BI__builtin_abs:
4178 case Builtin::BI__builtin_labs:
4179 case Builtin::BI__builtin_llabs:
4180 case Builtin::BI__builtin_fabsf:
4181 case Builtin::BI__builtin_fabs:
4182 case Builtin::BI__builtin_fabsl:
4183 return Builtin::BI__builtin_cabsf;
4184 case Builtin::BIabs:
4185 case Builtin::BIlabs:
4186 case Builtin::BIllabs:
4187 case Builtin::BIfabsf:
4188 case Builtin::BIfabs:
4189 case Builtin::BIfabsl:
4190 return Builtin::BIcabsf;
4191 }
4192 }
4193 llvm_unreachable("Unable to convert function");
4194}
4195
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004196static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004197 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4198 if (!FnInfo)
4199 return 0;
4200
4201 switch (FDecl->getBuiltinID()) {
4202 default:
4203 return 0;
4204 case Builtin::BI__builtin_abs:
4205 case Builtin::BI__builtin_fabs:
4206 case Builtin::BI__builtin_fabsf:
4207 case Builtin::BI__builtin_fabsl:
4208 case Builtin::BI__builtin_labs:
4209 case Builtin::BI__builtin_llabs:
4210 case Builtin::BI__builtin_cabs:
4211 case Builtin::BI__builtin_cabsf:
4212 case Builtin::BI__builtin_cabsl:
4213 case Builtin::BIabs:
4214 case Builtin::BIlabs:
4215 case Builtin::BIllabs:
4216 case Builtin::BIfabs:
4217 case Builtin::BIfabsf:
4218 case Builtin::BIfabsl:
4219 case Builtin::BIcabs:
4220 case Builtin::BIcabsf:
4221 case Builtin::BIcabsl:
4222 return FDecl->getBuiltinID();
4223 }
4224 llvm_unreachable("Unknown Builtin type");
4225}
4226
4227// If the replacement is valid, emit a note with replacement function.
4228// Additionally, suggest including the proper header if not already included.
4229static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004230 unsigned AbsKind, QualType ArgType) {
4231 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004232 const char *HeaderName = nullptr;
4233 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004234 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4235 FunctionName = "std::abs";
4236 if (ArgType->isIntegralOrEnumerationType()) {
4237 HeaderName = "cstdlib";
4238 } else if (ArgType->isRealFloatingType()) {
4239 HeaderName = "cmath";
4240 } else {
4241 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004242 }
Richard Trieubeffb832014-04-15 23:47:53 +00004243
4244 // Lookup all std::abs
4245 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004246 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004247 R.suppressDiagnostics();
4248 S.LookupQualifiedName(R, Std);
4249
4250 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004251 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004252 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4253 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4254 } else {
4255 FDecl = dyn_cast<FunctionDecl>(I);
4256 }
4257 if (!FDecl)
4258 continue;
4259
4260 // Found std::abs(), check that they are the right ones.
4261 if (FDecl->getNumParams() != 1)
4262 continue;
4263
4264 // Check that the parameter type can handle the argument.
4265 QualType ParamType = FDecl->getParamDecl(0)->getType();
4266 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4267 S.Context.getTypeSize(ArgType) <=
4268 S.Context.getTypeSize(ParamType)) {
4269 // Found a function, don't need the header hint.
4270 EmitHeaderHint = false;
4271 break;
4272 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004273 }
Richard Trieubeffb832014-04-15 23:47:53 +00004274 }
4275 } else {
4276 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4277 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4278
4279 if (HeaderName) {
4280 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4281 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4282 R.suppressDiagnostics();
4283 S.LookupName(R, S.getCurScope());
4284
4285 if (R.isSingleResult()) {
4286 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4287 if (FD && FD->getBuiltinID() == AbsKind) {
4288 EmitHeaderHint = false;
4289 } else {
4290 return;
4291 }
4292 } else if (!R.empty()) {
4293 return;
4294 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004295 }
4296 }
4297
4298 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004299 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004300
Richard Trieubeffb832014-04-15 23:47:53 +00004301 if (!HeaderName)
4302 return;
4303
4304 if (!EmitHeaderHint)
4305 return;
4306
Alp Toker5d96e0a2014-07-11 20:53:51 +00004307 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4308 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004309}
4310
4311static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4312 if (!FDecl)
4313 return false;
4314
4315 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4316 return false;
4317
4318 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4319
4320 while (ND && ND->isInlineNamespace()) {
4321 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004322 }
Richard Trieubeffb832014-04-15 23:47:53 +00004323
4324 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4325 return false;
4326
4327 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4328 return false;
4329
4330 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004331}
4332
4333// Warn when using the wrong abs() function.
4334void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4335 const FunctionDecl *FDecl,
4336 IdentifierInfo *FnInfo) {
4337 if (Call->getNumArgs() != 1)
4338 return;
4339
4340 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004341 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4342 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004343 return;
4344
4345 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4346 QualType ParamType = Call->getArg(0)->getType();
4347
Alp Toker5d96e0a2014-07-11 20:53:51 +00004348 // Unsigned types cannot be negative. Suggest removing the absolute value
4349 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004350 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004351 const char *FunctionName =
4352 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004353 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4354 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004355 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004356 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4357 return;
4358 }
4359
Richard Trieubeffb832014-04-15 23:47:53 +00004360 // std::abs has overloads which prevent most of the absolute value problems
4361 // from occurring.
4362 if (IsStdAbs)
4363 return;
4364
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004365 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4366 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4367
4368 // The argument and parameter are the same kind. Check if they are the right
4369 // size.
4370 if (ArgValueKind == ParamValueKind) {
4371 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4372 return;
4373
4374 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4375 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4376 << FDecl << ArgType << ParamType;
4377
4378 if (NewAbsKind == 0)
4379 return;
4380
4381 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004382 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004383 return;
4384 }
4385
4386 // ArgValueKind != ParamValueKind
4387 // The wrong type of absolute value function was used. Attempt to find the
4388 // proper one.
4389 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4390 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4391 if (NewAbsKind == 0)
4392 return;
4393
4394 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4395 << FDecl << ParamValueKind << ArgValueKind;
4396
4397 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004398 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004399 return;
4400}
4401
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004402//===--- CHECK: Standard memory functions ---------------------------------===//
4403
Nico Weber0e6daef2013-12-26 23:38:39 +00004404/// \brief Takes the expression passed to the size_t parameter of functions
4405/// such as memcmp, strncat, etc and warns if it's a comparison.
4406///
4407/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4408static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4409 IdentifierInfo *FnName,
4410 SourceLocation FnLoc,
4411 SourceLocation RParenLoc) {
4412 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4413 if (!Size)
4414 return false;
4415
4416 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4417 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4418 return false;
4419
Nico Weber0e6daef2013-12-26 23:38:39 +00004420 SourceRange SizeRange = Size->getSourceRange();
4421 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4422 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004423 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004424 << FnName << FixItHint::CreateInsertion(
4425 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004426 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004427 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004428 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004429 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4430 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004431
4432 return true;
4433}
4434
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004435/// \brief Determine whether the given type is or contains a dynamic class type
4436/// (e.g., whether it has a vtable).
4437static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4438 bool &IsContained) {
4439 // Look through array types while ignoring qualifiers.
4440 const Type *Ty = T->getBaseElementTypeUnsafe();
4441 IsContained = false;
4442
4443 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4444 RD = RD ? RD->getDefinition() : nullptr;
4445 if (!RD)
4446 return nullptr;
4447
4448 if (RD->isDynamicClass())
4449 return RD;
4450
4451 // Check all the fields. If any bases were dynamic, the class is dynamic.
4452 // It's impossible for a class to transitively contain itself by value, so
4453 // infinite recursion is impossible.
4454 for (auto *FD : RD->fields()) {
4455 bool SubContained;
4456 if (const CXXRecordDecl *ContainedRD =
4457 getContainedDynamicClass(FD->getType(), SubContained)) {
4458 IsContained = true;
4459 return ContainedRD;
4460 }
4461 }
4462
4463 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004464}
4465
Chandler Carruth889ed862011-06-21 23:04:20 +00004466/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004467/// otherwise returns NULL.
4468static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004469 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004470 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4471 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4472 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004473
Craig Topperc3ec1492014-05-26 06:22:03 +00004474 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004475}
4476
Chandler Carruth889ed862011-06-21 23:04:20 +00004477/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004478static QualType getSizeOfArgType(const Expr* E) {
4479 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4480 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4481 if (SizeOf->getKind() == clang::UETT_SizeOf)
4482 return SizeOf->getTypeOfArgument();
4483
4484 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004485}
4486
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004487/// \brief Check for dangerous or invalid arguments to memset().
4488///
Chandler Carruthac687262011-06-03 06:23:57 +00004489/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004490/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4491/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004492///
4493/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004494void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004495 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004496 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004497 assert(BId != 0);
4498
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004499 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004500 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004501 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004502 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004503 return;
4504
Anna Zaks22122702012-01-17 00:37:07 +00004505 unsigned LastArg = (BId == Builtin::BImemset ||
4506 BId == Builtin::BIstrndup ? 1 : 2);
4507 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004508 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004509
Nico Weber0e6daef2013-12-26 23:38:39 +00004510 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4511 Call->getLocStart(), Call->getRParenLoc()))
4512 return;
4513
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004514 // We have special checking when the length is a sizeof expression.
4515 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4516 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4517 llvm::FoldingSetNodeID SizeOfArgID;
4518
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004519 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4520 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004521 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004522
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004523 QualType DestTy = Dest->getType();
4524 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4525 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004526
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004527 // Never warn about void type pointers. This can be used to suppress
4528 // false positives.
4529 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004530 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004531
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004532 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4533 // actually comparing the expressions for equality. Because computing the
4534 // expression IDs can be expensive, we only do this if the diagnostic is
4535 // enabled.
4536 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004537 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4538 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004539 // We only compute IDs for expressions if the warning is enabled, and
4540 // cache the sizeof arg's ID.
4541 if (SizeOfArgID == llvm::FoldingSetNodeID())
4542 SizeOfArg->Profile(SizeOfArgID, Context, true);
4543 llvm::FoldingSetNodeID DestID;
4544 Dest->Profile(DestID, Context, true);
4545 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004546 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4547 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004548 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004549 StringRef ReadableName = FnName->getName();
4550
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004551 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004552 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004553 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004554 if (!PointeeTy->isIncompleteType() &&
4555 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004556 ActionIdx = 2; // If the pointee's size is sizeof(char),
4557 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004558
4559 // If the function is defined as a builtin macro, do not show macro
4560 // expansion.
4561 SourceLocation SL = SizeOfArg->getExprLoc();
4562 SourceRange DSR = Dest->getSourceRange();
4563 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004564 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004565
4566 if (SM.isMacroArgExpansion(SL)) {
4567 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4568 SL = SM.getSpellingLoc(SL);
4569 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4570 SM.getSpellingLoc(DSR.getEnd()));
4571 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4572 SM.getSpellingLoc(SSR.getEnd()));
4573 }
4574
Anna Zaksd08d9152012-05-30 23:14:52 +00004575 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004576 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004577 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004578 << PointeeTy
4579 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004580 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004581 << SSR);
4582 DiagRuntimeBehavior(SL, SizeOfArg,
4583 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4584 << ActionIdx
4585 << SSR);
4586
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004587 break;
4588 }
4589 }
4590
4591 // Also check for cases where the sizeof argument is the exact same
4592 // type as the memory argument, and where it points to a user-defined
4593 // record type.
4594 if (SizeOfArgTy != QualType()) {
4595 if (PointeeTy->isRecordType() &&
4596 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4597 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4598 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4599 << FnName << SizeOfArgTy << ArgIdx
4600 << PointeeTy << Dest->getSourceRange()
4601 << LenExpr->getSourceRange());
4602 break;
4603 }
Nico Weberc5e73862011-06-14 16:14:58 +00004604 }
4605
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004606 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004607 bool IsContained;
4608 if (const CXXRecordDecl *ContainedRD =
4609 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004610
4611 unsigned OperationType = 0;
4612 // "overwritten" if we're warning about the destination for any call
4613 // but memcmp; otherwise a verb appropriate to the call.
4614 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4615 if (BId == Builtin::BImemcpy)
4616 OperationType = 1;
4617 else if(BId == Builtin::BImemmove)
4618 OperationType = 2;
4619 else if (BId == Builtin::BImemcmp)
4620 OperationType = 3;
4621 }
4622
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004623 DiagRuntimeBehavior(
4624 Dest->getExprLoc(), Dest,
4625 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004626 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004627 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004628 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004629 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4630 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004631 DiagRuntimeBehavior(
4632 Dest->getExprLoc(), Dest,
4633 PDiag(diag::warn_arc_object_memaccess)
4634 << ArgIdx << FnName << PointeeTy
4635 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004636 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004637 continue;
John McCall31168b02011-06-15 23:02:42 +00004638
4639 DiagRuntimeBehavior(
4640 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004641 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004642 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4643 break;
4644 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004645 }
4646}
4647
Ted Kremenek6865f772011-08-18 20:55:45 +00004648// A little helper routine: ignore addition and subtraction of integer literals.
4649// This intentionally does not ignore all integer constant expressions because
4650// we don't want to remove sizeof().
4651static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4652 Ex = Ex->IgnoreParenCasts();
4653
4654 for (;;) {
4655 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4656 if (!BO || !BO->isAdditiveOp())
4657 break;
4658
4659 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4660 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4661
4662 if (isa<IntegerLiteral>(RHS))
4663 Ex = LHS;
4664 else if (isa<IntegerLiteral>(LHS))
4665 Ex = RHS;
4666 else
4667 break;
4668 }
4669
4670 return Ex;
4671}
4672
Anna Zaks13b08572012-08-08 21:42:23 +00004673static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4674 ASTContext &Context) {
4675 // Only handle constant-sized or VLAs, but not flexible members.
4676 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4677 // Only issue the FIXIT for arrays of size > 1.
4678 if (CAT->getSize().getSExtValue() <= 1)
4679 return false;
4680 } else if (!Ty->isVariableArrayType()) {
4681 return false;
4682 }
4683 return true;
4684}
4685
Ted Kremenek6865f772011-08-18 20:55:45 +00004686// Warn if the user has made the 'size' argument to strlcpy or strlcat
4687// be the size of the source, instead of the destination.
4688void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4689 IdentifierInfo *FnName) {
4690
4691 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004692 unsigned NumArgs = Call->getNumArgs();
4693 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004694 return;
4695
4696 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4697 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004698 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004699
4700 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4701 Call->getLocStart(), Call->getRParenLoc()))
4702 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004703
4704 // Look for 'strlcpy(dst, x, sizeof(x))'
4705 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4706 CompareWithSrc = Ex;
4707 else {
4708 // Look for 'strlcpy(dst, x, strlen(x))'
4709 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004710 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4711 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004712 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4713 }
4714 }
4715
4716 if (!CompareWithSrc)
4717 return;
4718
4719 // Determine if the argument to sizeof/strlen is equal to the source
4720 // argument. In principle there's all kinds of things you could do
4721 // here, for instance creating an == expression and evaluating it with
4722 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4723 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4724 if (!SrcArgDRE)
4725 return;
4726
4727 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4728 if (!CompareWithSrcDRE ||
4729 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4730 return;
4731
4732 const Expr *OriginalSizeArg = Call->getArg(2);
4733 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4734 << OriginalSizeArg->getSourceRange() << FnName;
4735
4736 // Output a FIXIT hint if the destination is an array (rather than a
4737 // pointer to an array). This could be enhanced to handle some
4738 // pointers if we know the actual size, like if DstArg is 'array+2'
4739 // we could say 'sizeof(array)-2'.
4740 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004741 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004742 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004743
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004744 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004745 llvm::raw_svector_ostream OS(sizeString);
4746 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004747 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004748 OS << ")";
4749
4750 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4751 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4752 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004753}
4754
Anna Zaks314cd092012-02-01 19:08:57 +00004755/// Check if two expressions refer to the same declaration.
4756static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4757 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4758 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4759 return D1->getDecl() == D2->getDecl();
4760 return false;
4761}
4762
4763static const Expr *getStrlenExprArg(const Expr *E) {
4764 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4765 const FunctionDecl *FD = CE->getDirectCallee();
4766 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004767 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004768 return CE->getArg(0)->IgnoreParenCasts();
4769 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004770 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004771}
4772
4773// Warn on anti-patterns as the 'size' argument to strncat.
4774// The correct size argument should look like following:
4775// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4776void Sema::CheckStrncatArguments(const CallExpr *CE,
4777 IdentifierInfo *FnName) {
4778 // Don't crash if the user has the wrong number of arguments.
4779 if (CE->getNumArgs() < 3)
4780 return;
4781 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4782 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4783 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4784
Nico Weber0e6daef2013-12-26 23:38:39 +00004785 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4786 CE->getRParenLoc()))
4787 return;
4788
Anna Zaks314cd092012-02-01 19:08:57 +00004789 // Identify common expressions, which are wrongly used as the size argument
4790 // to strncat and may lead to buffer overflows.
4791 unsigned PatternType = 0;
4792 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4793 // - sizeof(dst)
4794 if (referToTheSameDecl(SizeOfArg, DstArg))
4795 PatternType = 1;
4796 // - sizeof(src)
4797 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4798 PatternType = 2;
4799 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4800 if (BE->getOpcode() == BO_Sub) {
4801 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4802 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4803 // - sizeof(dst) - strlen(dst)
4804 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4805 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4806 PatternType = 1;
4807 // - sizeof(src) - (anything)
4808 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4809 PatternType = 2;
4810 }
4811 }
4812
4813 if (PatternType == 0)
4814 return;
4815
Anna Zaks5069aa32012-02-03 01:27:37 +00004816 // Generate the diagnostic.
4817 SourceLocation SL = LenArg->getLocStart();
4818 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004819 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004820
4821 // If the function is defined as a builtin macro, do not show macro expansion.
4822 if (SM.isMacroArgExpansion(SL)) {
4823 SL = SM.getSpellingLoc(SL);
4824 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4825 SM.getSpellingLoc(SR.getEnd()));
4826 }
4827
Anna Zaks13b08572012-08-08 21:42:23 +00004828 // Check if the destination is an array (rather than a pointer to an array).
4829 QualType DstTy = DstArg->getType();
4830 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4831 Context);
4832 if (!isKnownSizeArray) {
4833 if (PatternType == 1)
4834 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4835 else
4836 Diag(SL, diag::warn_strncat_src_size) << SR;
4837 return;
4838 }
4839
Anna Zaks314cd092012-02-01 19:08:57 +00004840 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004841 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004842 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004843 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004844
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004845 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004846 llvm::raw_svector_ostream OS(sizeString);
4847 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004848 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004849 OS << ") - ";
4850 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004851 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004852 OS << ") - 1";
4853
Anna Zaks5069aa32012-02-03 01:27:37 +00004854 Diag(SL, diag::note_strncat_wrong_size)
4855 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004856}
4857
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004858//===--- CHECK: Return Address of Stack Variable --------------------------===//
4859
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004860static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4861 Decl *ParentDecl);
4862static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4863 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004864
4865/// CheckReturnStackAddr - Check if a return statement returns the address
4866/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004867static void
4868CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4869 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004870
Craig Topperc3ec1492014-05-26 06:22:03 +00004871 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004872 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004873
4874 // Perform checking for returned stack addresses, local blocks,
4875 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004876 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004877 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004878 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004879 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004880 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004881 }
4882
Craig Topperc3ec1492014-05-26 06:22:03 +00004883 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004884 return; // Nothing suspicious was found.
4885
4886 SourceLocation diagLoc;
4887 SourceRange diagRange;
4888 if (refVars.empty()) {
4889 diagLoc = stackE->getLocStart();
4890 diagRange = stackE->getSourceRange();
4891 } else {
4892 // We followed through a reference variable. 'stackE' contains the
4893 // problematic expression but we will warn at the return statement pointing
4894 // at the reference variable. We will later display the "trail" of
4895 // reference variables using notes.
4896 diagLoc = refVars[0]->getLocStart();
4897 diagRange = refVars[0]->getSourceRange();
4898 }
4899
4900 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004901 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004902 : diag::warn_ret_stack_addr)
4903 << DR->getDecl()->getDeclName() << diagRange;
4904 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004905 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004906 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004907 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004908 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004909 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4910 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004911 << diagRange;
4912 }
4913
4914 // Display the "trail" of reference variables that we followed until we
4915 // found the problematic expression using notes.
4916 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4917 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4918 // If this var binds to another reference var, show the range of the next
4919 // var, otherwise the var binds to the problematic expression, in which case
4920 // show the range of the expression.
4921 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4922 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004923 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4924 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004925 }
4926}
4927
4928/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4929/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004930/// to a location on the stack, a local block, an address of a label, or a
4931/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004932/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004933/// encounter a subexpression that (1) clearly does not lead to one of the
4934/// above problematic expressions (2) is something we cannot determine leads to
4935/// a problematic expression based on such local checking.
4936///
4937/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4938/// the expression that they point to. Such variables are added to the
4939/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004940///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004941/// EvalAddr processes expressions that are pointers that are used as
4942/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004943/// At the base case of the recursion is a check for the above problematic
4944/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004945///
4946/// This implementation handles:
4947///
4948/// * pointer-to-pointer casts
4949/// * implicit conversions from array references to pointers
4950/// * taking the address of fields
4951/// * arbitrary interplay between "&" and "*" operators
4952/// * pointer arithmetic from an address of a stack variable
4953/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004954static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4955 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004956 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00004957 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004958
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004959 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004960 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004961 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004962 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004963 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004964
Peter Collingbourne91147592011-04-15 00:35:48 +00004965 E = E->IgnoreParens();
4966
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004967 // Our "symbolic interpreter" is just a dispatch off the currently
4968 // viewed AST node. We then recursively traverse the AST by calling
4969 // EvalAddr and EvalVal appropriately.
4970 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004971 case Stmt::DeclRefExprClass: {
4972 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4973
Richard Smith40f08eb2014-01-30 22:05:38 +00004974 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev07649fb2014-12-16 08:01:48 +00004975 if (DR->refersToCapturedVariable())
Craig Topperc3ec1492014-05-26 06:22:03 +00004976 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004977
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004978 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4979 // If this is a reference variable, follow through to the expression that
4980 // it points to.
4981 if (V->hasLocalStorage() &&
4982 V->getType()->isReferenceType() && V->hasInit()) {
4983 // Add the reference variable to the "trail".
4984 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004985 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004986 }
4987
Craig Topperc3ec1492014-05-26 06:22:03 +00004988 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004989 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004990
Chris Lattner934edb22007-12-28 05:31:15 +00004991 case Stmt::UnaryOperatorClass: {
4992 // The only unary operator that make sense to handle here
4993 // is AddrOf. All others don't make sense as pointers.
4994 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004995
John McCalle3027922010-08-25 11:45:40 +00004996 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004997 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004998 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004999 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005000 }
Mike Stump11289f42009-09-09 15:08:12 +00005001
Chris Lattner934edb22007-12-28 05:31:15 +00005002 case Stmt::BinaryOperatorClass: {
5003 // Handle pointer arithmetic. All other binary operators are not valid
5004 // in this context.
5005 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005006 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005007
John McCalle3027922010-08-25 11:45:40 +00005008 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005009 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005010
Chris Lattner934edb22007-12-28 05:31:15 +00005011 Expr *Base = B->getLHS();
5012
5013 // Determine which argument is the real pointer base. It could be
5014 // the RHS argument instead of the LHS.
5015 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005016
Chris Lattner934edb22007-12-28 05:31:15 +00005017 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005018 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005019 }
Steve Naroff2752a172008-09-10 19:17:48 +00005020
Chris Lattner934edb22007-12-28 05:31:15 +00005021 // For conditional operators we need to see if either the LHS or RHS are
5022 // valid DeclRefExpr*s. If one of them is valid, we return it.
5023 case Stmt::ConditionalOperatorClass: {
5024 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005025
Chris Lattner934edb22007-12-28 05:31:15 +00005026 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005027 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5028 if (Expr *LHSExpr = C->getLHS()) {
5029 // In C++, we can have a throw-expression, which has 'void' type.
5030 if (!LHSExpr->getType()->isVoidType())
5031 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005032 return LHS;
5033 }
Chris Lattner934edb22007-12-28 05:31:15 +00005034
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005035 // In C++, we can have a throw-expression, which has 'void' type.
5036 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005037 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005038
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005039 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005040 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005041
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005042 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005043 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005044 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005045 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005046
5047 case Stmt::AddrLabelExprClass:
5048 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005049
John McCall28fc7092011-11-10 05:35:25 +00005050 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005051 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5052 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005053
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005054 // For casts, we need to handle conversions from arrays to
5055 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005056 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005057 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005058 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005059 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005060 case Stmt::CXXStaticCastExprClass:
5061 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005062 case Stmt::CXXConstCastExprClass:
5063 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005064 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5065 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005066 case CK_LValueToRValue:
5067 case CK_NoOp:
5068 case CK_BaseToDerived:
5069 case CK_DerivedToBase:
5070 case CK_UncheckedDerivedToBase:
5071 case CK_Dynamic:
5072 case CK_CPointerToObjCPointerCast:
5073 case CK_BlockPointerToObjCPointerCast:
5074 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005075 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005076
5077 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005078 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005079
Richard Trieudadefde2014-07-02 04:39:38 +00005080 case CK_BitCast:
5081 if (SubExpr->getType()->isAnyPointerType() ||
5082 SubExpr->getType()->isBlockPointerType() ||
5083 SubExpr->getType()->isObjCQualifiedIdType())
5084 return EvalAddr(SubExpr, refVars, ParentDecl);
5085 else
5086 return nullptr;
5087
Eli Friedman8195ad72012-02-23 23:04:32 +00005088 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005089 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005090 }
Chris Lattner934edb22007-12-28 05:31:15 +00005091 }
Mike Stump11289f42009-09-09 15:08:12 +00005092
Douglas Gregorfe314812011-06-21 17:03:29 +00005093 case Stmt::MaterializeTemporaryExprClass:
5094 if (Expr *Result = EvalAddr(
5095 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005096 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005097 return Result;
5098
5099 return E;
5100
Chris Lattner934edb22007-12-28 05:31:15 +00005101 // Everything else: we simply don't reason about them.
5102 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005103 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005104 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005105}
Mike Stump11289f42009-09-09 15:08:12 +00005106
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005107
5108/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5109/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005110static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5111 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005112do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005113 // We should only be called for evaluating non-pointer expressions, or
5114 // expressions with a pointer type that are not used as references but instead
5115 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005116
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005117 // Our "symbolic interpreter" is just a dispatch off the currently
5118 // viewed AST node. We then recursively traverse the AST by calling
5119 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005120
5121 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005122 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005123 case Stmt::ImplicitCastExprClass: {
5124 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005125 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005126 E = IE->getSubExpr();
5127 continue;
5128 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005129 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005130 }
5131
John McCall28fc7092011-11-10 05:35:25 +00005132 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005133 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005134
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005135 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005136 // When we hit a DeclRefExpr we are looking at code that refers to a
5137 // variable's name. If it's not a reference variable we check if it has
5138 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005139 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005140
Richard Smith40f08eb2014-01-30 22:05:38 +00005141 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev07649fb2014-12-16 08:01:48 +00005142 if (DR->refersToCapturedVariable())
Craig Topperc3ec1492014-05-26 06:22:03 +00005143 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005144
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005145 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5146 // Check if it refers to itself, e.g. "int& i = i;".
5147 if (V == ParentDecl)
5148 return DR;
5149
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005150 if (V->hasLocalStorage()) {
5151 if (!V->getType()->isReferenceType())
5152 return DR;
5153
5154 // Reference variable, follow through to the expression that
5155 // it points to.
5156 if (V->hasInit()) {
5157 // Add the reference variable to the "trail".
5158 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005159 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005160 }
5161 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005162 }
Mike Stump11289f42009-09-09 15:08:12 +00005163
Craig Topperc3ec1492014-05-26 06:22:03 +00005164 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005165 }
Mike Stump11289f42009-09-09 15:08:12 +00005166
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005167 case Stmt::UnaryOperatorClass: {
5168 // The only unary operator that make sense to handle here
5169 // is Deref. All others don't resolve to a "name." This includes
5170 // handling all sorts of rvalues passed to a unary operator.
5171 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005172
John McCalle3027922010-08-25 11:45:40 +00005173 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005174 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005175
Craig Topperc3ec1492014-05-26 06:22:03 +00005176 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005177 }
Mike Stump11289f42009-09-09 15:08:12 +00005178
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005179 case Stmt::ArraySubscriptExprClass: {
5180 // Array subscripts are potential references to data on the stack. We
5181 // retrieve the DeclRefExpr* for the array variable if it indeed
5182 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005183 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005184 }
Mike Stump11289f42009-09-09 15:08:12 +00005185
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005186 case Stmt::ConditionalOperatorClass: {
5187 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005188 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005189 ConditionalOperator *C = cast<ConditionalOperator>(E);
5190
Anders Carlsson801c5c72007-11-30 19:04:31 +00005191 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005192 if (Expr *LHSExpr = C->getLHS()) {
5193 // In C++, we can have a throw-expression, which has 'void' type.
5194 if (!LHSExpr->getType()->isVoidType())
5195 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5196 return LHS;
5197 }
5198
5199 // In C++, we can have a throw-expression, which has 'void' type.
5200 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005201 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005202
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005203 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005204 }
Mike Stump11289f42009-09-09 15:08:12 +00005205
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005206 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005207 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005208 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005209
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005210 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005211 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005212 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005213
5214 // Check whether the member type is itself a reference, in which case
5215 // we're not going to refer to the member, but to what the member refers to.
5216 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005217 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005218
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005219 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005220 }
Mike Stump11289f42009-09-09 15:08:12 +00005221
Douglas Gregorfe314812011-06-21 17:03:29 +00005222 case Stmt::MaterializeTemporaryExprClass:
5223 if (Expr *Result = EvalVal(
5224 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005225 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005226 return Result;
5227
5228 return E;
5229
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005230 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005231 // Check that we don't return or take the address of a reference to a
5232 // temporary. This is only useful in C++.
5233 if (!E->isTypeDependent() && E->isRValue())
5234 return E;
5235
5236 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005237 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005238 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005239} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005240}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005241
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005242void
5243Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5244 SourceLocation ReturnLoc,
5245 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005246 const AttrVec *Attrs,
5247 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005248 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5249
5250 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005251 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5252 CheckNonNullExpr(*this, RetValExp))
5253 Diag(ReturnLoc, diag::warn_null_ret)
5254 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005255
5256 // C++11 [basic.stc.dynamic.allocation]p4:
5257 // If an allocation function declared with a non-throwing
5258 // exception-specification fails to allocate storage, it shall return
5259 // a null pointer. Any other allocation function that fails to allocate
5260 // storage shall indicate failure only by throwing an exception [...]
5261 if (FD) {
5262 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5263 if (Op == OO_New || Op == OO_Array_New) {
5264 const FunctionProtoType *Proto
5265 = FD->getType()->castAs<FunctionProtoType>();
5266 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5267 CheckNonNullExpr(*this, RetValExp))
5268 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5269 << FD << getLangOpts().CPlusPlus11;
5270 }
5271 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005272}
5273
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005274//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5275
5276/// Check for comparisons of floating point operands using != and ==.
5277/// Issue a warning if these are no self-comparisons, as they are not likely
5278/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005279void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005280 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5281 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005282
5283 // Special case: check for x == x (which is OK).
5284 // Do not emit warnings for such cases.
5285 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5286 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5287 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005288 return;
Mike Stump11289f42009-09-09 15:08:12 +00005289
5290
Ted Kremenekeda40e22007-11-29 00:59:04 +00005291 // Special case: check for comparisons against literals that can be exactly
5292 // represented by APFloat. In such cases, do not emit a warning. This
5293 // is a heuristic: often comparison against such literals are used to
5294 // detect if a value in a variable has not changed. This clearly can
5295 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005296 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5297 if (FLL->isExact())
5298 return;
5299 } else
5300 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5301 if (FLR->isExact())
5302 return;
Mike Stump11289f42009-09-09 15:08:12 +00005303
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005304 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005305 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005306 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005307 return;
Mike Stump11289f42009-09-09 15:08:12 +00005308
David Blaikie1f4ff152012-07-16 20:47:22 +00005309 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005310 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005311 return;
Mike Stump11289f42009-09-09 15:08:12 +00005312
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005313 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005314 Diag(Loc, diag::warn_floatingpoint_eq)
5315 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005316}
John McCallca01b222010-01-04 23:21:16 +00005317
John McCall70aa5392010-01-06 05:24:50 +00005318//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5319//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005320
John McCall70aa5392010-01-06 05:24:50 +00005321namespace {
John McCallca01b222010-01-04 23:21:16 +00005322
John McCall70aa5392010-01-06 05:24:50 +00005323/// Structure recording the 'active' range of an integer-valued
5324/// expression.
5325struct IntRange {
5326 /// The number of bits active in the int.
5327 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005328
John McCall70aa5392010-01-06 05:24:50 +00005329 /// True if the int is known not to have negative values.
5330 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005331
John McCall70aa5392010-01-06 05:24:50 +00005332 IntRange(unsigned Width, bool NonNegative)
5333 : Width(Width), NonNegative(NonNegative)
5334 {}
John McCallca01b222010-01-04 23:21:16 +00005335
John McCall817d4af2010-11-10 23:38:19 +00005336 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005337 static IntRange forBoolType() {
5338 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005339 }
5340
John McCall817d4af2010-11-10 23:38:19 +00005341 /// Returns the range of an opaque value of the given integral type.
5342 static IntRange forValueOfType(ASTContext &C, QualType T) {
5343 return forValueOfCanonicalType(C,
5344 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005345 }
5346
John McCall817d4af2010-11-10 23:38:19 +00005347 /// Returns the range of an opaque value of a canonical integral type.
5348 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005349 assert(T->isCanonicalUnqualified());
5350
5351 if (const VectorType *VT = dyn_cast<VectorType>(T))
5352 T = VT->getElementType().getTypePtr();
5353 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5354 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005355 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5356 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005357
David Majnemer6a426652013-06-07 22:07:20 +00005358 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005359 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005360 EnumDecl *Enum = ET->getDecl();
5361 if (!Enum->isCompleteDefinition())
5362 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005363
David Majnemer6a426652013-06-07 22:07:20 +00005364 unsigned NumPositive = Enum->getNumPositiveBits();
5365 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005366
David Majnemer6a426652013-06-07 22:07:20 +00005367 if (NumNegative == 0)
5368 return IntRange(NumPositive, true/*NonNegative*/);
5369 else
5370 return IntRange(std::max(NumPositive + 1, NumNegative),
5371 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005372 }
John McCall70aa5392010-01-06 05:24:50 +00005373
5374 const BuiltinType *BT = cast<BuiltinType>(T);
5375 assert(BT->isInteger());
5376
5377 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5378 }
5379
John McCall817d4af2010-11-10 23:38:19 +00005380 /// Returns the "target" range of a canonical integral type, i.e.
5381 /// the range of values expressible in the type.
5382 ///
5383 /// This matches forValueOfCanonicalType except that enums have the
5384 /// full range of their type, not the range of their enumerators.
5385 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5386 assert(T->isCanonicalUnqualified());
5387
5388 if (const VectorType *VT = dyn_cast<VectorType>(T))
5389 T = VT->getElementType().getTypePtr();
5390 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5391 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005392 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5393 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005394 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005395 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005396
5397 const BuiltinType *BT = cast<BuiltinType>(T);
5398 assert(BT->isInteger());
5399
5400 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5401 }
5402
5403 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005404 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005405 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005406 L.NonNegative && R.NonNegative);
5407 }
5408
John McCall817d4af2010-11-10 23:38:19 +00005409 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005410 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005411 return IntRange(std::min(L.Width, R.Width),
5412 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005413 }
5414};
5415
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005416static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5417 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005418 if (value.isSigned() && value.isNegative())
5419 return IntRange(value.getMinSignedBits(), false);
5420
5421 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005422 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005423
5424 // isNonNegative() just checks the sign bit without considering
5425 // signedness.
5426 return IntRange(value.getActiveBits(), true);
5427}
5428
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005429static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5430 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005431 if (result.isInt())
5432 return GetValueRange(C, result.getInt(), MaxWidth);
5433
5434 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005435 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5436 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5437 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5438 R = IntRange::join(R, El);
5439 }
John McCall70aa5392010-01-06 05:24:50 +00005440 return R;
5441 }
5442
5443 if (result.isComplexInt()) {
5444 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5445 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5446 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005447 }
5448
5449 // This can happen with lossless casts to intptr_t of "based" lvalues.
5450 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005451 // FIXME: The only reason we need to pass the type in here is to get
5452 // the sign right on this one case. It would be nice if APValue
5453 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005454 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005455 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005456}
John McCall70aa5392010-01-06 05:24:50 +00005457
Eli Friedmane6d33952013-07-08 20:20:06 +00005458static QualType GetExprType(Expr *E) {
5459 QualType Ty = E->getType();
5460 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5461 Ty = AtomicRHS->getValueType();
5462 return Ty;
5463}
5464
John McCall70aa5392010-01-06 05:24:50 +00005465/// Pseudo-evaluate the given integer expression, estimating the
5466/// range of values it might take.
5467///
5468/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005469static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005470 E = E->IgnoreParens();
5471
5472 // Try a full evaluation first.
5473 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005474 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005475 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005476
5477 // I think we only want to look through implicit casts here; if the
5478 // user has an explicit widening cast, we should treat the value as
5479 // being of the new, wider type.
5480 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005481 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005482 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5483
Eli Friedmane6d33952013-07-08 20:20:06 +00005484 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005485
John McCalle3027922010-08-25 11:45:40 +00005486 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005487
John McCall70aa5392010-01-06 05:24:50 +00005488 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005489 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005490 return OutputTypeRange;
5491
5492 IntRange SubRange
5493 = GetExprRange(C, CE->getSubExpr(),
5494 std::min(MaxWidth, OutputTypeRange.Width));
5495
5496 // Bail out if the subexpr's range is as wide as the cast type.
5497 if (SubRange.Width >= OutputTypeRange.Width)
5498 return OutputTypeRange;
5499
5500 // Otherwise, we take the smaller width, and we're non-negative if
5501 // either the output type or the subexpr is.
5502 return IntRange(SubRange.Width,
5503 SubRange.NonNegative || OutputTypeRange.NonNegative);
5504 }
5505
5506 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5507 // If we can fold the condition, just take that operand.
5508 bool CondResult;
5509 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5510 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5511 : CO->getFalseExpr(),
5512 MaxWidth);
5513
5514 // Otherwise, conservatively merge.
5515 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5516 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5517 return IntRange::join(L, R);
5518 }
5519
5520 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5521 switch (BO->getOpcode()) {
5522
5523 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005524 case BO_LAnd:
5525 case BO_LOr:
5526 case BO_LT:
5527 case BO_GT:
5528 case BO_LE:
5529 case BO_GE:
5530 case BO_EQ:
5531 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005532 return IntRange::forBoolType();
5533
John McCallc3688382011-07-13 06:35:24 +00005534 // The type of the assignments is the type of the LHS, so the RHS
5535 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005536 case BO_MulAssign:
5537 case BO_DivAssign:
5538 case BO_RemAssign:
5539 case BO_AddAssign:
5540 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005541 case BO_XorAssign:
5542 case BO_OrAssign:
5543 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005544 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005545
John McCallc3688382011-07-13 06:35:24 +00005546 // Simple assignments just pass through the RHS, which will have
5547 // been coerced to the LHS type.
5548 case BO_Assign:
5549 // TODO: bitfields?
5550 return GetExprRange(C, BO->getRHS(), MaxWidth);
5551
John McCall70aa5392010-01-06 05:24:50 +00005552 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005553 case BO_PtrMemD:
5554 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005555 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005556
John McCall2ce81ad2010-01-06 22:07:33 +00005557 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005558 case BO_And:
5559 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005560 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5561 GetExprRange(C, BO->getRHS(), MaxWidth));
5562
John McCall70aa5392010-01-06 05:24:50 +00005563 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005564 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005565 // ...except that we want to treat '1 << (blah)' as logically
5566 // positive. It's an important idiom.
5567 if (IntegerLiteral *I
5568 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5569 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005570 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005571 return IntRange(R.Width, /*NonNegative*/ true);
5572 }
5573 }
5574 // fallthrough
5575
John McCalle3027922010-08-25 11:45:40 +00005576 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005577 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005578
John McCall2ce81ad2010-01-06 22:07:33 +00005579 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005580 case BO_Shr:
5581 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005582 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5583
5584 // If the shift amount is a positive constant, drop the width by
5585 // that much.
5586 llvm::APSInt shift;
5587 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5588 shift.isNonNegative()) {
5589 unsigned zext = shift.getZExtValue();
5590 if (zext >= L.Width)
5591 L.Width = (L.NonNegative ? 0 : 1);
5592 else
5593 L.Width -= zext;
5594 }
5595
5596 return L;
5597 }
5598
5599 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005600 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005601 return GetExprRange(C, BO->getRHS(), MaxWidth);
5602
John McCall2ce81ad2010-01-06 22:07:33 +00005603 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005604 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005605 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005606 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005607 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005608
John McCall51431812011-07-14 22:39:48 +00005609 // The width of a division result is mostly determined by the size
5610 // of the LHS.
5611 case BO_Div: {
5612 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005613 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005614 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5615
5616 // If the divisor is constant, use that.
5617 llvm::APSInt divisor;
5618 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5619 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5620 if (log2 >= L.Width)
5621 L.Width = (L.NonNegative ? 0 : 1);
5622 else
5623 L.Width = std::min(L.Width - log2, MaxWidth);
5624 return L;
5625 }
5626
5627 // Otherwise, just use the LHS's width.
5628 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5629 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5630 }
5631
5632 // The result of a remainder can't be larger than the result of
5633 // either side.
5634 case BO_Rem: {
5635 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005636 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005637 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5638 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5639
5640 IntRange meet = IntRange::meet(L, R);
5641 meet.Width = std::min(meet.Width, MaxWidth);
5642 return meet;
5643 }
5644
5645 // The default behavior is okay for these.
5646 case BO_Mul:
5647 case BO_Add:
5648 case BO_Xor:
5649 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005650 break;
5651 }
5652
John McCall51431812011-07-14 22:39:48 +00005653 // The default case is to treat the operation as if it were closed
5654 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005655 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5656 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5657 return IntRange::join(L, R);
5658 }
5659
5660 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5661 switch (UO->getOpcode()) {
5662 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005663 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005664 return IntRange::forBoolType();
5665
5666 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005667 case UO_Deref:
5668 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005669 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005670
5671 default:
5672 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5673 }
5674 }
5675
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005676 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5677 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5678
John McCalld25db7e2013-05-06 21:39:12 +00005679 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005680 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005681 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005682
Eli Friedmane6d33952013-07-08 20:20:06 +00005683 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005684}
John McCall263a48b2010-01-04 23:31:57 +00005685
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005686static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005687 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005688}
5689
John McCall263a48b2010-01-04 23:31:57 +00005690/// Checks whether the given value, which currently has the given
5691/// source semantics, has the same value when coerced through the
5692/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005693static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5694 const llvm::fltSemantics &Src,
5695 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005696 llvm::APFloat truncated = value;
5697
5698 bool ignored;
5699 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5700 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5701
5702 return truncated.bitwiseIsEqual(value);
5703}
5704
5705/// Checks whether the given value, which currently has the given
5706/// source semantics, has the same value when coerced through the
5707/// target semantics.
5708///
5709/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005710static bool IsSameFloatAfterCast(const APValue &value,
5711 const llvm::fltSemantics &Src,
5712 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005713 if (value.isFloat())
5714 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5715
5716 if (value.isVector()) {
5717 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5718 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5719 return false;
5720 return true;
5721 }
5722
5723 assert(value.isComplexFloat());
5724 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5725 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5726}
5727
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005728static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005729
Ted Kremenek6274be42010-09-23 21:43:44 +00005730static bool IsZero(Sema &S, Expr *E) {
5731 // Suppress cases where we are comparing against an enum constant.
5732 if (const DeclRefExpr *DR =
5733 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5734 if (isa<EnumConstantDecl>(DR->getDecl()))
5735 return false;
5736
5737 // Suppress cases where the '0' value is expanded from a macro.
5738 if (E->getLocStart().isMacroID())
5739 return false;
5740
John McCallcc7e5bf2010-05-06 08:58:33 +00005741 llvm::APSInt Value;
5742 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5743}
5744
John McCall2551c1b2010-10-06 00:25:24 +00005745static bool HasEnumType(Expr *E) {
5746 // Strip off implicit integral promotions.
5747 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005748 if (ICE->getCastKind() != CK_IntegralCast &&
5749 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005750 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005751 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005752 }
5753
5754 return E->getType()->isEnumeralType();
5755}
5756
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005757static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005758 // Disable warning in template instantiations.
5759 if (!S.ActiveTemplateInstantiations.empty())
5760 return;
5761
John McCalle3027922010-08-25 11:45:40 +00005762 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005763 if (E->isValueDependent())
5764 return;
5765
John McCalle3027922010-08-25 11:45:40 +00005766 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005767 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005768 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005769 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005770 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005771 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005772 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005773 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005774 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005775 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005776 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005777 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005778 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005779 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005780 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005781 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5782 }
5783}
5784
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005785static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005786 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005787 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005788 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005789 // Disable warning in template instantiations.
5790 if (!S.ActiveTemplateInstantiations.empty())
5791 return;
5792
Richard Trieu0f097742014-04-04 04:13:47 +00005793 // TODO: Investigate using GetExprRange() to get tighter bounds
5794 // on the bit ranges.
5795 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005796 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5797 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005798 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5799 unsigned OtherWidth = OtherRange.Width;
5800
5801 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5802
Richard Trieu560910c2012-11-14 22:50:24 +00005803 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005804 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005805 return;
5806
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005807 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005808 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005809
Richard Trieu0f097742014-04-04 04:13:47 +00005810 // Used for diagnostic printout.
5811 enum {
5812 LiteralConstant = 0,
5813 CXXBoolLiteralTrue,
5814 CXXBoolLiteralFalse
5815 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005816
Richard Trieu0f097742014-04-04 04:13:47 +00005817 if (!OtherIsBooleanType) {
5818 QualType ConstantT = Constant->getType();
5819 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005820
Richard Trieu0f097742014-04-04 04:13:47 +00005821 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5822 return;
5823 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5824 "comparison with non-integer type");
5825
5826 bool ConstantSigned = ConstantT->isSignedIntegerType();
5827 bool CommonSigned = CommonT->isSignedIntegerType();
5828
5829 bool EqualityOnly = false;
5830
5831 if (CommonSigned) {
5832 // The common type is signed, therefore no signed to unsigned conversion.
5833 if (!OtherRange.NonNegative) {
5834 // Check that the constant is representable in type OtherT.
5835 if (ConstantSigned) {
5836 if (OtherWidth >= Value.getMinSignedBits())
5837 return;
5838 } else { // !ConstantSigned
5839 if (OtherWidth >= Value.getActiveBits() + 1)
5840 return;
5841 }
5842 } else { // !OtherSigned
5843 // Check that the constant is representable in type OtherT.
5844 // Negative values are out of range.
5845 if (ConstantSigned) {
5846 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5847 return;
5848 } else { // !ConstantSigned
5849 if (OtherWidth >= Value.getActiveBits())
5850 return;
5851 }
Richard Trieu560910c2012-11-14 22:50:24 +00005852 }
Richard Trieu0f097742014-04-04 04:13:47 +00005853 } else { // !CommonSigned
5854 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005855 if (OtherWidth >= Value.getActiveBits())
5856 return;
Craig Toppercf360162014-06-18 05:13:11 +00005857 } else { // OtherSigned
5858 assert(!ConstantSigned &&
5859 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00005860 // Check to see if the constant is representable in OtherT.
5861 if (OtherWidth > Value.getActiveBits())
5862 return;
5863 // Check to see if the constant is equivalent to a negative value
5864 // cast to CommonT.
5865 if (S.Context.getIntWidth(ConstantT) ==
5866 S.Context.getIntWidth(CommonT) &&
5867 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5868 return;
5869 // The constant value rests between values that OtherT can represent
5870 // after conversion. Relational comparison still works, but equality
5871 // comparisons will be tautological.
5872 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005873 }
5874 }
Richard Trieu0f097742014-04-04 04:13:47 +00005875
5876 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5877
5878 if (op == BO_EQ || op == BO_NE) {
5879 IsTrue = op == BO_NE;
5880 } else if (EqualityOnly) {
5881 return;
5882 } else if (RhsConstant) {
5883 if (op == BO_GT || op == BO_GE)
5884 IsTrue = !PositiveConstant;
5885 else // op == BO_LT || op == BO_LE
5886 IsTrue = PositiveConstant;
5887 } else {
5888 if (op == BO_LT || op == BO_LE)
5889 IsTrue = !PositiveConstant;
5890 else // op == BO_GT || op == BO_GE
5891 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005892 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005893 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005894 // Other isKnownToHaveBooleanValue
5895 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5896 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5897 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5898
5899 static const struct LinkedConditions {
5900 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5901 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5902 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5903 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5904 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5905 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5906
5907 } TruthTable = {
5908 // Constant on LHS. | Constant on RHS. |
5909 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5910 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5911 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5912 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5913 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5914 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5915 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5916 };
5917
5918 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5919
5920 enum ConstantValue ConstVal = Zero;
5921 if (Value.isUnsigned() || Value.isNonNegative()) {
5922 if (Value == 0) {
5923 LiteralOrBoolConstant =
5924 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5925 ConstVal = Zero;
5926 } else if (Value == 1) {
5927 LiteralOrBoolConstant =
5928 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5929 ConstVal = One;
5930 } else {
5931 LiteralOrBoolConstant = LiteralConstant;
5932 ConstVal = GT_One;
5933 }
5934 } else {
5935 ConstVal = LT_Zero;
5936 }
5937
5938 CompareBoolWithConstantResult CmpRes;
5939
5940 switch (op) {
5941 case BO_LT:
5942 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5943 break;
5944 case BO_GT:
5945 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5946 break;
5947 case BO_LE:
5948 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5949 break;
5950 case BO_GE:
5951 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5952 break;
5953 case BO_EQ:
5954 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5955 break;
5956 case BO_NE:
5957 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5958 break;
5959 default:
5960 CmpRes = Unkwn;
5961 break;
5962 }
5963
5964 if (CmpRes == AFals) {
5965 IsTrue = false;
5966 } else if (CmpRes == ATrue) {
5967 IsTrue = true;
5968 } else {
5969 return;
5970 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005971 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005972
5973 // If this is a comparison to an enum constant, include that
5974 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00005975 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005976 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5977 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5978
5979 SmallString<64> PrettySourceValue;
5980 llvm::raw_svector_ostream OS(PrettySourceValue);
5981 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005982 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005983 else
5984 OS << Value;
5985
Richard Trieu0f097742014-04-04 04:13:47 +00005986 S.DiagRuntimeBehavior(
5987 E->getOperatorLoc(), E,
5988 S.PDiag(diag::warn_out_of_range_compare)
5989 << OS.str() << LiteralOrBoolConstant
5990 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5991 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005992}
5993
John McCallcc7e5bf2010-05-06 08:58:33 +00005994/// Analyze the operands of the given comparison. Implements the
5995/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005996static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005997 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5998 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005999}
John McCall263a48b2010-01-04 23:31:57 +00006000
John McCallca01b222010-01-04 23:21:16 +00006001/// \brief Implements -Wsign-compare.
6002///
Richard Trieu82402a02011-09-15 21:56:47 +00006003/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006004static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006005 // The type the comparison is being performed in.
6006 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006007
6008 // Only analyze comparison operators where both sides have been converted to
6009 // the same type.
6010 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6011 return AnalyzeImpConvsInComparison(S, E);
6012
6013 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006014 if (E->isValueDependent())
6015 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006016
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006017 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6018 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006019
6020 bool IsComparisonConstant = false;
6021
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006022 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006023 // of 'true' or 'false'.
6024 if (T->isIntegralType(S.Context)) {
6025 llvm::APSInt RHSValue;
6026 bool IsRHSIntegralLiteral =
6027 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6028 llvm::APSInt LHSValue;
6029 bool IsLHSIntegralLiteral =
6030 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6031 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6032 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6033 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6034 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6035 else
6036 IsComparisonConstant =
6037 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006038 } else if (!T->hasUnsignedIntegerRepresentation())
6039 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006040
John McCallcc7e5bf2010-05-06 08:58:33 +00006041 // We don't do anything special if this isn't an unsigned integral
6042 // comparison: we're only interested in integral comparisons, and
6043 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006044 //
6045 // We also don't care about value-dependent expressions or expressions
6046 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006047 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006048 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006049
John McCallcc7e5bf2010-05-06 08:58:33 +00006050 // Check to see if one of the (unmodified) operands is of different
6051 // signedness.
6052 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006053 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6054 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006055 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006056 signedOperand = LHS;
6057 unsignedOperand = RHS;
6058 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6059 signedOperand = RHS;
6060 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006061 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006062 CheckTrivialUnsignedComparison(S, E);
6063 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006064 }
6065
John McCallcc7e5bf2010-05-06 08:58:33 +00006066 // Otherwise, calculate the effective range of the signed operand.
6067 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006068
John McCallcc7e5bf2010-05-06 08:58:33 +00006069 // Go ahead and analyze implicit conversions in the operands. Note
6070 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006071 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6072 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006073
John McCallcc7e5bf2010-05-06 08:58:33 +00006074 // If the signed range is non-negative, -Wsign-compare won't fire,
6075 // but we should still check for comparisons which are always true
6076 // or false.
6077 if (signedRange.NonNegative)
6078 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006079
6080 // For (in)equality comparisons, if the unsigned operand is a
6081 // constant which cannot collide with a overflowed signed operand,
6082 // then reinterpreting the signed operand as unsigned will not
6083 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006084 if (E->isEqualityOp()) {
6085 unsigned comparisonWidth = S.Context.getIntWidth(T);
6086 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006087
John McCallcc7e5bf2010-05-06 08:58:33 +00006088 // We should never be unable to prove that the unsigned operand is
6089 // non-negative.
6090 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6091
6092 if (unsignedRange.Width < comparisonWidth)
6093 return;
6094 }
6095
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006096 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6097 S.PDiag(diag::warn_mixed_sign_comparison)
6098 << LHS->getType() << RHS->getType()
6099 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006100}
6101
John McCall1f425642010-11-11 03:21:53 +00006102/// Analyzes an attempt to assign the given value to a bitfield.
6103///
6104/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006105static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6106 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006107 assert(Bitfield->isBitField());
6108 if (Bitfield->isInvalidDecl())
6109 return false;
6110
John McCalldeebbcf2010-11-11 05:33:51 +00006111 // White-list bool bitfields.
6112 if (Bitfield->getType()->isBooleanType())
6113 return false;
6114
Douglas Gregor789adec2011-02-04 13:09:01 +00006115 // Ignore value- or type-dependent expressions.
6116 if (Bitfield->getBitWidth()->isValueDependent() ||
6117 Bitfield->getBitWidth()->isTypeDependent() ||
6118 Init->isValueDependent() ||
6119 Init->isTypeDependent())
6120 return false;
6121
John McCall1f425642010-11-11 03:21:53 +00006122 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6123
Richard Smith5fab0c92011-12-28 19:48:30 +00006124 llvm::APSInt Value;
6125 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006126 return false;
6127
John McCall1f425642010-11-11 03:21:53 +00006128 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006129 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006130
6131 if (OriginalWidth <= FieldWidth)
6132 return false;
6133
Eli Friedmanc267a322012-01-26 23:11:39 +00006134 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006135 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006136 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006137
Eli Friedmanc267a322012-01-26 23:11:39 +00006138 // Check whether the stored value is equal to the original value.
6139 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006140 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006141 return false;
6142
Eli Friedmanc267a322012-01-26 23:11:39 +00006143 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006144 // therefore don't strictly fit into a signed bitfield of width 1.
6145 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006146 return false;
6147
John McCall1f425642010-11-11 03:21:53 +00006148 std::string PrettyValue = Value.toString(10);
6149 std::string PrettyTrunc = TruncatedValue.toString(10);
6150
6151 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6152 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6153 << Init->getSourceRange();
6154
6155 return true;
6156}
6157
John McCalld2a53122010-11-09 23:24:47 +00006158/// Analyze the given simple or compound assignment for warning-worthy
6159/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006160static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006161 // Just recurse on the LHS.
6162 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6163
6164 // We want to recurse on the RHS as normal unless we're assigning to
6165 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006166 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006167 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006168 E->getOperatorLoc())) {
6169 // Recurse, ignoring any implicit conversions on the RHS.
6170 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6171 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006172 }
6173 }
6174
6175 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6176}
6177
John McCall263a48b2010-01-04 23:31:57 +00006178/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006179static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006180 SourceLocation CContext, unsigned diag,
6181 bool pruneControlFlow = false) {
6182 if (pruneControlFlow) {
6183 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6184 S.PDiag(diag)
6185 << SourceType << T << E->getSourceRange()
6186 << SourceRange(CContext));
6187 return;
6188 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006189 S.Diag(E->getExprLoc(), diag)
6190 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6191}
6192
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006193/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006194static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006195 SourceLocation CContext, unsigned diag,
6196 bool pruneControlFlow = false) {
6197 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006198}
6199
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006200/// Diagnose an implicit cast from a literal expression. Does not warn when the
6201/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006202void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6203 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006204 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006205 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006206 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006207 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6208 T->hasUnsignedIntegerRepresentation());
6209 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006210 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006211 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006212 return;
6213
Eli Friedman07185912013-08-29 23:44:43 +00006214 // FIXME: Force the precision of the source value down so we don't print
6215 // digits which are usually useless (we don't really care here if we
6216 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6217 // would automatically print the shortest representation, but it's a bit
6218 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006219 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006220 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6221 precision = (precision * 59 + 195) / 196;
6222 Value.toString(PrettySourceValue, precision);
6223
David Blaikie9b88cc02012-05-15 17:18:27 +00006224 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006225 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6226 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6227 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006228 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006229
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006230 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006231 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6232 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006233}
6234
John McCall18a2c2c2010-11-09 22:22:12 +00006235std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6236 if (!Range.Width) return "0";
6237
6238 llvm::APSInt ValueInRange = Value;
6239 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006240 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006241 return ValueInRange.toString(10);
6242}
6243
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006244static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6245 if (!isa<ImplicitCastExpr>(Ex))
6246 return false;
6247
6248 Expr *InnerE = Ex->IgnoreParenImpCasts();
6249 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6250 const Type *Source =
6251 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6252 if (Target->isDependentType())
6253 return false;
6254
6255 const BuiltinType *FloatCandidateBT =
6256 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6257 const Type *BoolCandidateType = ToBool ? Target : Source;
6258
6259 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6260 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6261}
6262
6263void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6264 SourceLocation CC) {
6265 unsigned NumArgs = TheCall->getNumArgs();
6266 for (unsigned i = 0; i < NumArgs; ++i) {
6267 Expr *CurrA = TheCall->getArg(i);
6268 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6269 continue;
6270
6271 bool IsSwapped = ((i > 0) &&
6272 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6273 IsSwapped |= ((i < (NumArgs - 1)) &&
6274 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6275 if (IsSwapped) {
6276 // Warn on this floating-point to bool conversion.
6277 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6278 CurrA->getType(), CC,
6279 diag::warn_impcast_floating_point_to_bool);
6280 }
6281 }
6282}
6283
Richard Trieu5b993502014-10-15 03:42:06 +00006284static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6285 SourceLocation CC) {
6286 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6287 E->getExprLoc()))
6288 return;
6289
6290 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6291 const Expr::NullPointerConstantKind NullKind =
6292 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6293 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6294 return;
6295
6296 // Return if target type is a safe conversion.
6297 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6298 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6299 return;
6300
6301 SourceLocation Loc = E->getSourceRange().getBegin();
6302
6303 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6304 if (NullKind == Expr::NPCK_GNUNull) {
6305 if (Loc.isMacroID())
6306 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6307 }
6308
6309 // Only warn if the null and context location are in the same macro expansion.
6310 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6311 return;
6312
6313 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6314 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6315 << FixItHint::CreateReplacement(Loc,
6316 S.getFixItZeroLiteralForType(T, Loc));
6317}
6318
John McCallcc7e5bf2010-05-06 08:58:33 +00006319void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006320 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006321 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006322
John McCallcc7e5bf2010-05-06 08:58:33 +00006323 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6324 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6325 if (Source == Target) return;
6326 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006327
Chandler Carruthc22845a2011-07-26 05:40:03 +00006328 // If the conversion context location is invalid don't complain. We also
6329 // don't want to emit a warning if the issue occurs from the expansion of
6330 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6331 // delay this check as long as possible. Once we detect we are in that
6332 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006333 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006334 return;
6335
Richard Trieu021baa32011-09-23 20:10:00 +00006336 // Diagnose implicit casts to bool.
6337 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6338 if (isa<StringLiteral>(E))
6339 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006340 // and expressions, for instance, assert(0 && "error here"), are
6341 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006342 return DiagnoseImpCast(S, E, T, CC,
6343 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006344 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6345 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6346 // This covers the literal expressions that evaluate to Objective-C
6347 // objects.
6348 return DiagnoseImpCast(S, E, T, CC,
6349 diag::warn_impcast_objective_c_literal_to_bool);
6350 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006351 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6352 // Warn on pointer to bool conversion that is always true.
6353 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6354 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006355 }
Richard Trieu021baa32011-09-23 20:10:00 +00006356 }
John McCall263a48b2010-01-04 23:31:57 +00006357
6358 // Strip vector types.
6359 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006360 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006361 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006362 return;
John McCallacf0ee52010-10-08 02:01:28 +00006363 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006364 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006365
6366 // If the vector cast is cast between two vectors of the same size, it is
6367 // a bitcast, not a conversion.
6368 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6369 return;
John McCall263a48b2010-01-04 23:31:57 +00006370
6371 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6372 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6373 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006374 if (auto VecTy = dyn_cast<VectorType>(Target))
6375 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006376
6377 // Strip complex types.
6378 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006379 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006380 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006381 return;
6382
John McCallacf0ee52010-10-08 02:01:28 +00006383 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006384 }
John McCall263a48b2010-01-04 23:31:57 +00006385
6386 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6387 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6388 }
6389
6390 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6391 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6392
6393 // If the source is floating point...
6394 if (SourceBT && SourceBT->isFloatingPoint()) {
6395 // ...and the target is floating point...
6396 if (TargetBT && TargetBT->isFloatingPoint()) {
6397 // ...then warn if we're dropping FP rank.
6398
6399 // Builtin FP kinds are ordered by increasing FP rank.
6400 if (SourceBT->getKind() > TargetBT->getKind()) {
6401 // Don't warn about float constants that are precisely
6402 // representable in the target type.
6403 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006404 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006405 // Value might be a float, a float vector, or a float complex.
6406 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006407 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6408 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006409 return;
6410 }
6411
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006412 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006413 return;
6414
John McCallacf0ee52010-10-08 02:01:28 +00006415 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006416 }
6417 return;
6418 }
6419
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006420 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006421 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006422 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006423 return;
6424
Chandler Carruth22c7a792011-02-17 11:05:49 +00006425 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006426 // We also want to warn on, e.g., "int i = -1.234"
6427 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6428 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6429 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6430
Chandler Carruth016ef402011-04-10 08:36:24 +00006431 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6432 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006433 } else {
6434 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6435 }
6436 }
John McCall263a48b2010-01-04 23:31:57 +00006437
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006438 // If the target is bool, warn if expr is a function or method call.
6439 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6440 isa<CallExpr>(E)) {
6441 // Check last argument of function call to see if it is an
6442 // implicit cast from a type matching the type the result
6443 // is being cast to.
6444 CallExpr *CEx = cast<CallExpr>(E);
6445 unsigned NumArgs = CEx->getNumArgs();
6446 if (NumArgs > 0) {
6447 Expr *LastA = CEx->getArg(NumArgs - 1);
6448 Expr *InnerE = LastA->IgnoreParenImpCasts();
6449 const Type *InnerType =
6450 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6451 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6452 // Warn on this floating-point to bool conversion
6453 DiagnoseImpCast(S, E, T, CC,
6454 diag::warn_impcast_floating_point_to_bool);
6455 }
6456 }
6457 }
John McCall263a48b2010-01-04 23:31:57 +00006458 return;
6459 }
6460
Richard Trieu5b993502014-10-15 03:42:06 +00006461 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006462
David Blaikie9366d2b2012-06-19 21:19:06 +00006463 if (!Source->isIntegerType() || !Target->isIntegerType())
6464 return;
6465
David Blaikie7555b6a2012-05-15 16:56:36 +00006466 // TODO: remove this early return once the false positives for constant->bool
6467 // in templates, macros, etc, are reduced or removed.
6468 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6469 return;
6470
John McCallcc7e5bf2010-05-06 08:58:33 +00006471 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006472 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006473
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006474 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006475 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006476 // TODO: this should happen for bitfield stores, too.
6477 llvm::APSInt Value(32);
6478 if (E->isIntegerConstantExpr(Value, S.Context)) {
6479 if (S.SourceMgr.isInSystemMacro(CC))
6480 return;
6481
John McCall18a2c2c2010-11-09 22:22:12 +00006482 std::string PrettySourceValue = Value.toString(10);
6483 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006484
Ted Kremenek33ba9952011-10-22 02:37:33 +00006485 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6486 S.PDiag(diag::warn_impcast_integer_precision_constant)
6487 << PrettySourceValue << PrettyTargetValue
6488 << E->getType() << T << E->getSourceRange()
6489 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006490 return;
6491 }
6492
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006493 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6494 if (S.SourceMgr.isInSystemMacro(CC))
6495 return;
6496
David Blaikie9455da02012-04-12 22:40:54 +00006497 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006498 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6499 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006500 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006501 }
6502
6503 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6504 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6505 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006506
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006507 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006508 return;
6509
John McCallcc7e5bf2010-05-06 08:58:33 +00006510 unsigned DiagID = diag::warn_impcast_integer_sign;
6511
6512 // Traditionally, gcc has warned about this under -Wsign-compare.
6513 // We also want to warn about it in -Wconversion.
6514 // So if -Wconversion is off, use a completely identical diagnostic
6515 // in the sign-compare group.
6516 // The conditional-checking code will
6517 if (ICContext) {
6518 DiagID = diag::warn_impcast_integer_sign_conditional;
6519 *ICContext = true;
6520 }
6521
John McCallacf0ee52010-10-08 02:01:28 +00006522 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006523 }
6524
Douglas Gregora78f1932011-02-22 02:45:07 +00006525 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006526 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6527 // type, to give us better diagnostics.
6528 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006529 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006530 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6531 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6532 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6533 SourceType = S.Context.getTypeDeclType(Enum);
6534 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6535 }
6536 }
6537
Douglas Gregora78f1932011-02-22 02:45:07 +00006538 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6539 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006540 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6541 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006542 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006543 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006544 return;
6545
Douglas Gregor364f7db2011-03-12 00:14:31 +00006546 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006547 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006548 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006549
John McCall263a48b2010-01-04 23:31:57 +00006550 return;
6551}
6552
David Blaikie18e9ac72012-05-15 21:57:38 +00006553void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6554 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006555
6556void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006557 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006558 E = E->IgnoreParenImpCasts();
6559
6560 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006561 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006562
John McCallacf0ee52010-10-08 02:01:28 +00006563 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006564 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006565 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006566 return;
6567}
6568
David Blaikie18e9ac72012-05-15 21:57:38 +00006569void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6570 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006571 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006572
6573 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006574 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6575 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006576
6577 // If -Wconversion would have warned about either of the candidates
6578 // for a signedness conversion to the context type...
6579 if (!Suspicious) return;
6580
6581 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006582 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006583 return;
6584
John McCallcc7e5bf2010-05-06 08:58:33 +00006585 // ...then check whether it would have warned about either of the
6586 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006587 if (E->getType() == T) return;
6588
6589 Suspicious = false;
6590 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6591 E->getType(), CC, &Suspicious);
6592 if (!Suspicious)
6593 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006594 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006595}
6596
Richard Trieu65724892014-11-15 06:37:39 +00006597/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6598/// Input argument E is a logical expression.
6599static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6600 if (S.getLangOpts().Bool)
6601 return;
6602 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6603}
6604
John McCallcc7e5bf2010-05-06 08:58:33 +00006605/// AnalyzeImplicitConversions - Find and report any interesting
6606/// implicit conversions in the given expression. There are a couple
6607/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006608void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006609 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006610 Expr *E = OrigE->IgnoreParenImpCasts();
6611
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006612 if (E->isTypeDependent() || E->isValueDependent())
6613 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006614
John McCallcc7e5bf2010-05-06 08:58:33 +00006615 // For conditional operators, we analyze the arguments as if they
6616 // were being fed directly into the output.
6617 if (isa<ConditionalOperator>(E)) {
6618 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006619 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006620 return;
6621 }
6622
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006623 // Check implicit argument conversions for function calls.
6624 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6625 CheckImplicitArgumentConversions(S, Call, CC);
6626
John McCallcc7e5bf2010-05-06 08:58:33 +00006627 // Go ahead and check any implicit conversions we might have skipped.
6628 // The non-canonical typecheck is just an optimization;
6629 // CheckImplicitConversion will filter out dead implicit conversions.
6630 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006631 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006632
6633 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006634
6635 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006636 if (POE->getResultExpr())
6637 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006638 }
6639
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006640 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6641 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6642
John McCallcc7e5bf2010-05-06 08:58:33 +00006643 // Skip past explicit casts.
6644 if (isa<ExplicitCastExpr>(E)) {
6645 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006646 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006647 }
6648
John McCalld2a53122010-11-09 23:24:47 +00006649 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6650 // Do a somewhat different check with comparison operators.
6651 if (BO->isComparisonOp())
6652 return AnalyzeComparison(S, BO);
6653
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006654 // And with simple assignments.
6655 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006656 return AnalyzeAssignment(S, BO);
6657 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006658
6659 // These break the otherwise-useful invariant below. Fortunately,
6660 // we don't really need to recurse into them, because any internal
6661 // expressions should have been analyzed already when they were
6662 // built into statements.
6663 if (isa<StmtExpr>(E)) return;
6664
6665 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006666 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006667
6668 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006669 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006670 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006671 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006672 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006673 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006674 if (!ChildExpr)
6675 continue;
6676
Richard Trieu955231d2014-01-25 01:10:35 +00006677 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006678 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006679 // Ignore checking string literals that are in logical and operators.
6680 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006681 continue;
6682 AnalyzeImplicitConversions(S, ChildExpr, CC);
6683 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006684
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006685 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006686 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6687 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
6688 ::CheckBoolLikeConversion(S, SubExpr, SubExpr->getExprLoc());
6689
6690 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6691 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
6692 ::CheckBoolLikeConversion(S, SubExpr, SubExpr->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006693 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006694
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006695 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6696 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00006697 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006698}
6699
6700} // end anonymous namespace
6701
Richard Trieu3bb8b562014-02-26 02:36:06 +00006702enum {
6703 AddressOf,
6704 FunctionPointer,
6705 ArrayPointer
6706};
6707
Richard Trieuc1888e02014-06-28 23:25:37 +00006708// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6709// Returns true when emitting a warning about taking the address of a reference.
6710static bool CheckForReference(Sema &SemaRef, const Expr *E,
6711 PartialDiagnostic PD) {
6712 E = E->IgnoreParenImpCasts();
6713
6714 const FunctionDecl *FD = nullptr;
6715
6716 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6717 if (!DRE->getDecl()->getType()->isReferenceType())
6718 return false;
6719 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6720 if (!M->getMemberDecl()->getType()->isReferenceType())
6721 return false;
6722 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6723 if (!Call->getCallReturnType()->isReferenceType())
6724 return false;
6725 FD = Call->getDirectCallee();
6726 } else {
6727 return false;
6728 }
6729
6730 SemaRef.Diag(E->getExprLoc(), PD);
6731
6732 // If possible, point to location of function.
6733 if (FD) {
6734 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6735 }
6736
6737 return true;
6738}
6739
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006740// Returns true if the SourceLocation is expanded from any macro body.
6741// Returns false if the SourceLocation is invalid, is from not in a macro
6742// expansion, or is from expanded from a top-level macro argument.
6743static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6744 if (Loc.isInvalid())
6745 return false;
6746
6747 while (Loc.isMacroID()) {
6748 if (SM.isMacroBodyExpansion(Loc))
6749 return true;
6750 Loc = SM.getImmediateMacroCallerLoc(Loc);
6751 }
6752
6753 return false;
6754}
6755
Richard Trieu3bb8b562014-02-26 02:36:06 +00006756/// \brief Diagnose pointers that are always non-null.
6757/// \param E the expression containing the pointer
6758/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6759/// compared to a null pointer
6760/// \param IsEqual True when the comparison is equal to a null pointer
6761/// \param Range Extra SourceRange to highlight in the diagnostic
6762void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6763 Expr::NullPointerConstantKind NullKind,
6764 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006765 if (!E)
6766 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006767
6768 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006769 if (E->getExprLoc().isMacroID()) {
6770 const SourceManager &SM = getSourceManager();
6771 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6772 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006773 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006774 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006775 E = E->IgnoreImpCasts();
6776
6777 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6778
Richard Trieuf7432752014-06-06 21:39:26 +00006779 if (isa<CXXThisExpr>(E)) {
6780 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6781 : diag::warn_this_bool_conversion;
6782 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6783 return;
6784 }
6785
Richard Trieu3bb8b562014-02-26 02:36:06 +00006786 bool IsAddressOf = false;
6787
6788 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6789 if (UO->getOpcode() != UO_AddrOf)
6790 return;
6791 IsAddressOf = true;
6792 E = UO->getSubExpr();
6793 }
6794
Richard Trieuc1888e02014-06-28 23:25:37 +00006795 if (IsAddressOf) {
6796 unsigned DiagID = IsCompare
6797 ? diag::warn_address_of_reference_null_compare
6798 : diag::warn_address_of_reference_bool_conversion;
6799 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6800 << IsEqual;
6801 if (CheckForReference(*this, E, PD)) {
6802 return;
6803 }
6804 }
6805
Richard Trieu3bb8b562014-02-26 02:36:06 +00006806 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006807 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006808 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6809 D = R->getDecl();
6810 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6811 D = M->getMemberDecl();
6812 }
6813
6814 // Weak Decls can be null.
6815 if (!D || D->isWeak())
6816 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006817
6818 // Check for parameter decl with nonnull attribute
6819 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6820 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6821 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6822 unsigned NumArgs = FD->getNumParams();
6823 llvm::SmallBitVector AttrNonNull(NumArgs);
6824 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6825 if (!NonNull->args_size()) {
6826 AttrNonNull.set(0, NumArgs);
6827 break;
6828 }
6829 for (unsigned Val : NonNull->args()) {
6830 if (Val >= NumArgs)
6831 continue;
6832 AttrNonNull.set(Val);
6833 }
6834 }
6835 if (!AttrNonNull.empty())
6836 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00006837 if (FD->getParamDecl(i) == PV &&
6838 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006839 std::string Str;
6840 llvm::raw_string_ostream S(Str);
6841 E->printPretty(S, nullptr, getPrintingPolicy());
6842 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
6843 : diag::warn_cast_nonnull_to_bool;
6844 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
6845 << Range << IsEqual;
6846 return;
6847 }
6848 }
6849 }
6850
Richard Trieu3bb8b562014-02-26 02:36:06 +00006851 QualType T = D->getType();
6852 const bool IsArray = T->isArrayType();
6853 const bool IsFunction = T->isFunctionType();
6854
Richard Trieuc1888e02014-06-28 23:25:37 +00006855 // Address of function is used to silence the function warning.
6856 if (IsAddressOf && IsFunction) {
6857 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006858 }
6859
6860 // Found nothing.
6861 if (!IsAddressOf && !IsFunction && !IsArray)
6862 return;
6863
6864 // Pretty print the expression for the diagnostic.
6865 std::string Str;
6866 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006867 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006868
6869 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6870 : diag::warn_impcast_pointer_to_bool;
6871 unsigned DiagType;
6872 if (IsAddressOf)
6873 DiagType = AddressOf;
6874 else if (IsFunction)
6875 DiagType = FunctionPointer;
6876 else if (IsArray)
6877 DiagType = ArrayPointer;
6878 else
6879 llvm_unreachable("Could not determine diagnostic.");
6880 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6881 << Range << IsEqual;
6882
6883 if (!IsFunction)
6884 return;
6885
6886 // Suggest '&' to silence the function warning.
6887 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6888 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6889
6890 // Check to see if '()' fixit should be emitted.
6891 QualType ReturnType;
6892 UnresolvedSet<4> NonTemplateOverloads;
6893 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6894 if (ReturnType.isNull())
6895 return;
6896
6897 if (IsCompare) {
6898 // There are two cases here. If there is null constant, the only suggest
6899 // for a pointer return type. If the null is 0, then suggest if the return
6900 // type is a pointer or an integer type.
6901 if (!ReturnType->isPointerType()) {
6902 if (NullKind == Expr::NPCK_ZeroExpression ||
6903 NullKind == Expr::NPCK_ZeroLiteral) {
6904 if (!ReturnType->isIntegerType())
6905 return;
6906 } else {
6907 return;
6908 }
6909 }
6910 } else { // !IsCompare
6911 // For function to bool, only suggest if the function pointer has bool
6912 // return type.
6913 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6914 return;
6915 }
6916 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006917 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006918}
6919
6920
John McCallcc7e5bf2010-05-06 08:58:33 +00006921/// Diagnoses "dangerous" implicit conversions within the given
6922/// expression (which is a full expression). Implements -Wconversion
6923/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006924///
6925/// \param CC the "context" location of the implicit conversion, i.e.
6926/// the most location of the syntactic entity requiring the implicit
6927/// conversion
6928void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006929 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006930 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006931 return;
6932
6933 // Don't diagnose for value- or type-dependent expressions.
6934 if (E->isTypeDependent() || E->isValueDependent())
6935 return;
6936
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006937 // Check for array bounds violations in cases where the check isn't triggered
6938 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6939 // ArraySubscriptExpr is on the RHS of a variable initialization.
6940 CheckArrayAccess(E);
6941
John McCallacf0ee52010-10-08 02:01:28 +00006942 // This is not the right CC for (e.g.) a variable initialization.
6943 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006944}
6945
Richard Trieu65724892014-11-15 06:37:39 +00006946/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6947/// Input argument E is a logical expression.
6948void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
6949 ::CheckBoolLikeConversion(*this, E, CC);
6950}
6951
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006952/// Diagnose when expression is an integer constant expression and its evaluation
6953/// results in integer overflow
6954void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00006955 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
6956 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006957}
6958
Richard Smithc406cb72013-01-17 01:17:56 +00006959namespace {
6960/// \brief Visitor for expressions which looks for unsequenced operations on the
6961/// same object.
6962class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006963 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6964
Richard Smithc406cb72013-01-17 01:17:56 +00006965 /// \brief A tree of sequenced regions within an expression. Two regions are
6966 /// unsequenced if one is an ancestor or a descendent of the other. When we
6967 /// finish processing an expression with sequencing, such as a comma
6968 /// expression, we fold its tree nodes into its parent, since they are
6969 /// unsequenced with respect to nodes we will visit later.
6970 class SequenceTree {
6971 struct Value {
6972 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6973 unsigned Parent : 31;
6974 bool Merged : 1;
6975 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006976 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006977
6978 public:
6979 /// \brief A region within an expression which may be sequenced with respect
6980 /// to some other region.
6981 class Seq {
6982 explicit Seq(unsigned N) : Index(N) {}
6983 unsigned Index;
6984 friend class SequenceTree;
6985 public:
6986 Seq() : Index(0) {}
6987 };
6988
6989 SequenceTree() { Values.push_back(Value(0)); }
6990 Seq root() const { return Seq(0); }
6991
6992 /// \brief Create a new sequence of operations, which is an unsequenced
6993 /// subset of \p Parent. This sequence of operations is sequenced with
6994 /// respect to other children of \p Parent.
6995 Seq allocate(Seq Parent) {
6996 Values.push_back(Value(Parent.Index));
6997 return Seq(Values.size() - 1);
6998 }
6999
7000 /// \brief Merge a sequence of operations into its parent.
7001 void merge(Seq S) {
7002 Values[S.Index].Merged = true;
7003 }
7004
7005 /// \brief Determine whether two operations are unsequenced. This operation
7006 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7007 /// should have been merged into its parent as appropriate.
7008 bool isUnsequenced(Seq Cur, Seq Old) {
7009 unsigned C = representative(Cur.Index);
7010 unsigned Target = representative(Old.Index);
7011 while (C >= Target) {
7012 if (C == Target)
7013 return true;
7014 C = Values[C].Parent;
7015 }
7016 return false;
7017 }
7018
7019 private:
7020 /// \brief Pick a representative for a sequence.
7021 unsigned representative(unsigned K) {
7022 if (Values[K].Merged)
7023 // Perform path compression as we go.
7024 return Values[K].Parent = representative(Values[K].Parent);
7025 return K;
7026 }
7027 };
7028
7029 /// An object for which we can track unsequenced uses.
7030 typedef NamedDecl *Object;
7031
7032 /// Different flavors of object usage which we track. We only track the
7033 /// least-sequenced usage of each kind.
7034 enum UsageKind {
7035 /// A read of an object. Multiple unsequenced reads are OK.
7036 UK_Use,
7037 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007038 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007039 UK_ModAsValue,
7040 /// A modification of an object which is not sequenced before the value
7041 /// computation of the expression, such as n++.
7042 UK_ModAsSideEffect,
7043
7044 UK_Count = UK_ModAsSideEffect + 1
7045 };
7046
7047 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007048 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007049 Expr *Use;
7050 SequenceTree::Seq Seq;
7051 };
7052
7053 struct UsageInfo {
7054 UsageInfo() : Diagnosed(false) {}
7055 Usage Uses[UK_Count];
7056 /// Have we issued a diagnostic for this variable already?
7057 bool Diagnosed;
7058 };
7059 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7060
7061 Sema &SemaRef;
7062 /// Sequenced regions within the expression.
7063 SequenceTree Tree;
7064 /// Declaration modifications and references which we have seen.
7065 UsageInfoMap UsageMap;
7066 /// The region we are currently within.
7067 SequenceTree::Seq Region;
7068 /// Filled in with declarations which were modified as a side-effect
7069 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007070 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007071 /// Expressions to check later. We defer checking these to reduce
7072 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007073 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007074
7075 /// RAII object wrapping the visitation of a sequenced subexpression of an
7076 /// expression. At the end of this process, the side-effects of the evaluation
7077 /// become sequenced with respect to the value computation of the result, so
7078 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7079 /// UK_ModAsValue.
7080 struct SequencedSubexpression {
7081 SequencedSubexpression(SequenceChecker &Self)
7082 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7083 Self.ModAsSideEffect = &ModAsSideEffect;
7084 }
7085 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007086 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7087 MI != ME; ++MI) {
7088 UsageInfo &U = Self.UsageMap[MI->first];
7089 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7090 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7091 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007092 }
7093 Self.ModAsSideEffect = OldModAsSideEffect;
7094 }
7095
7096 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007097 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7098 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007099 };
7100
Richard Smith40238f02013-06-20 22:21:56 +00007101 /// RAII object wrapping the visitation of a subexpression which we might
7102 /// choose to evaluate as a constant. If any subexpression is evaluated and
7103 /// found to be non-constant, this allows us to suppress the evaluation of
7104 /// the outer expression.
7105 class EvaluationTracker {
7106 public:
7107 EvaluationTracker(SequenceChecker &Self)
7108 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7109 Self.EvalTracker = this;
7110 }
7111 ~EvaluationTracker() {
7112 Self.EvalTracker = Prev;
7113 if (Prev)
7114 Prev->EvalOK &= EvalOK;
7115 }
7116
7117 bool evaluate(const Expr *E, bool &Result) {
7118 if (!EvalOK || E->isValueDependent())
7119 return false;
7120 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7121 return EvalOK;
7122 }
7123
7124 private:
7125 SequenceChecker &Self;
7126 EvaluationTracker *Prev;
7127 bool EvalOK;
7128 } *EvalTracker;
7129
Richard Smithc406cb72013-01-17 01:17:56 +00007130 /// \brief Find the object which is produced by the specified expression,
7131 /// if any.
7132 Object getObject(Expr *E, bool Mod) const {
7133 E = E->IgnoreParenCasts();
7134 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7135 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7136 return getObject(UO->getSubExpr(), Mod);
7137 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7138 if (BO->getOpcode() == BO_Comma)
7139 return getObject(BO->getRHS(), Mod);
7140 if (Mod && BO->isAssignmentOp())
7141 return getObject(BO->getLHS(), Mod);
7142 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7143 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7144 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7145 return ME->getMemberDecl();
7146 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7147 // FIXME: If this is a reference, map through to its value.
7148 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007149 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007150 }
7151
7152 /// \brief Note that an object was modified or used by an expression.
7153 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7154 Usage &U = UI.Uses[UK];
7155 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7156 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7157 ModAsSideEffect->push_back(std::make_pair(O, U));
7158 U.Use = Ref;
7159 U.Seq = Region;
7160 }
7161 }
7162 /// \brief Check whether a modification or use conflicts with a prior usage.
7163 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7164 bool IsModMod) {
7165 if (UI.Diagnosed)
7166 return;
7167
7168 const Usage &U = UI.Uses[OtherKind];
7169 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7170 return;
7171
7172 Expr *Mod = U.Use;
7173 Expr *ModOrUse = Ref;
7174 if (OtherKind == UK_Use)
7175 std::swap(Mod, ModOrUse);
7176
7177 SemaRef.Diag(Mod->getExprLoc(),
7178 IsModMod ? diag::warn_unsequenced_mod_mod
7179 : diag::warn_unsequenced_mod_use)
7180 << O << SourceRange(ModOrUse->getExprLoc());
7181 UI.Diagnosed = true;
7182 }
7183
7184 void notePreUse(Object O, Expr *Use) {
7185 UsageInfo &U = UsageMap[O];
7186 // Uses conflict with other modifications.
7187 checkUsage(O, U, Use, UK_ModAsValue, false);
7188 }
7189 void notePostUse(Object O, Expr *Use) {
7190 UsageInfo &U = UsageMap[O];
7191 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7192 addUsage(U, O, Use, UK_Use);
7193 }
7194
7195 void notePreMod(Object O, Expr *Mod) {
7196 UsageInfo &U = UsageMap[O];
7197 // Modifications conflict with other modifications and with uses.
7198 checkUsage(O, U, Mod, UK_ModAsValue, true);
7199 checkUsage(O, U, Mod, UK_Use, false);
7200 }
7201 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7202 UsageInfo &U = UsageMap[O];
7203 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7204 addUsage(U, O, Use, UK);
7205 }
7206
7207public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007208 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007209 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7210 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007211 Visit(E);
7212 }
7213
7214 void VisitStmt(Stmt *S) {
7215 // Skip all statements which aren't expressions for now.
7216 }
7217
7218 void VisitExpr(Expr *E) {
7219 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007220 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007221 }
7222
7223 void VisitCastExpr(CastExpr *E) {
7224 Object O = Object();
7225 if (E->getCastKind() == CK_LValueToRValue)
7226 O = getObject(E->getSubExpr(), false);
7227
7228 if (O)
7229 notePreUse(O, E);
7230 VisitExpr(E);
7231 if (O)
7232 notePostUse(O, E);
7233 }
7234
7235 void VisitBinComma(BinaryOperator *BO) {
7236 // C++11 [expr.comma]p1:
7237 // Every value computation and side effect associated with the left
7238 // expression is sequenced before every value computation and side
7239 // effect associated with the right expression.
7240 SequenceTree::Seq LHS = Tree.allocate(Region);
7241 SequenceTree::Seq RHS = Tree.allocate(Region);
7242 SequenceTree::Seq OldRegion = Region;
7243
7244 {
7245 SequencedSubexpression SeqLHS(*this);
7246 Region = LHS;
7247 Visit(BO->getLHS());
7248 }
7249
7250 Region = RHS;
7251 Visit(BO->getRHS());
7252
7253 Region = OldRegion;
7254
7255 // Forget that LHS and RHS are sequenced. They are both unsequenced
7256 // with respect to other stuff.
7257 Tree.merge(LHS);
7258 Tree.merge(RHS);
7259 }
7260
7261 void VisitBinAssign(BinaryOperator *BO) {
7262 // The modification is sequenced after the value computation of the LHS
7263 // and RHS, so check it before inspecting the operands and update the
7264 // map afterwards.
7265 Object O = getObject(BO->getLHS(), true);
7266 if (!O)
7267 return VisitExpr(BO);
7268
7269 notePreMod(O, BO);
7270
7271 // C++11 [expr.ass]p7:
7272 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7273 // only once.
7274 //
7275 // Therefore, for a compound assignment operator, O is considered used
7276 // everywhere except within the evaluation of E1 itself.
7277 if (isa<CompoundAssignOperator>(BO))
7278 notePreUse(O, BO);
7279
7280 Visit(BO->getLHS());
7281
7282 if (isa<CompoundAssignOperator>(BO))
7283 notePostUse(O, BO);
7284
7285 Visit(BO->getRHS());
7286
Richard Smith83e37bee2013-06-26 23:16:51 +00007287 // C++11 [expr.ass]p1:
7288 // the assignment is sequenced [...] before the value computation of the
7289 // assignment expression.
7290 // C11 6.5.16/3 has no such rule.
7291 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7292 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007293 }
7294 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7295 VisitBinAssign(CAO);
7296 }
7297
7298 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7299 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7300 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7301 Object O = getObject(UO->getSubExpr(), true);
7302 if (!O)
7303 return VisitExpr(UO);
7304
7305 notePreMod(O, UO);
7306 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007307 // C++11 [expr.pre.incr]p1:
7308 // the expression ++x is equivalent to x+=1
7309 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7310 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007311 }
7312
7313 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7314 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7315 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7316 Object O = getObject(UO->getSubExpr(), true);
7317 if (!O)
7318 return VisitExpr(UO);
7319
7320 notePreMod(O, UO);
7321 Visit(UO->getSubExpr());
7322 notePostMod(O, UO, UK_ModAsSideEffect);
7323 }
7324
7325 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7326 void VisitBinLOr(BinaryOperator *BO) {
7327 // The side-effects of the LHS of an '&&' are sequenced before the
7328 // value computation of the RHS, and hence before the value computation
7329 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7330 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007331 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007332 {
7333 SequencedSubexpression Sequenced(*this);
7334 Visit(BO->getLHS());
7335 }
7336
7337 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007338 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007339 if (!Result)
7340 Visit(BO->getRHS());
7341 } else {
7342 // Check for unsequenced operations in the RHS, treating it as an
7343 // entirely separate evaluation.
7344 //
7345 // FIXME: If there are operations in the RHS which are unsequenced
7346 // with respect to operations outside the RHS, and those operations
7347 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007348 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007349 }
Richard Smithc406cb72013-01-17 01:17:56 +00007350 }
7351 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007352 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007353 {
7354 SequencedSubexpression Sequenced(*this);
7355 Visit(BO->getLHS());
7356 }
7357
7358 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007359 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007360 if (Result)
7361 Visit(BO->getRHS());
7362 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007363 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007364 }
Richard Smithc406cb72013-01-17 01:17:56 +00007365 }
7366
7367 // Only visit the condition, unless we can be sure which subexpression will
7368 // be chosen.
7369 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007370 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007371 {
7372 SequencedSubexpression Sequenced(*this);
7373 Visit(CO->getCond());
7374 }
Richard Smithc406cb72013-01-17 01:17:56 +00007375
7376 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007377 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007378 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007379 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007380 WorkList.push_back(CO->getTrueExpr());
7381 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007382 }
Richard Smithc406cb72013-01-17 01:17:56 +00007383 }
7384
Richard Smithe3dbfe02013-06-30 10:40:20 +00007385 void VisitCallExpr(CallExpr *CE) {
7386 // C++11 [intro.execution]p15:
7387 // When calling a function [...], every value computation and side effect
7388 // associated with any argument expression, or with the postfix expression
7389 // designating the called function, is sequenced before execution of every
7390 // expression or statement in the body of the function [and thus before
7391 // the value computation of its result].
7392 SequencedSubexpression Sequenced(*this);
7393 Base::VisitCallExpr(CE);
7394
7395 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7396 }
7397
Richard Smithc406cb72013-01-17 01:17:56 +00007398 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007399 // This is a call, so all subexpressions are sequenced before the result.
7400 SequencedSubexpression Sequenced(*this);
7401
Richard Smithc406cb72013-01-17 01:17:56 +00007402 if (!CCE->isListInitialization())
7403 return VisitExpr(CCE);
7404
7405 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007406 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007407 SequenceTree::Seq Parent = Region;
7408 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7409 E = CCE->arg_end();
7410 I != E; ++I) {
7411 Region = Tree.allocate(Parent);
7412 Elts.push_back(Region);
7413 Visit(*I);
7414 }
7415
7416 // Forget that the initializers are sequenced.
7417 Region = Parent;
7418 for (unsigned I = 0; I < Elts.size(); ++I)
7419 Tree.merge(Elts[I]);
7420 }
7421
7422 void VisitInitListExpr(InitListExpr *ILE) {
7423 if (!SemaRef.getLangOpts().CPlusPlus11)
7424 return VisitExpr(ILE);
7425
7426 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007427 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007428 SequenceTree::Seq Parent = Region;
7429 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7430 Expr *E = ILE->getInit(I);
7431 if (!E) continue;
7432 Region = Tree.allocate(Parent);
7433 Elts.push_back(Region);
7434 Visit(E);
7435 }
7436
7437 // Forget that the initializers are sequenced.
7438 Region = Parent;
7439 for (unsigned I = 0; I < Elts.size(); ++I)
7440 Tree.merge(Elts[I]);
7441 }
7442};
7443}
7444
7445void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007446 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007447 WorkList.push_back(E);
7448 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007449 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007450 SequenceChecker(*this, Item, WorkList);
7451 }
Richard Smithc406cb72013-01-17 01:17:56 +00007452}
7453
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007454void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7455 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007456 CheckImplicitConversions(E, CheckLoc);
7457 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007458 if (!IsConstexpr && !E->isValueDependent())
7459 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007460}
7461
John McCall1f425642010-11-11 03:21:53 +00007462void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7463 FieldDecl *BitField,
7464 Expr *Init) {
7465 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7466}
7467
Mike Stump0c2ec772010-01-21 03:59:47 +00007468/// CheckParmsForFunctionDef - Check that the parameters of the given
7469/// function are appropriate for the definition of a function. This
7470/// takes care of any checks that cannot be performed on the
7471/// declaration itself, e.g., that the types of each of the function
7472/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007473bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7474 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007475 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007476 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007477 for (; P != PEnd; ++P) {
7478 ParmVarDecl *Param = *P;
7479
Mike Stump0c2ec772010-01-21 03:59:47 +00007480 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7481 // function declarator that is part of a function definition of
7482 // that function shall not have incomplete type.
7483 //
7484 // This is also C++ [dcl.fct]p6.
7485 if (!Param->isInvalidDecl() &&
7486 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007487 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007488 Param->setInvalidDecl();
7489 HasInvalidParm = true;
7490 }
7491
7492 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7493 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007494 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007495 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007496 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007497 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007498 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007499
7500 // C99 6.7.5.3p12:
7501 // If the function declarator is not part of a definition of that
7502 // function, parameters may have incomplete type and may use the [*]
7503 // notation in their sequences of declarator specifiers to specify
7504 // variable length array types.
7505 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007506 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007507 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007508 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007509 // information is added for it.
7510 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007511 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007512 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007513 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007514 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007515
7516 // MSVC destroys objects passed by value in the callee. Therefore a
7517 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007518 // object's destructor. However, we don't perform any direct access check
7519 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007520 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7521 .getCXXABI()
7522 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007523 if (!Param->isInvalidDecl()) {
7524 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7525 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7526 if (!ClassDecl->isInvalidDecl() &&
7527 !ClassDecl->hasIrrelevantDestructor() &&
7528 !ClassDecl->isDependentContext()) {
7529 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7530 MarkFunctionReferenced(Param->getLocation(), Destructor);
7531 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7532 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007533 }
7534 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007535 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007536 }
7537
7538 return HasInvalidParm;
7539}
John McCall2b5c1b22010-08-12 21:44:57 +00007540
7541/// CheckCastAlign - Implements -Wcast-align, which warns when a
7542/// pointer cast increases the alignment requirements.
7543void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7544 // This is actually a lot of work to potentially be doing on every
7545 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007546 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007547 return;
7548
7549 // Ignore dependent types.
7550 if (T->isDependentType() || Op->getType()->isDependentType())
7551 return;
7552
7553 // Require that the destination be a pointer type.
7554 const PointerType *DestPtr = T->getAs<PointerType>();
7555 if (!DestPtr) return;
7556
7557 // If the destination has alignment 1, we're done.
7558 QualType DestPointee = DestPtr->getPointeeType();
7559 if (DestPointee->isIncompleteType()) return;
7560 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7561 if (DestAlign.isOne()) return;
7562
7563 // Require that the source be a pointer type.
7564 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7565 if (!SrcPtr) return;
7566 QualType SrcPointee = SrcPtr->getPointeeType();
7567
7568 // Whitelist casts from cv void*. We already implicitly
7569 // whitelisted casts to cv void*, since they have alignment 1.
7570 // Also whitelist casts involving incomplete types, which implicitly
7571 // includes 'void'.
7572 if (SrcPointee->isIncompleteType()) return;
7573
7574 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7575 if (SrcAlign >= DestAlign) return;
7576
7577 Diag(TRange.getBegin(), diag::warn_cast_align)
7578 << Op->getType() << T
7579 << static_cast<unsigned>(SrcAlign.getQuantity())
7580 << static_cast<unsigned>(DestAlign.getQuantity())
7581 << TRange << Op->getSourceRange();
7582}
7583
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007584static const Type* getElementType(const Expr *BaseExpr) {
7585 const Type* EltType = BaseExpr->getType().getTypePtr();
7586 if (EltType->isAnyPointerType())
7587 return EltType->getPointeeType().getTypePtr();
7588 else if (EltType->isArrayType())
7589 return EltType->getBaseElementTypeUnsafe();
7590 return EltType;
7591}
7592
Chandler Carruth28389f02011-08-05 09:10:50 +00007593/// \brief Check whether this array fits the idiom of a size-one tail padded
7594/// array member of a struct.
7595///
7596/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7597/// commonly used to emulate flexible arrays in C89 code.
7598static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7599 const NamedDecl *ND) {
7600 if (Size != 1 || !ND) return false;
7601
7602 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7603 if (!FD) return false;
7604
7605 // Don't consider sizes resulting from macro expansions or template argument
7606 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007607
7608 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007609 while (TInfo) {
7610 TypeLoc TL = TInfo->getTypeLoc();
7611 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007612 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7613 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007614 TInfo = TDL->getTypeSourceInfo();
7615 continue;
7616 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007617 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7618 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007619 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7620 return false;
7621 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007622 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007623 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007624
7625 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007626 if (!RD) return false;
7627 if (RD->isUnion()) return false;
7628 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7629 if (!CRD->isStandardLayout()) return false;
7630 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007631
Benjamin Kramer8c543672011-08-06 03:04:42 +00007632 // See if this is the last field decl in the record.
7633 const Decl *D = FD;
7634 while ((D = D->getNextDeclInContext()))
7635 if (isa<FieldDecl>(D))
7636 return false;
7637 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007638}
7639
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007640void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007641 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007642 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007643 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007644 if (IndexExpr->isValueDependent())
7645 return;
7646
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007647 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007648 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007649 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007650 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007651 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007652 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007653
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007654 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007655 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007656 return;
Richard Smith13f67182011-12-16 19:31:14 +00007657 if (IndexNegated)
7658 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007659
Craig Topperc3ec1492014-05-26 06:22:03 +00007660 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007661 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7662 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007663 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007664 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007665
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007666 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007667 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007668 if (!size.isStrictlyPositive())
7669 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007670
7671 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007672 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007673 // Make sure we're comparing apples to apples when comparing index to size
7674 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7675 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007676 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007677 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007678 if (ptrarith_typesize != array_typesize) {
7679 // There's a cast to a different size type involved
7680 uint64_t ratio = array_typesize / ptrarith_typesize;
7681 // TODO: Be smarter about handling cases where array_typesize is not a
7682 // multiple of ptrarith_typesize
7683 if (ptrarith_typesize * ratio == array_typesize)
7684 size *= llvm::APInt(size.getBitWidth(), ratio);
7685 }
7686 }
7687
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007688 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007689 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007690 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007691 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007692
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007693 // For array subscripting the index must be less than size, but for pointer
7694 // arithmetic also allow the index (offset) to be equal to size since
7695 // computing the next address after the end of the array is legal and
7696 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007697 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007698 return;
7699
7700 // Also don't warn for arrays of size 1 which are members of some
7701 // structure. These are often used to approximate flexible arrays in C89
7702 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007703 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007704 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007705
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007706 // Suppress the warning if the subscript expression (as identified by the
7707 // ']' location) and the index expression are both from macro expansions
7708 // within a system header.
7709 if (ASE) {
7710 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7711 ASE->getRBracketLoc());
7712 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7713 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7714 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007715 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007716 return;
7717 }
7718 }
7719
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007720 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007721 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007722 DiagID = diag::warn_array_index_exceeds_bounds;
7723
7724 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7725 PDiag(DiagID) << index.toString(10, true)
7726 << size.toString(10, true)
7727 << (unsigned)size.getLimitedValue(~0U)
7728 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007729 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007730 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007731 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007732 DiagID = diag::warn_ptr_arith_precedes_bounds;
7733 if (index.isNegative()) index = -index;
7734 }
7735
7736 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7737 PDiag(DiagID) << index.toString(10, true)
7738 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007739 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007740
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007741 if (!ND) {
7742 // Try harder to find a NamedDecl to point at in the note.
7743 while (const ArraySubscriptExpr *ASE =
7744 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7745 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7746 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7747 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7748 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7749 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7750 }
7751
Chandler Carruth1af88f12011-02-17 21:10:52 +00007752 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007753 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7754 PDiag(diag::note_array_index_out_of_bounds)
7755 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007756}
7757
Ted Kremenekdf26df72011-03-01 18:41:00 +00007758void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007759 int AllowOnePastEnd = 0;
7760 while (expr) {
7761 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007762 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007763 case Stmt::ArraySubscriptExprClass: {
7764 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007765 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007766 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007767 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007768 }
7769 case Stmt::UnaryOperatorClass: {
7770 // Only unwrap the * and & unary operators
7771 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7772 expr = UO->getSubExpr();
7773 switch (UO->getOpcode()) {
7774 case UO_AddrOf:
7775 AllowOnePastEnd++;
7776 break;
7777 case UO_Deref:
7778 AllowOnePastEnd--;
7779 break;
7780 default:
7781 return;
7782 }
7783 break;
7784 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007785 case Stmt::ConditionalOperatorClass: {
7786 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7787 if (const Expr *lhs = cond->getLHS())
7788 CheckArrayAccess(lhs);
7789 if (const Expr *rhs = cond->getRHS())
7790 CheckArrayAccess(rhs);
7791 return;
7792 }
7793 default:
7794 return;
7795 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007796 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007797}
John McCall31168b02011-06-15 23:02:42 +00007798
7799//===--- CHECK: Objective-C retain cycles ----------------------------------//
7800
7801namespace {
7802 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007803 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007804 VarDecl *Variable;
7805 SourceRange Range;
7806 SourceLocation Loc;
7807 bool Indirect;
7808
7809 void setLocsFrom(Expr *e) {
7810 Loc = e->getExprLoc();
7811 Range = e->getSourceRange();
7812 }
7813 };
7814}
7815
7816/// Consider whether capturing the given variable can possibly lead to
7817/// a retain cycle.
7818static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007819 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007820 // lifetime. In MRR, it's captured strongly if the variable is
7821 // __block and has an appropriate type.
7822 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7823 return false;
7824
7825 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007826 if (ref)
7827 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007828 return true;
7829}
7830
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007831static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007832 while (true) {
7833 e = e->IgnoreParens();
7834 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7835 switch (cast->getCastKind()) {
7836 case CK_BitCast:
7837 case CK_LValueBitCast:
7838 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007839 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007840 e = cast->getSubExpr();
7841 continue;
7842
John McCall31168b02011-06-15 23:02:42 +00007843 default:
7844 return false;
7845 }
7846 }
7847
7848 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7849 ObjCIvarDecl *ivar = ref->getDecl();
7850 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7851 return false;
7852
7853 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007854 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007855 return false;
7856
7857 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7858 owner.Indirect = true;
7859 return true;
7860 }
7861
7862 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7863 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7864 if (!var) return false;
7865 return considerVariable(var, ref, owner);
7866 }
7867
John McCall31168b02011-06-15 23:02:42 +00007868 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7869 if (member->isArrow()) return false;
7870
7871 // Don't count this as an indirect ownership.
7872 e = member->getBase();
7873 continue;
7874 }
7875
John McCallfe96e0b2011-11-06 09:01:30 +00007876 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7877 // Only pay attention to pseudo-objects on property references.
7878 ObjCPropertyRefExpr *pre
7879 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7880 ->IgnoreParens());
7881 if (!pre) return false;
7882 if (pre->isImplicitProperty()) return false;
7883 ObjCPropertyDecl *property = pre->getExplicitProperty();
7884 if (!property->isRetaining() &&
7885 !(property->getPropertyIvarDecl() &&
7886 property->getPropertyIvarDecl()->getType()
7887 .getObjCLifetime() == Qualifiers::OCL_Strong))
7888 return false;
7889
7890 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007891 if (pre->isSuperReceiver()) {
7892 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7893 if (!owner.Variable)
7894 return false;
7895 owner.Loc = pre->getLocation();
7896 owner.Range = pre->getSourceRange();
7897 return true;
7898 }
John McCallfe96e0b2011-11-06 09:01:30 +00007899 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7900 ->getSourceExpr());
7901 continue;
7902 }
7903
John McCall31168b02011-06-15 23:02:42 +00007904 // Array ivars?
7905
7906 return false;
7907 }
7908}
7909
7910namespace {
7911 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7912 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7913 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007914 Context(Context), Variable(variable), Capturer(nullptr),
7915 VarWillBeReased(false) {}
7916 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00007917 VarDecl *Variable;
7918 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007919 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00007920
7921 void VisitDeclRefExpr(DeclRefExpr *ref) {
7922 if (ref->getDecl() == Variable && !Capturer)
7923 Capturer = ref;
7924 }
7925
John McCall31168b02011-06-15 23:02:42 +00007926 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7927 if (Capturer) return;
7928 Visit(ref->getBase());
7929 if (Capturer && ref->isFreeIvar())
7930 Capturer = ref;
7931 }
7932
7933 void VisitBlockExpr(BlockExpr *block) {
7934 // Look inside nested blocks
7935 if (block->getBlockDecl()->capturesVariable(Variable))
7936 Visit(block->getBlockDecl()->getBody());
7937 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007938
7939 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7940 if (Capturer) return;
7941 if (OVE->getSourceExpr())
7942 Visit(OVE->getSourceExpr());
7943 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007944 void VisitBinaryOperator(BinaryOperator *BinOp) {
7945 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7946 return;
7947 Expr *LHS = BinOp->getLHS();
7948 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7949 if (DRE->getDecl() != Variable)
7950 return;
7951 if (Expr *RHS = BinOp->getRHS()) {
7952 RHS = RHS->IgnoreParenCasts();
7953 llvm::APSInt Value;
7954 VarWillBeReased =
7955 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7956 }
7957 }
7958 }
John McCall31168b02011-06-15 23:02:42 +00007959 };
7960}
7961
7962/// Check whether the given argument is a block which captures a
7963/// variable.
7964static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7965 assert(owner.Variable && owner.Loc.isValid());
7966
7967 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007968
7969 // Look through [^{...} copy] and Block_copy(^{...}).
7970 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7971 Selector Cmd = ME->getSelector();
7972 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7973 e = ME->getInstanceReceiver();
7974 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00007975 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00007976 e = e->IgnoreParenCasts();
7977 }
7978 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7979 if (CE->getNumArgs() == 1) {
7980 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007981 if (Fn) {
7982 const IdentifierInfo *FnI = Fn->getIdentifier();
7983 if (FnI && FnI->isStr("_Block_copy")) {
7984 e = CE->getArg(0)->IgnoreParenCasts();
7985 }
7986 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007987 }
7988 }
7989
John McCall31168b02011-06-15 23:02:42 +00007990 BlockExpr *block = dyn_cast<BlockExpr>(e);
7991 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00007992 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00007993
7994 FindCaptureVisitor visitor(S.Context, owner.Variable);
7995 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007996 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00007997}
7998
7999static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8000 RetainCycleOwner &owner) {
8001 assert(capturer);
8002 assert(owner.Variable && owner.Loc.isValid());
8003
8004 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8005 << owner.Variable << capturer->getSourceRange();
8006 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8007 << owner.Indirect << owner.Range;
8008}
8009
8010/// Check for a keyword selector that starts with the word 'add' or
8011/// 'set'.
8012static bool isSetterLikeSelector(Selector sel) {
8013 if (sel.isUnarySelector()) return false;
8014
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008015 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008016 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008017 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008018 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008019 else if (str.startswith("add")) {
8020 // Specially whitelist 'addOperationWithBlock:'.
8021 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8022 return false;
8023 str = str.substr(3);
8024 }
John McCall31168b02011-06-15 23:02:42 +00008025 else
8026 return false;
8027
8028 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008029 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008030}
8031
8032/// Check a message send to see if it's likely to cause a retain cycle.
8033void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8034 // Only check instance methods whose selector looks like a setter.
8035 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8036 return;
8037
8038 // Try to find a variable that the receiver is strongly owned by.
8039 RetainCycleOwner owner;
8040 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008041 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008042 return;
8043 } else {
8044 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8045 owner.Variable = getCurMethodDecl()->getSelfDecl();
8046 owner.Loc = msg->getSuperLoc();
8047 owner.Range = msg->getSuperLoc();
8048 }
8049
8050 // Check whether the receiver is captured by any of the arguments.
8051 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8052 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8053 return diagnoseRetainCycle(*this, capturer, owner);
8054}
8055
8056/// Check a property assign to see if it's likely to cause a retain cycle.
8057void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8058 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008059 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008060 return;
8061
8062 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8063 diagnoseRetainCycle(*this, capturer, owner);
8064}
8065
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008066void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8067 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008068 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008069 return;
8070
8071 // Because we don't have an expression for the variable, we have to set the
8072 // location explicitly here.
8073 Owner.Loc = Var->getLocation();
8074 Owner.Range = Var->getSourceRange();
8075
8076 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8077 diagnoseRetainCycle(*this, Capturer, Owner);
8078}
8079
Ted Kremenek9304da92012-12-21 08:04:28 +00008080static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8081 Expr *RHS, bool isProperty) {
8082 // Check if RHS is an Objective-C object literal, which also can get
8083 // immediately zapped in a weak reference. Note that we explicitly
8084 // allow ObjCStringLiterals, since those are designed to never really die.
8085 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008086
Ted Kremenek64873352012-12-21 22:46:35 +00008087 // This enum needs to match with the 'select' in
8088 // warn_objc_arc_literal_assign (off-by-1).
8089 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8090 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8091 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008092
8093 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008094 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008095 << (isProperty ? 0 : 1)
8096 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008097
8098 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008099}
8100
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008101static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8102 Qualifiers::ObjCLifetime LT,
8103 Expr *RHS, bool isProperty) {
8104 // Strip off any implicit cast added to get to the one ARC-specific.
8105 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8106 if (cast->getCastKind() == CK_ARCConsumeObject) {
8107 S.Diag(Loc, diag::warn_arc_retained_assign)
8108 << (LT == Qualifiers::OCL_ExplicitNone)
8109 << (isProperty ? 0 : 1)
8110 << RHS->getSourceRange();
8111 return true;
8112 }
8113 RHS = cast->getSubExpr();
8114 }
8115
8116 if (LT == Qualifiers::OCL_Weak &&
8117 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8118 return true;
8119
8120 return false;
8121}
8122
Ted Kremenekb36234d2012-12-21 08:04:20 +00008123bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8124 QualType LHS, Expr *RHS) {
8125 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8126
8127 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8128 return false;
8129
8130 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8131 return true;
8132
8133 return false;
8134}
8135
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008136void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8137 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008138 QualType LHSType;
8139 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008140 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008141 ObjCPropertyRefExpr *PRE
8142 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8143 if (PRE && !PRE->isImplicitProperty()) {
8144 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8145 if (PD)
8146 LHSType = PD->getType();
8147 }
8148
8149 if (LHSType.isNull())
8150 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008151
8152 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8153
8154 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008155 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008156 getCurFunction()->markSafeWeakUse(LHS);
8157 }
8158
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008159 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8160 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008161
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008162 // FIXME. Check for other life times.
8163 if (LT != Qualifiers::OCL_None)
8164 return;
8165
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008166 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008167 if (PRE->isImplicitProperty())
8168 return;
8169 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8170 if (!PD)
8171 return;
8172
Bill Wendling44426052012-12-20 19:22:21 +00008173 unsigned Attributes = PD->getPropertyAttributes();
8174 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008175 // when 'assign' attribute was not explicitly specified
8176 // by user, ignore it and rely on property type itself
8177 // for lifetime info.
8178 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8179 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8180 LHSType->isObjCRetainableType())
8181 return;
8182
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008183 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008184 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008185 Diag(Loc, diag::warn_arc_retained_property_assign)
8186 << RHS->getSourceRange();
8187 return;
8188 }
8189 RHS = cast->getSubExpr();
8190 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008191 }
Bill Wendling44426052012-12-20 19:22:21 +00008192 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008193 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8194 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008195 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008196 }
8197}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008198
8199//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8200
8201namespace {
8202bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8203 SourceLocation StmtLoc,
8204 const NullStmt *Body) {
8205 // Do not warn if the body is a macro that expands to nothing, e.g:
8206 //
8207 // #define CALL(x)
8208 // if (condition)
8209 // CALL(0);
8210 //
8211 if (Body->hasLeadingEmptyMacro())
8212 return false;
8213
8214 // Get line numbers of statement and body.
8215 bool StmtLineInvalid;
8216 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8217 &StmtLineInvalid);
8218 if (StmtLineInvalid)
8219 return false;
8220
8221 bool BodyLineInvalid;
8222 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8223 &BodyLineInvalid);
8224 if (BodyLineInvalid)
8225 return false;
8226
8227 // Warn if null statement and body are on the same line.
8228 if (StmtLine != BodyLine)
8229 return false;
8230
8231 return true;
8232}
8233} // Unnamed namespace
8234
8235void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8236 const Stmt *Body,
8237 unsigned DiagID) {
8238 // Since this is a syntactic check, don't emit diagnostic for template
8239 // instantiations, this just adds noise.
8240 if (CurrentInstantiationScope)
8241 return;
8242
8243 // The body should be a null statement.
8244 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8245 if (!NBody)
8246 return;
8247
8248 // Do the usual checks.
8249 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8250 return;
8251
8252 Diag(NBody->getSemiLoc(), DiagID);
8253 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8254}
8255
8256void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8257 const Stmt *PossibleBody) {
8258 assert(!CurrentInstantiationScope); // Ensured by caller
8259
8260 SourceLocation StmtLoc;
8261 const Stmt *Body;
8262 unsigned DiagID;
8263 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8264 StmtLoc = FS->getRParenLoc();
8265 Body = FS->getBody();
8266 DiagID = diag::warn_empty_for_body;
8267 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8268 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8269 Body = WS->getBody();
8270 DiagID = diag::warn_empty_while_body;
8271 } else
8272 return; // Neither `for' nor `while'.
8273
8274 // The body should be a null statement.
8275 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8276 if (!NBody)
8277 return;
8278
8279 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008280 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008281 return;
8282
8283 // Do the usual checks.
8284 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8285 return;
8286
8287 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8288 // noise level low, emit diagnostics only if for/while is followed by a
8289 // CompoundStmt, e.g.:
8290 // for (int i = 0; i < n; i++);
8291 // {
8292 // a(i);
8293 // }
8294 // or if for/while is followed by a statement with more indentation
8295 // than for/while itself:
8296 // for (int i = 0; i < n; i++);
8297 // a(i);
8298 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8299 if (!ProbableTypo) {
8300 bool BodyColInvalid;
8301 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8302 PossibleBody->getLocStart(),
8303 &BodyColInvalid);
8304 if (BodyColInvalid)
8305 return;
8306
8307 bool StmtColInvalid;
8308 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8309 S->getLocStart(),
8310 &StmtColInvalid);
8311 if (StmtColInvalid)
8312 return;
8313
8314 if (BodyCol > StmtCol)
8315 ProbableTypo = true;
8316 }
8317
8318 if (ProbableTypo) {
8319 Diag(NBody->getSemiLoc(), DiagID);
8320 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8321 }
8322}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008323
8324//===--- Layout compatibility ----------------------------------------------//
8325
8326namespace {
8327
8328bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8329
8330/// \brief Check if two enumeration types are layout-compatible.
8331bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8332 // C++11 [dcl.enum] p8:
8333 // Two enumeration types are layout-compatible if they have the same
8334 // underlying type.
8335 return ED1->isComplete() && ED2->isComplete() &&
8336 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8337}
8338
8339/// \brief Check if two fields are layout-compatible.
8340bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8341 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8342 return false;
8343
8344 if (Field1->isBitField() != Field2->isBitField())
8345 return false;
8346
8347 if (Field1->isBitField()) {
8348 // Make sure that the bit-fields are the same length.
8349 unsigned Bits1 = Field1->getBitWidthValue(C);
8350 unsigned Bits2 = Field2->getBitWidthValue(C);
8351
8352 if (Bits1 != Bits2)
8353 return false;
8354 }
8355
8356 return true;
8357}
8358
8359/// \brief Check if two standard-layout structs are layout-compatible.
8360/// (C++11 [class.mem] p17)
8361bool isLayoutCompatibleStruct(ASTContext &C,
8362 RecordDecl *RD1,
8363 RecordDecl *RD2) {
8364 // If both records are C++ classes, check that base classes match.
8365 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8366 // If one of records is a CXXRecordDecl we are in C++ mode,
8367 // thus the other one is a CXXRecordDecl, too.
8368 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8369 // Check number of base classes.
8370 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8371 return false;
8372
8373 // Check the base classes.
8374 for (CXXRecordDecl::base_class_const_iterator
8375 Base1 = D1CXX->bases_begin(),
8376 BaseEnd1 = D1CXX->bases_end(),
8377 Base2 = D2CXX->bases_begin();
8378 Base1 != BaseEnd1;
8379 ++Base1, ++Base2) {
8380 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8381 return false;
8382 }
8383 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8384 // If only RD2 is a C++ class, it should have zero base classes.
8385 if (D2CXX->getNumBases() > 0)
8386 return false;
8387 }
8388
8389 // Check the fields.
8390 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8391 Field2End = RD2->field_end(),
8392 Field1 = RD1->field_begin(),
8393 Field1End = RD1->field_end();
8394 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8395 if (!isLayoutCompatible(C, *Field1, *Field2))
8396 return false;
8397 }
8398 if (Field1 != Field1End || Field2 != Field2End)
8399 return false;
8400
8401 return true;
8402}
8403
8404/// \brief Check if two standard-layout unions are layout-compatible.
8405/// (C++11 [class.mem] p18)
8406bool isLayoutCompatibleUnion(ASTContext &C,
8407 RecordDecl *RD1,
8408 RecordDecl *RD2) {
8409 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008410 for (auto *Field2 : RD2->fields())
8411 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008412
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008413 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008414 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8415 I = UnmatchedFields.begin(),
8416 E = UnmatchedFields.end();
8417
8418 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008419 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008420 bool Result = UnmatchedFields.erase(*I);
8421 (void) Result;
8422 assert(Result);
8423 break;
8424 }
8425 }
8426 if (I == E)
8427 return false;
8428 }
8429
8430 return UnmatchedFields.empty();
8431}
8432
8433bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8434 if (RD1->isUnion() != RD2->isUnion())
8435 return false;
8436
8437 if (RD1->isUnion())
8438 return isLayoutCompatibleUnion(C, RD1, RD2);
8439 else
8440 return isLayoutCompatibleStruct(C, RD1, RD2);
8441}
8442
8443/// \brief Check if two types are layout-compatible in C++11 sense.
8444bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8445 if (T1.isNull() || T2.isNull())
8446 return false;
8447
8448 // C++11 [basic.types] p11:
8449 // If two types T1 and T2 are the same type, then T1 and T2 are
8450 // layout-compatible types.
8451 if (C.hasSameType(T1, T2))
8452 return true;
8453
8454 T1 = T1.getCanonicalType().getUnqualifiedType();
8455 T2 = T2.getCanonicalType().getUnqualifiedType();
8456
8457 const Type::TypeClass TC1 = T1->getTypeClass();
8458 const Type::TypeClass TC2 = T2->getTypeClass();
8459
8460 if (TC1 != TC2)
8461 return false;
8462
8463 if (TC1 == Type::Enum) {
8464 return isLayoutCompatible(C,
8465 cast<EnumType>(T1)->getDecl(),
8466 cast<EnumType>(T2)->getDecl());
8467 } else if (TC1 == Type::Record) {
8468 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8469 return false;
8470
8471 return isLayoutCompatible(C,
8472 cast<RecordType>(T1)->getDecl(),
8473 cast<RecordType>(T2)->getDecl());
8474 }
8475
8476 return false;
8477}
8478}
8479
8480//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8481
8482namespace {
8483/// \brief Given a type tag expression find the type tag itself.
8484///
8485/// \param TypeExpr Type tag expression, as it appears in user's code.
8486///
8487/// \param VD Declaration of an identifier that appears in a type tag.
8488///
8489/// \param MagicValue Type tag magic value.
8490bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8491 const ValueDecl **VD, uint64_t *MagicValue) {
8492 while(true) {
8493 if (!TypeExpr)
8494 return false;
8495
8496 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8497
8498 switch (TypeExpr->getStmtClass()) {
8499 case Stmt::UnaryOperatorClass: {
8500 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8501 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8502 TypeExpr = UO->getSubExpr();
8503 continue;
8504 }
8505 return false;
8506 }
8507
8508 case Stmt::DeclRefExprClass: {
8509 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8510 *VD = DRE->getDecl();
8511 return true;
8512 }
8513
8514 case Stmt::IntegerLiteralClass: {
8515 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8516 llvm::APInt MagicValueAPInt = IL->getValue();
8517 if (MagicValueAPInt.getActiveBits() <= 64) {
8518 *MagicValue = MagicValueAPInt.getZExtValue();
8519 return true;
8520 } else
8521 return false;
8522 }
8523
8524 case Stmt::BinaryConditionalOperatorClass:
8525 case Stmt::ConditionalOperatorClass: {
8526 const AbstractConditionalOperator *ACO =
8527 cast<AbstractConditionalOperator>(TypeExpr);
8528 bool Result;
8529 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8530 if (Result)
8531 TypeExpr = ACO->getTrueExpr();
8532 else
8533 TypeExpr = ACO->getFalseExpr();
8534 continue;
8535 }
8536 return false;
8537 }
8538
8539 case Stmt::BinaryOperatorClass: {
8540 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8541 if (BO->getOpcode() == BO_Comma) {
8542 TypeExpr = BO->getRHS();
8543 continue;
8544 }
8545 return false;
8546 }
8547
8548 default:
8549 return false;
8550 }
8551 }
8552}
8553
8554/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8555///
8556/// \param TypeExpr Expression that specifies a type tag.
8557///
8558/// \param MagicValues Registered magic values.
8559///
8560/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8561/// kind.
8562///
8563/// \param TypeInfo Information about the corresponding C type.
8564///
8565/// \returns true if the corresponding C type was found.
8566bool GetMatchingCType(
8567 const IdentifierInfo *ArgumentKind,
8568 const Expr *TypeExpr, const ASTContext &Ctx,
8569 const llvm::DenseMap<Sema::TypeTagMagicValue,
8570 Sema::TypeTagData> *MagicValues,
8571 bool &FoundWrongKind,
8572 Sema::TypeTagData &TypeInfo) {
8573 FoundWrongKind = false;
8574
8575 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008576 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008577
8578 uint64_t MagicValue;
8579
8580 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8581 return false;
8582
8583 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008584 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008585 if (I->getArgumentKind() != ArgumentKind) {
8586 FoundWrongKind = true;
8587 return false;
8588 }
8589 TypeInfo.Type = I->getMatchingCType();
8590 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8591 TypeInfo.MustBeNull = I->getMustBeNull();
8592 return true;
8593 }
8594 return false;
8595 }
8596
8597 if (!MagicValues)
8598 return false;
8599
8600 llvm::DenseMap<Sema::TypeTagMagicValue,
8601 Sema::TypeTagData>::const_iterator I =
8602 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8603 if (I == MagicValues->end())
8604 return false;
8605
8606 TypeInfo = I->second;
8607 return true;
8608}
8609} // unnamed namespace
8610
8611void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8612 uint64_t MagicValue, QualType Type,
8613 bool LayoutCompatible,
8614 bool MustBeNull) {
8615 if (!TypeTagForDatatypeMagicValues)
8616 TypeTagForDatatypeMagicValues.reset(
8617 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8618
8619 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8620 (*TypeTagForDatatypeMagicValues)[Magic] =
8621 TypeTagData(Type, LayoutCompatible, MustBeNull);
8622}
8623
8624namespace {
8625bool IsSameCharType(QualType T1, QualType T2) {
8626 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8627 if (!BT1)
8628 return false;
8629
8630 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8631 if (!BT2)
8632 return false;
8633
8634 BuiltinType::Kind T1Kind = BT1->getKind();
8635 BuiltinType::Kind T2Kind = BT2->getKind();
8636
8637 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8638 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8639 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8640 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8641}
8642} // unnamed namespace
8643
8644void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8645 const Expr * const *ExprArgs) {
8646 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8647 bool IsPointerAttr = Attr->getIsPointer();
8648
8649 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8650 bool FoundWrongKind;
8651 TypeTagData TypeInfo;
8652 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8653 TypeTagForDatatypeMagicValues.get(),
8654 FoundWrongKind, TypeInfo)) {
8655 if (FoundWrongKind)
8656 Diag(TypeTagExpr->getExprLoc(),
8657 diag::warn_type_tag_for_datatype_wrong_kind)
8658 << TypeTagExpr->getSourceRange();
8659 return;
8660 }
8661
8662 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8663 if (IsPointerAttr) {
8664 // Skip implicit cast of pointer to `void *' (as a function argument).
8665 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008666 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008667 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008668 ArgumentExpr = ICE->getSubExpr();
8669 }
8670 QualType ArgumentType = ArgumentExpr->getType();
8671
8672 // Passing a `void*' pointer shouldn't trigger a warning.
8673 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8674 return;
8675
8676 if (TypeInfo.MustBeNull) {
8677 // Type tag with matching void type requires a null pointer.
8678 if (!ArgumentExpr->isNullPointerConstant(Context,
8679 Expr::NPC_ValueDependentIsNotNull)) {
8680 Diag(ArgumentExpr->getExprLoc(),
8681 diag::warn_type_safety_null_pointer_required)
8682 << ArgumentKind->getName()
8683 << ArgumentExpr->getSourceRange()
8684 << TypeTagExpr->getSourceRange();
8685 }
8686 return;
8687 }
8688
8689 QualType RequiredType = TypeInfo.Type;
8690 if (IsPointerAttr)
8691 RequiredType = Context.getPointerType(RequiredType);
8692
8693 bool mismatch = false;
8694 if (!TypeInfo.LayoutCompatible) {
8695 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8696
8697 // C++11 [basic.fundamental] p1:
8698 // Plain char, signed char, and unsigned char are three distinct types.
8699 //
8700 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8701 // char' depending on the current char signedness mode.
8702 if (mismatch)
8703 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8704 RequiredType->getPointeeType())) ||
8705 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8706 mismatch = false;
8707 } else
8708 if (IsPointerAttr)
8709 mismatch = !isLayoutCompatible(Context,
8710 ArgumentType->getPointeeType(),
8711 RequiredType->getPointeeType());
8712 else
8713 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8714
8715 if (mismatch)
8716 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008717 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008718 << TypeInfo.LayoutCompatible << RequiredType
8719 << ArgumentExpr->getSourceRange()
8720 << TypeTagExpr->getSourceRange();
8721}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008722