blob: c26ba3cf9bbb8c435f7c855335b9ef4014f99e85 [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
Reid Kleckner1d59f992015-01-22 01:36:17 +0000205static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
206 Scope::ScopeFlags NeededScopeFlags,
207 unsigned DiagID) {
208 // Scopes aren't available during instantiation. Fortunately, builtin
209 // functions cannot be template args so they cannot be formed through template
210 // instantiation. Therefore checking once during the parse is sufficient.
211 if (!SemaRef.ActiveTemplateInstantiations.empty())
212 return false;
213
214 Scope *S = SemaRef.getCurScope();
215 while (S && !S->isSEHExceptScope())
216 S = S->getParent();
217 if (!S || !(S->getFlags() & NeededScopeFlags)) {
218 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
219 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
220 << DRE->getDecl()->getIdentifier();
221 return true;
222 }
223
224 return false;
225}
226
John McCalldadc5752010-08-24 06:29:42 +0000227ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000228Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
229 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000230 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000231
Chris Lattner3be167f2010-10-01 23:23:24 +0000232 // Find out if any arguments are required to be integer constant expressions.
233 unsigned ICEArguments = 0;
234 ASTContext::GetBuiltinTypeError Error;
235 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
236 if (Error != ASTContext::GE_None)
237 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
238
239 // If any arguments are required to be ICE's, check and diagnose.
240 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
241 // Skip arguments not required to be ICE's.
242 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
243
244 llvm::APSInt Result;
245 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
246 return true;
247 ICEArguments &= ~(1 << ArgNo);
248 }
249
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000250 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000251 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000252 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000253 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000254 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000255 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000256 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000257 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000258 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000259 if (SemaBuiltinVAStart(TheCall))
260 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000261 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000262 case Builtin::BI__va_start: {
263 switch (Context.getTargetInfo().getTriple().getArch()) {
264 case llvm::Triple::arm:
265 case llvm::Triple::thumb:
266 if (SemaBuiltinVAStartARM(TheCall))
267 return ExprError();
268 break;
269 default:
270 if (SemaBuiltinVAStart(TheCall))
271 return ExprError();
272 break;
273 }
274 break;
275 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000276 case Builtin::BI__builtin_isgreater:
277 case Builtin::BI__builtin_isgreaterequal:
278 case Builtin::BI__builtin_isless:
279 case Builtin::BI__builtin_islessequal:
280 case Builtin::BI__builtin_islessgreater:
281 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000282 if (SemaBuiltinUnorderedCompare(TheCall))
283 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000284 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000285 case Builtin::BI__builtin_fpclassify:
286 if (SemaBuiltinFPClassification(TheCall, 6))
287 return ExprError();
288 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000289 case Builtin::BI__builtin_isfinite:
290 case Builtin::BI__builtin_isinf:
291 case Builtin::BI__builtin_isinf_sign:
292 case Builtin::BI__builtin_isnan:
293 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000294 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000295 return ExprError();
296 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000297 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000298 return SemaBuiltinShuffleVector(TheCall);
299 // TheCall will be freed by the smart pointer here, but that's fine, since
300 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000301 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000302 if (SemaBuiltinPrefetch(TheCall))
303 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000304 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000305 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000306 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000307 if (SemaBuiltinAssume(TheCall))
308 return ExprError();
309 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000310 case Builtin::BI__builtin_assume_aligned:
311 if (SemaBuiltinAssumeAligned(TheCall))
312 return ExprError();
313 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000314 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000315 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000316 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000317 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000318 case Builtin::BI__builtin_longjmp:
319 if (SemaBuiltinLongjmp(TheCall))
320 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000321 break;
John McCallbebede42011-02-26 05:39:39 +0000322
323 case Builtin::BI__builtin_classify_type:
324 if (checkArgCount(*this, TheCall, 1)) return true;
325 TheCall->setType(Context.IntTy);
326 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000327 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000328 if (checkArgCount(*this, TheCall, 1)) return true;
329 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000330 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000331 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000332 case Builtin::BI__sync_fetch_and_add_1:
333 case Builtin::BI__sync_fetch_and_add_2:
334 case Builtin::BI__sync_fetch_and_add_4:
335 case Builtin::BI__sync_fetch_and_add_8:
336 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000337 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000338 case Builtin::BI__sync_fetch_and_sub_1:
339 case Builtin::BI__sync_fetch_and_sub_2:
340 case Builtin::BI__sync_fetch_and_sub_4:
341 case Builtin::BI__sync_fetch_and_sub_8:
342 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000343 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000344 case Builtin::BI__sync_fetch_and_or_1:
345 case Builtin::BI__sync_fetch_and_or_2:
346 case Builtin::BI__sync_fetch_and_or_4:
347 case Builtin::BI__sync_fetch_and_or_8:
348 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000349 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000350 case Builtin::BI__sync_fetch_and_and_1:
351 case Builtin::BI__sync_fetch_and_and_2:
352 case Builtin::BI__sync_fetch_and_and_4:
353 case Builtin::BI__sync_fetch_and_and_8:
354 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000355 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000356 case Builtin::BI__sync_fetch_and_xor_1:
357 case Builtin::BI__sync_fetch_and_xor_2:
358 case Builtin::BI__sync_fetch_and_xor_4:
359 case Builtin::BI__sync_fetch_and_xor_8:
360 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000361 case Builtin::BI__sync_fetch_and_nand:
362 case Builtin::BI__sync_fetch_and_nand_1:
363 case Builtin::BI__sync_fetch_and_nand_2:
364 case Builtin::BI__sync_fetch_and_nand_4:
365 case Builtin::BI__sync_fetch_and_nand_8:
366 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000367 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000368 case Builtin::BI__sync_add_and_fetch_1:
369 case Builtin::BI__sync_add_and_fetch_2:
370 case Builtin::BI__sync_add_and_fetch_4:
371 case Builtin::BI__sync_add_and_fetch_8:
372 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000373 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000374 case Builtin::BI__sync_sub_and_fetch_1:
375 case Builtin::BI__sync_sub_and_fetch_2:
376 case Builtin::BI__sync_sub_and_fetch_4:
377 case Builtin::BI__sync_sub_and_fetch_8:
378 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000379 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000380 case Builtin::BI__sync_and_and_fetch_1:
381 case Builtin::BI__sync_and_and_fetch_2:
382 case Builtin::BI__sync_and_and_fetch_4:
383 case Builtin::BI__sync_and_and_fetch_8:
384 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000385 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000386 case Builtin::BI__sync_or_and_fetch_1:
387 case Builtin::BI__sync_or_and_fetch_2:
388 case Builtin::BI__sync_or_and_fetch_4:
389 case Builtin::BI__sync_or_and_fetch_8:
390 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000391 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000392 case Builtin::BI__sync_xor_and_fetch_1:
393 case Builtin::BI__sync_xor_and_fetch_2:
394 case Builtin::BI__sync_xor_and_fetch_4:
395 case Builtin::BI__sync_xor_and_fetch_8:
396 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000397 case Builtin::BI__sync_nand_and_fetch:
398 case Builtin::BI__sync_nand_and_fetch_1:
399 case Builtin::BI__sync_nand_and_fetch_2:
400 case Builtin::BI__sync_nand_and_fetch_4:
401 case Builtin::BI__sync_nand_and_fetch_8:
402 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000403 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000404 case Builtin::BI__sync_val_compare_and_swap_1:
405 case Builtin::BI__sync_val_compare_and_swap_2:
406 case Builtin::BI__sync_val_compare_and_swap_4:
407 case Builtin::BI__sync_val_compare_and_swap_8:
408 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000409 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000410 case Builtin::BI__sync_bool_compare_and_swap_1:
411 case Builtin::BI__sync_bool_compare_and_swap_2:
412 case Builtin::BI__sync_bool_compare_and_swap_4:
413 case Builtin::BI__sync_bool_compare_and_swap_8:
414 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000415 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000416 case Builtin::BI__sync_lock_test_and_set_1:
417 case Builtin::BI__sync_lock_test_and_set_2:
418 case Builtin::BI__sync_lock_test_and_set_4:
419 case Builtin::BI__sync_lock_test_and_set_8:
420 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000421 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000422 case Builtin::BI__sync_lock_release_1:
423 case Builtin::BI__sync_lock_release_2:
424 case Builtin::BI__sync_lock_release_4:
425 case Builtin::BI__sync_lock_release_8:
426 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000427 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000428 case Builtin::BI__sync_swap_1:
429 case Builtin::BI__sync_swap_2:
430 case Builtin::BI__sync_swap_4:
431 case Builtin::BI__sync_swap_8:
432 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000433 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000434#define BUILTIN(ID, TYPE, ATTRS)
435#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
436 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000437 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000438#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000439 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000440 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000441 return ExprError();
442 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000443 case Builtin::BI__builtin_addressof:
444 if (SemaBuiltinAddressof(*this, TheCall))
445 return ExprError();
446 break;
Richard Smith760520b2014-06-03 23:27:44 +0000447 case Builtin::BI__builtin_operator_new:
448 case Builtin::BI__builtin_operator_delete:
449 if (!getLangOpts().CPlusPlus) {
450 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
451 << (BuiltinID == Builtin::BI__builtin_operator_new
452 ? "__builtin_operator_new"
453 : "__builtin_operator_delete")
454 << "C++";
455 return ExprError();
456 }
457 // CodeGen assumes it can find the global new and delete to call,
458 // so ensure that they are declared.
459 DeclareGlobalNewDelete();
460 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000461
462 // check secure string manipulation functions where overflows
463 // are detectable at compile time
464 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000465 case Builtin::BI__builtin___memmove_chk:
466 case Builtin::BI__builtin___memset_chk:
467 case Builtin::BI__builtin___strlcat_chk:
468 case Builtin::BI__builtin___strlcpy_chk:
469 case Builtin::BI__builtin___strncat_chk:
470 case Builtin::BI__builtin___strncpy_chk:
471 case Builtin::BI__builtin___stpncpy_chk:
472 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
473 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000474 case Builtin::BI__builtin___memccpy_chk:
475 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
476 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000477 case Builtin::BI__builtin___snprintf_chk:
478 case Builtin::BI__builtin___vsnprintf_chk:
479 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
480 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000481
482 case Builtin::BI__builtin_call_with_static_chain:
483 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
484 return ExprError();
485 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000486
487 case Builtin::BI__exception_code:
488 case Builtin::BI_exception_code: {
489 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
490 diag::err_seh___except_block))
491 return ExprError();
492 break;
493 }
494 case Builtin::BI__exception_info:
495 case Builtin::BI_exception_info: {
496 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
497 diag::err_seh___except_filter))
498 return ExprError();
499 break;
500 }
501
Nate Begeman4904e322010-06-08 02:47:44 +0000502 }
Richard Smith760520b2014-06-03 23:27:44 +0000503
Nate Begeman4904e322010-06-08 02:47:44 +0000504 // Since the target specific builtins for each arch overlap, only check those
505 // of the arch we are compiling for.
506 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000507 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000508 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000509 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000510 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000511 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000512 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
513 return ExprError();
514 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000515 case llvm::Triple::aarch64:
516 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000517 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000518 return ExprError();
519 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000520 case llvm::Triple::mips:
521 case llvm::Triple::mipsel:
522 case llvm::Triple::mips64:
523 case llvm::Triple::mips64el:
524 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
525 return ExprError();
526 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000527 case llvm::Triple::x86:
528 case llvm::Triple::x86_64:
529 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
530 return ExprError();
531 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000532 default:
533 break;
534 }
535 }
536
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000537 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000538}
539
Nate Begeman91e1fea2010-06-14 05:21:25 +0000540// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000541static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000542 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000543 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000544 switch (Type.getEltType()) {
545 case NeonTypeFlags::Int8:
546 case NeonTypeFlags::Poly8:
547 return shift ? 7 : (8 << IsQuad) - 1;
548 case NeonTypeFlags::Int16:
549 case NeonTypeFlags::Poly16:
550 return shift ? 15 : (4 << IsQuad) - 1;
551 case NeonTypeFlags::Int32:
552 return shift ? 31 : (2 << IsQuad) - 1;
553 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000554 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000555 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000556 case NeonTypeFlags::Poly128:
557 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000558 case NeonTypeFlags::Float16:
559 assert(!shift && "cannot shift float types!");
560 return (4 << IsQuad) - 1;
561 case NeonTypeFlags::Float32:
562 assert(!shift && "cannot shift float types!");
563 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000564 case NeonTypeFlags::Float64:
565 assert(!shift && "cannot shift float types!");
566 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000567 }
David Blaikie8a40f702012-01-17 06:56:22 +0000568 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000569}
570
Bob Wilsone4d77232011-11-08 05:04:11 +0000571/// getNeonEltType - Return the QualType corresponding to the elements of
572/// the vector type specified by the NeonTypeFlags. This is used to check
573/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000574static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000575 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000576 switch (Flags.getEltType()) {
577 case NeonTypeFlags::Int8:
578 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
579 case NeonTypeFlags::Int16:
580 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
581 case NeonTypeFlags::Int32:
582 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
583 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000584 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000585 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
586 else
587 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
588 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000589 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000590 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000591 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000592 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000593 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000594 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000595 case NeonTypeFlags::Poly128:
596 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000597 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000598 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000599 case NeonTypeFlags::Float32:
600 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000601 case NeonTypeFlags::Float64:
602 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000603 }
David Blaikie8a40f702012-01-17 06:56:22 +0000604 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000605}
606
Tim Northover12670412014-02-19 10:37:05 +0000607bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000608 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000609 uint64_t mask = 0;
610 unsigned TV = 0;
611 int PtrArgNum = -1;
612 bool HasConstPtr = false;
613 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000614#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000615#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000616#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000617 }
618
619 // For NEON intrinsics which are overloaded on vector element type, validate
620 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000621 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000622 if (mask) {
623 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
624 return true;
625
626 TV = Result.getLimitedValue(64);
627 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
628 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000629 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000630 }
631
632 if (PtrArgNum >= 0) {
633 // Check that pointer arguments have the specified type.
634 Expr *Arg = TheCall->getArg(PtrArgNum);
635 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
636 Arg = ICE->getSubExpr();
637 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
638 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000639
Tim Northovera2ee4332014-03-29 15:09:45 +0000640 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000641 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000642 bool IsInt64Long =
643 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
644 QualType EltTy =
645 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000646 if (HasConstPtr)
647 EltTy = EltTy.withConst();
648 QualType LHSTy = Context.getPointerType(EltTy);
649 AssignConvertType ConvTy;
650 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
651 if (RHS.isInvalid())
652 return true;
653 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
654 RHS.get(), AA_Assigning))
655 return true;
656 }
657
658 // For NEON intrinsics which take an immediate value as part of the
659 // instruction, range check them here.
660 unsigned i = 0, l = 0, u = 0;
661 switch (BuiltinID) {
662 default:
663 return false;
Tim Northover12670412014-02-19 10:37:05 +0000664#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000665#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000666#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000667 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000668
Richard Sandiford28940af2014-04-16 08:47:51 +0000669 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000670}
671
Tim Northovera2ee4332014-03-29 15:09:45 +0000672bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
673 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000674 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000675 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000676 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000677 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000678 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000679 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
680 BuiltinID == AArch64::BI__builtin_arm_strex ||
681 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000682 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000683 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000684 BuiltinID == ARM::BI__builtin_arm_ldaex ||
685 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
686 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000687
688 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
689
690 // Ensure that we have the proper number of arguments.
691 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
692 return true;
693
694 // Inspect the pointer argument of the atomic builtin. This should always be
695 // a pointer type, whose element is an integral scalar or pointer type.
696 // Because it is a pointer type, we don't have to worry about any implicit
697 // casts here.
698 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
699 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
700 if (PointerArgRes.isInvalid())
701 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000702 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000703
704 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
705 if (!pointerType) {
706 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
707 << PointerArg->getType() << PointerArg->getSourceRange();
708 return true;
709 }
710
711 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
712 // task is to insert the appropriate casts into the AST. First work out just
713 // what the appropriate type is.
714 QualType ValType = pointerType->getPointeeType();
715 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
716 if (IsLdrex)
717 AddrType.addConst();
718
719 // Issue a warning if the cast is dodgy.
720 CastKind CastNeeded = CK_NoOp;
721 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
722 CastNeeded = CK_BitCast;
723 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
724 << PointerArg->getType()
725 << Context.getPointerType(AddrType)
726 << AA_Passing << PointerArg->getSourceRange();
727 }
728
729 // Finally, do the cast and replace the argument with the corrected version.
730 AddrType = Context.getPointerType(AddrType);
731 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
732 if (PointerArgRes.isInvalid())
733 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000734 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000735
736 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
737
738 // In general, we allow ints, floats and pointers to be loaded and stored.
739 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
740 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
741 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
742 << PointerArg->getType() << PointerArg->getSourceRange();
743 return true;
744 }
745
746 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000747 if (Context.getTypeSize(ValType) > MaxWidth) {
748 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000749 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
750 << PointerArg->getType() << PointerArg->getSourceRange();
751 return true;
752 }
753
754 switch (ValType.getObjCLifetime()) {
755 case Qualifiers::OCL_None:
756 case Qualifiers::OCL_ExplicitNone:
757 // okay
758 break;
759
760 case Qualifiers::OCL_Weak:
761 case Qualifiers::OCL_Strong:
762 case Qualifiers::OCL_Autoreleasing:
763 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
764 << ValType << PointerArg->getSourceRange();
765 return true;
766 }
767
768
769 if (IsLdrex) {
770 TheCall->setType(ValType);
771 return false;
772 }
773
774 // Initialize the argument to be stored.
775 ExprResult ValArg = TheCall->getArg(0);
776 InitializedEntity Entity = InitializedEntity::InitializeParameter(
777 Context, ValType, /*consume*/ false);
778 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
779 if (ValArg.isInvalid())
780 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000781 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000782
783 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
784 // but the custom checker bypasses all default analysis.
785 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000786 return false;
787}
788
Nate Begeman4904e322010-06-08 02:47:44 +0000789bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000790 llvm::APSInt Result;
791
Tim Northover6aacd492013-07-16 09:47:53 +0000792 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000793 BuiltinID == ARM::BI__builtin_arm_ldaex ||
794 BuiltinID == ARM::BI__builtin_arm_strex ||
795 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000796 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000797 }
798
Yi Kong26d104a2014-08-13 19:18:14 +0000799 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
800 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
801 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
802 }
803
Tim Northover12670412014-02-19 10:37:05 +0000804 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
805 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000806
Yi Kong4efadfb2014-07-03 16:01:25 +0000807 // For intrinsics which take an immediate value as part of the instruction,
808 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000809 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000810 switch (BuiltinID) {
811 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000812 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
813 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000814 case ARM::BI__builtin_arm_vcvtr_f:
815 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000816 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000817 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000818 case ARM::BI__builtin_arm_isb:
819 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000820 }
Nate Begemand773fe62010-06-13 04:47:52 +0000821
Nate Begemanf568b072010-08-03 21:32:34 +0000822 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000823 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000824}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000825
Tim Northover573cbee2014-05-24 12:52:07 +0000826bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000827 CallExpr *TheCall) {
828 llvm::APSInt Result;
829
Tim Northover573cbee2014-05-24 12:52:07 +0000830 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000831 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
832 BuiltinID == AArch64::BI__builtin_arm_strex ||
833 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000834 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
835 }
836
Yi Konga5548432014-08-13 19:18:20 +0000837 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
838 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
839 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
840 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
841 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
842 }
843
Tim Northovera2ee4332014-03-29 15:09:45 +0000844 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
845 return true;
846
Yi Kong19a29ac2014-07-17 10:52:06 +0000847 // For intrinsics which take an immediate value as part of the instruction,
848 // range check them here.
849 unsigned i = 0, l = 0, u = 0;
850 switch (BuiltinID) {
851 default: return false;
852 case AArch64::BI__builtin_arm_dmb:
853 case AArch64::BI__builtin_arm_dsb:
854 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
855 }
856
Yi Kong19a29ac2014-07-17 10:52:06 +0000857 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000858}
859
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000860bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
861 unsigned i = 0, l = 0, u = 0;
862 switch (BuiltinID) {
863 default: return false;
864 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
865 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000866 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
867 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
868 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
869 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
870 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000871 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000872
Richard Sandiford28940af2014-04-16 08:47:51 +0000873 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000874}
875
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000876bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000877 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000878 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000879 default: return false;
880 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +0000881 case X86::BI__builtin_ia32_vextractf128_pd256:
882 case X86::BI__builtin_ia32_vextractf128_ps256:
883 case X86::BI__builtin_ia32_vextractf128_si256:
884 case X86::BI__builtin_ia32_extract128i256: i = 1, l = 0, u = 1; break;
885 case X86::BI__builtin_ia32_vinsertf128_pd256:
886 case X86::BI__builtin_ia32_vinsertf128_ps256:
887 case X86::BI__builtin_ia32_vinsertf128_si256:
888 case X86::BI__builtin_ia32_insert128i256:
889 case X86::BI__builtin_ia32_blendpd: i = 2, l = 0; u = 1; break;
890 case X86::BI__builtin_ia32_blendps:
891 case X86::BI__builtin_ia32_blendpd256:
892 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +0000893 case X86::BI__builtin_ia32_vpermil2pd:
894 case X86::BI__builtin_ia32_vpermil2pd256:
895 case X86::BI__builtin_ia32_vpermil2ps:
896 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +0000897 case X86::BI__builtin_ia32_cmpb128_mask:
898 case X86::BI__builtin_ia32_cmpw128_mask:
899 case X86::BI__builtin_ia32_cmpd128_mask:
900 case X86::BI__builtin_ia32_cmpq128_mask:
901 case X86::BI__builtin_ia32_cmpb256_mask:
902 case X86::BI__builtin_ia32_cmpw256_mask:
903 case X86::BI__builtin_ia32_cmpd256_mask:
904 case X86::BI__builtin_ia32_cmpq256_mask:
905 case X86::BI__builtin_ia32_cmpb512_mask:
906 case X86::BI__builtin_ia32_cmpw512_mask:
907 case X86::BI__builtin_ia32_cmpd512_mask:
908 case X86::BI__builtin_ia32_cmpq512_mask:
909 case X86::BI__builtin_ia32_ucmpb128_mask:
910 case X86::BI__builtin_ia32_ucmpw128_mask:
911 case X86::BI__builtin_ia32_ucmpd128_mask:
912 case X86::BI__builtin_ia32_ucmpq128_mask:
913 case X86::BI__builtin_ia32_ucmpb256_mask:
914 case X86::BI__builtin_ia32_ucmpw256_mask:
915 case X86::BI__builtin_ia32_ucmpd256_mask:
916 case X86::BI__builtin_ia32_ucmpq256_mask:
917 case X86::BI__builtin_ia32_ucmpb512_mask:
918 case X86::BI__builtin_ia32_ucmpw512_mask:
919 case X86::BI__builtin_ia32_ucmpd512_mask:
920 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +0000921 case X86::BI__builtin_ia32_roundps:
922 case X86::BI__builtin_ia32_roundpd:
923 case X86::BI__builtin_ia32_roundps256:
924 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
925 case X86::BI__builtin_ia32_roundss:
926 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
927 case X86::BI__builtin_ia32_cmpps:
928 case X86::BI__builtin_ia32_cmpss:
929 case X86::BI__builtin_ia32_cmppd:
930 case X86::BI__builtin_ia32_cmpsd:
931 case X86::BI__builtin_ia32_cmpps256:
932 case X86::BI__builtin_ia32_cmppd256:
933 case X86::BI__builtin_ia32_cmpps512_mask:
934 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +0000935 case X86::BI__builtin_ia32_vpcomub:
936 case X86::BI__builtin_ia32_vpcomuw:
937 case X86::BI__builtin_ia32_vpcomud:
938 case X86::BI__builtin_ia32_vpcomuq:
939 case X86::BI__builtin_ia32_vpcomb:
940 case X86::BI__builtin_ia32_vpcomw:
941 case X86::BI__builtin_ia32_vpcomd:
942 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000943 }
Craig Topperdd84ec52014-12-27 07:00:08 +0000944 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000945}
946
Richard Smith55ce3522012-06-25 20:30:08 +0000947/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
948/// parameter with the FormatAttr's correct format_idx and firstDataArg.
949/// Returns true when the format fits the function and the FormatStringInfo has
950/// been populated.
951bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
952 FormatStringInfo *FSI) {
953 FSI->HasVAListArg = Format->getFirstArg() == 0;
954 FSI->FormatIdx = Format->getFormatIdx() - 1;
955 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000956
Richard Smith55ce3522012-06-25 20:30:08 +0000957 // The way the format attribute works in GCC, the implicit this argument
958 // of member functions is counted. However, it doesn't appear in our own
959 // lists, so decrement format_idx in that case.
960 if (IsCXXMember) {
961 if(FSI->FormatIdx == 0)
962 return false;
963 --FSI->FormatIdx;
964 if (FSI->FirstDataArg != 0)
965 --FSI->FirstDataArg;
966 }
967 return true;
968}
Mike Stump11289f42009-09-09 15:08:12 +0000969
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000970/// Checks if a the given expression evaluates to null.
971///
972/// \brief Returns true if the value evaluates to null.
973static bool CheckNonNullExpr(Sema &S,
974 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000975 // As a special case, transparent unions initialized with zero are
976 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000977 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000978 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
979 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000980 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000981 if (const InitListExpr *ILE =
982 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000983 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000984 }
985
986 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000987 return (!Expr->isValueDependent() &&
988 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
989 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000990}
991
992static void CheckNonNullArgument(Sema &S,
993 const Expr *ArgExpr,
994 SourceLocation CallSiteLoc) {
995 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000996 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
997}
998
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000999bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1000 FormatStringInfo FSI;
1001 if ((GetFormatStringType(Format) == FST_NSString) &&
1002 getFormatStringInfo(Format, false, &FSI)) {
1003 Idx = FSI.FormatIdx;
1004 return true;
1005 }
1006 return false;
1007}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001008/// \brief Diagnose use of %s directive in an NSString which is being passed
1009/// as formatting string to formatting method.
1010static void
1011DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1012 const NamedDecl *FDecl,
1013 Expr **Args,
1014 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001015 unsigned Idx = 0;
1016 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001017 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1018 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001019 Idx = 2;
1020 Format = true;
1021 }
1022 else
1023 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1024 if (S.GetFormatNSStringIdx(I, Idx)) {
1025 Format = true;
1026 break;
1027 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001028 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001029 if (!Format || NumArgs <= Idx)
1030 return;
1031 const Expr *FormatExpr = Args[Idx];
1032 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1033 FormatExpr = CSCE->getSubExpr();
1034 const StringLiteral *FormatString;
1035 if (const ObjCStringLiteral *OSL =
1036 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1037 FormatString = OSL->getString();
1038 else
1039 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1040 if (!FormatString)
1041 return;
1042 if (S.FormatStringHasSArg(FormatString)) {
1043 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1044 << "%s" << 1 << 1;
1045 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1046 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001047 }
1048}
1049
Ted Kremenek2bc73332014-01-17 06:24:43 +00001050static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001051 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +00001052 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001053 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001054 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001055 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001056 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001057 if (!NonNull->args_size()) {
1058 // Easy case: all pointer arguments are nonnull.
1059 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +00001060 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +00001061 CheckNonNullArgument(S, Arg, CallSiteLoc);
1062 return;
1063 }
1064
1065 for (unsigned Val : NonNull->args()) {
1066 if (Val >= Args.size())
1067 continue;
1068 if (NonNullArgs.empty())
1069 NonNullArgs.resize(Args.size());
1070 NonNullArgs.set(Val);
1071 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001072 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001073
1074 // Check the attributes on the parameters.
1075 ArrayRef<ParmVarDecl*> parms;
1076 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1077 parms = FD->parameters();
1078 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1079 parms = MD->parameters();
1080
Richard Smith588bd9b2014-08-27 04:59:42 +00001081 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001082 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +00001083 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001084 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +00001085 if (PVD->hasAttr<NonNullAttr>() ||
1086 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1087 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +00001088 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001089
1090 // In case this is a variadic call, check any remaining arguments.
1091 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1092 if (NonNullArgs[ArgIndex])
1093 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +00001094}
1095
Richard Smith55ce3522012-06-25 20:30:08 +00001096/// Handles the checks for format strings, non-POD arguments to vararg
1097/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00001098void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1099 unsigned NumParams, bool IsMemberFunction,
1100 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001101 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001102 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001103 if (CurContext->isDependentContext())
1104 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001105
Ted Kremenekb8176da2010-09-09 04:33:05 +00001106 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001107 llvm::SmallBitVector CheckedVarArgs;
1108 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001109 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001110 // Only create vector if there are format attributes.
1111 CheckedVarArgs.resize(Args.size());
1112
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001113 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001114 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001115 }
Richard Smithd7293d72013-08-05 18:49:43 +00001116 }
Richard Smith55ce3522012-06-25 20:30:08 +00001117
1118 // Refuse POD arguments that weren't caught by the format string
1119 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001120 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001121 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001122 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001123 if (const Expr *Arg = Args[ArgIdx]) {
1124 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1125 checkVariadicArgument(Arg, CallType);
1126 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001127 }
Richard Smithd7293d72013-08-05 18:49:43 +00001128 }
Mike Stump11289f42009-09-09 15:08:12 +00001129
Richard Trieu41bc0992013-06-22 00:20:41 +00001130 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001131 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001132
Richard Trieu41bc0992013-06-22 00:20:41 +00001133 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001134 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1135 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001136 }
Richard Smith55ce3522012-06-25 20:30:08 +00001137}
1138
1139/// CheckConstructorCall - Check a constructor call for correctness and safety
1140/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001141void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1142 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001143 const FunctionProtoType *Proto,
1144 SourceLocation Loc) {
1145 VariadicCallType CallType =
1146 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +00001147 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +00001148 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1149}
1150
1151/// CheckFunctionCall - Check a direct function call for various correctness
1152/// and safety properties not strictly enforced by the C type system.
1153bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1154 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001155 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1156 isa<CXXMethodDecl>(FDecl);
1157 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1158 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001159 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1160 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001161 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +00001162 Expr** Args = TheCall->getArgs();
1163 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001164 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001165 // If this is a call to a member operator, hide the first argument
1166 // from checkCall.
1167 // FIXME: Our choice of AST representation here is less than ideal.
1168 ++Args;
1169 --NumArgs;
1170 }
Craig Topper8c2a2a02014-08-30 16:55:39 +00001171 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +00001172 IsMemberFunction, TheCall->getRParenLoc(),
1173 TheCall->getCallee()->getSourceRange(), CallType);
1174
1175 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1176 // None of the checks below are needed for functions that don't have
1177 // simple names (e.g., C++ conversion functions).
1178 if (!FnInfo)
1179 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001180
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001181 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001182 if (getLangOpts().ObjC1)
1183 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001184
Anna Zaks22122702012-01-17 00:37:07 +00001185 unsigned CMId = FDecl->getMemoryFunctionKind();
1186 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001187 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001188
Anna Zaks201d4892012-01-13 21:52:01 +00001189 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001190 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001191 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001192 else if (CMId == Builtin::BIstrncat)
1193 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001194 else
Anna Zaks22122702012-01-17 00:37:07 +00001195 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001196
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001197 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001198}
1199
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001200bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001201 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001202 VariadicCallType CallType =
1203 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001204
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001205 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001206 /*IsMemberFunction=*/false,
1207 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001208
1209 return false;
1210}
1211
Richard Trieu664c4c62013-06-20 21:03:13 +00001212bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1213 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001214 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1215 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001216 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001217
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001218 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +00001219 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001220 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001221
Richard Trieu664c4c62013-06-20 21:03:13 +00001222 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001223 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001224 CallType = VariadicDoesNotApply;
1225 } else if (Ty->isBlockPointerType()) {
1226 CallType = VariadicBlock;
1227 } else { // Ty->isFunctionPointerType()
1228 CallType = VariadicFunction;
1229 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001230 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001231
Craig Topper8c2a2a02014-08-30 16:55:39 +00001232 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1233 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001234 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001235 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001236
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001237 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001238}
1239
Richard Trieu41bc0992013-06-22 00:20:41 +00001240/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1241/// such as function pointers returned from functions.
1242bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001243 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001244 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001245 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001246
Craig Topperc3ec1492014-05-26 06:22:03 +00001247 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001248 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001249 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001250 TheCall->getCallee()->getSourceRange(), CallType);
1251
1252 return false;
1253}
1254
Tim Northovere94a34c2014-03-11 10:49:14 +00001255static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1256 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1257 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1258 return false;
1259
1260 switch (Op) {
1261 case AtomicExpr::AO__c11_atomic_init:
1262 llvm_unreachable("There is no ordering argument for an init");
1263
1264 case AtomicExpr::AO__c11_atomic_load:
1265 case AtomicExpr::AO__atomic_load_n:
1266 case AtomicExpr::AO__atomic_load:
1267 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1268 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1269
1270 case AtomicExpr::AO__c11_atomic_store:
1271 case AtomicExpr::AO__atomic_store:
1272 case AtomicExpr::AO__atomic_store_n:
1273 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1274 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1275 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1276
1277 default:
1278 return true;
1279 }
1280}
1281
Richard Smithfeea8832012-04-12 05:08:17 +00001282ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1283 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001284 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1285 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001286
Richard Smithfeea8832012-04-12 05:08:17 +00001287 // All these operations take one of the following forms:
1288 enum {
1289 // C __c11_atomic_init(A *, C)
1290 Init,
1291 // C __c11_atomic_load(A *, int)
1292 Load,
1293 // void __atomic_load(A *, CP, int)
1294 Copy,
1295 // C __c11_atomic_add(A *, M, int)
1296 Arithmetic,
1297 // C __atomic_exchange_n(A *, CP, int)
1298 Xchg,
1299 // void __atomic_exchange(A *, C *, CP, int)
1300 GNUXchg,
1301 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1302 C11CmpXchg,
1303 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1304 GNUCmpXchg
1305 } Form = Init;
1306 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1307 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1308 // where:
1309 // C is an appropriate type,
1310 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1311 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1312 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1313 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001314
Richard Smithfeea8832012-04-12 05:08:17 +00001315 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1316 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1317 && "need to update code for modified C11 atomics");
1318 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1319 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1320 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1321 Op == AtomicExpr::AO__atomic_store_n ||
1322 Op == AtomicExpr::AO__atomic_exchange_n ||
1323 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1324 bool IsAddSub = false;
1325
1326 switch (Op) {
1327 case AtomicExpr::AO__c11_atomic_init:
1328 Form = Init;
1329 break;
1330
1331 case AtomicExpr::AO__c11_atomic_load:
1332 case AtomicExpr::AO__atomic_load_n:
1333 Form = Load;
1334 break;
1335
1336 case AtomicExpr::AO__c11_atomic_store:
1337 case AtomicExpr::AO__atomic_load:
1338 case AtomicExpr::AO__atomic_store:
1339 case AtomicExpr::AO__atomic_store_n:
1340 Form = Copy;
1341 break;
1342
1343 case AtomicExpr::AO__c11_atomic_fetch_add:
1344 case AtomicExpr::AO__c11_atomic_fetch_sub:
1345 case AtomicExpr::AO__atomic_fetch_add:
1346 case AtomicExpr::AO__atomic_fetch_sub:
1347 case AtomicExpr::AO__atomic_add_fetch:
1348 case AtomicExpr::AO__atomic_sub_fetch:
1349 IsAddSub = true;
1350 // Fall through.
1351 case AtomicExpr::AO__c11_atomic_fetch_and:
1352 case AtomicExpr::AO__c11_atomic_fetch_or:
1353 case AtomicExpr::AO__c11_atomic_fetch_xor:
1354 case AtomicExpr::AO__atomic_fetch_and:
1355 case AtomicExpr::AO__atomic_fetch_or:
1356 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001357 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001358 case AtomicExpr::AO__atomic_and_fetch:
1359 case AtomicExpr::AO__atomic_or_fetch:
1360 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001361 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001362 Form = Arithmetic;
1363 break;
1364
1365 case AtomicExpr::AO__c11_atomic_exchange:
1366 case AtomicExpr::AO__atomic_exchange_n:
1367 Form = Xchg;
1368 break;
1369
1370 case AtomicExpr::AO__atomic_exchange:
1371 Form = GNUXchg;
1372 break;
1373
1374 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1375 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1376 Form = C11CmpXchg;
1377 break;
1378
1379 case AtomicExpr::AO__atomic_compare_exchange:
1380 case AtomicExpr::AO__atomic_compare_exchange_n:
1381 Form = GNUCmpXchg;
1382 break;
1383 }
1384
1385 // Check we have the right number of arguments.
1386 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001387 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001388 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001389 << TheCall->getCallee()->getSourceRange();
1390 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001391 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1392 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001393 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001394 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001395 << TheCall->getCallee()->getSourceRange();
1396 return ExprError();
1397 }
1398
Richard Smithfeea8832012-04-12 05:08:17 +00001399 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001400 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001401 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1402 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1403 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001404 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001405 << Ptr->getType() << Ptr->getSourceRange();
1406 return ExprError();
1407 }
1408
Richard Smithfeea8832012-04-12 05:08:17 +00001409 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1410 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1411 QualType ValType = AtomTy; // 'C'
1412 if (IsC11) {
1413 if (!AtomTy->isAtomicType()) {
1414 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1415 << Ptr->getType() << Ptr->getSourceRange();
1416 return ExprError();
1417 }
Richard Smithe00921a2012-09-15 06:09:58 +00001418 if (AtomTy.isConstQualified()) {
1419 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1420 << Ptr->getType() << Ptr->getSourceRange();
1421 return ExprError();
1422 }
Richard Smithfeea8832012-04-12 05:08:17 +00001423 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001424 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001425
Richard Smithfeea8832012-04-12 05:08:17 +00001426 // For an arithmetic operation, the implied arithmetic must be well-formed.
1427 if (Form == Arithmetic) {
1428 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1429 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1430 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1431 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1432 return ExprError();
1433 }
1434 if (!IsAddSub && !ValType->isIntegerType()) {
1435 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1436 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1437 return ExprError();
1438 }
David Majnemere85cff82015-01-28 05:48:06 +00001439 if (IsC11 && ValType->isPointerType() &&
1440 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1441 diag::err_incomplete_type)) {
1442 return ExprError();
1443 }
Richard Smithfeea8832012-04-12 05:08:17 +00001444 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1445 // For __atomic_*_n operations, the value type must be a scalar integral or
1446 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001447 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001448 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1449 return ExprError();
1450 }
1451
Eli Friedmanaa769812013-09-11 03:49:34 +00001452 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1453 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001454 // For GNU atomics, require a trivially-copyable type. This is not part of
1455 // the GNU atomics specification, but we enforce it for sanity.
1456 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001457 << Ptr->getType() << Ptr->getSourceRange();
1458 return ExprError();
1459 }
1460
Richard Smithfeea8832012-04-12 05:08:17 +00001461 // FIXME: For any builtin other than a load, the ValType must not be
1462 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001463
1464 switch (ValType.getObjCLifetime()) {
1465 case Qualifiers::OCL_None:
1466 case Qualifiers::OCL_ExplicitNone:
1467 // okay
1468 break;
1469
1470 case Qualifiers::OCL_Weak:
1471 case Qualifiers::OCL_Strong:
1472 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001473 // FIXME: Can this happen? By this point, ValType should be known
1474 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001475 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1476 << ValType << Ptr->getSourceRange();
1477 return ExprError();
1478 }
1479
1480 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001481 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001482 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001483 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001484 ResultType = Context.BoolTy;
1485
Richard Smithfeea8832012-04-12 05:08:17 +00001486 // The type of a parameter passed 'by value'. In the GNU atomics, such
1487 // arguments are actually passed as pointers.
1488 QualType ByValType = ValType; // 'CP'
1489 if (!IsC11 && !IsN)
1490 ByValType = Ptr->getType();
1491
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001492 // The first argument --- the pointer --- has a fixed type; we
1493 // deduce the types of the rest of the arguments accordingly. Walk
1494 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001495 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001496 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001497 if (i < NumVals[Form] + 1) {
1498 switch (i) {
1499 case 1:
1500 // The second argument is the non-atomic operand. For arithmetic, this
1501 // is always passed by value, and for a compare_exchange it is always
1502 // passed by address. For the rest, GNU uses by-address and C11 uses
1503 // by-value.
1504 assert(Form != Load);
1505 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1506 Ty = ValType;
1507 else if (Form == Copy || Form == Xchg)
1508 Ty = ByValType;
1509 else if (Form == Arithmetic)
1510 Ty = Context.getPointerDiffType();
1511 else
1512 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1513 break;
1514 case 2:
1515 // The third argument to compare_exchange / GNU exchange is a
1516 // (pointer to a) desired value.
1517 Ty = ByValType;
1518 break;
1519 case 3:
1520 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1521 Ty = Context.BoolTy;
1522 break;
1523 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001524 } else {
1525 // The order(s) are always converted to int.
1526 Ty = Context.IntTy;
1527 }
Richard Smithfeea8832012-04-12 05:08:17 +00001528
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001529 InitializedEntity Entity =
1530 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001531 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001532 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1533 if (Arg.isInvalid())
1534 return true;
1535 TheCall->setArg(i, Arg.get());
1536 }
1537
Richard Smithfeea8832012-04-12 05:08:17 +00001538 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001539 SmallVector<Expr*, 5> SubExprs;
1540 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001541 switch (Form) {
1542 case Init:
1543 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001544 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001545 break;
1546 case Load:
1547 SubExprs.push_back(TheCall->getArg(1)); // Order
1548 break;
1549 case Copy:
1550 case Arithmetic:
1551 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001552 SubExprs.push_back(TheCall->getArg(2)); // Order
1553 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001554 break;
1555 case GNUXchg:
1556 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1557 SubExprs.push_back(TheCall->getArg(3)); // Order
1558 SubExprs.push_back(TheCall->getArg(1)); // Val1
1559 SubExprs.push_back(TheCall->getArg(2)); // Val2
1560 break;
1561 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001562 SubExprs.push_back(TheCall->getArg(3)); // Order
1563 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001564 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001565 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001566 break;
1567 case GNUCmpXchg:
1568 SubExprs.push_back(TheCall->getArg(4)); // Order
1569 SubExprs.push_back(TheCall->getArg(1)); // Val1
1570 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1571 SubExprs.push_back(TheCall->getArg(2)); // Val2
1572 SubExprs.push_back(TheCall->getArg(3)); // Weak
1573 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001574 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001575
1576 if (SubExprs.size() >= 2 && Form != Init) {
1577 llvm::APSInt Result(32);
1578 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1579 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001580 Diag(SubExprs[1]->getLocStart(),
1581 diag::warn_atomic_op_has_invalid_memory_order)
1582 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001583 }
1584
Fariborz Jahanian615de762013-05-28 17:37:39 +00001585 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1586 SubExprs, ResultType, Op,
1587 TheCall->getRParenLoc());
1588
1589 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1590 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1591 Context.AtomicUsesUnsupportedLibcall(AE))
1592 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1593 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001594
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001595 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001596}
1597
1598
John McCall29ad95b2011-08-27 01:09:30 +00001599/// checkBuiltinArgument - Given a call to a builtin function, perform
1600/// normal type-checking on the given argument, updating the call in
1601/// place. This is useful when a builtin function requires custom
1602/// type-checking for some of its arguments but not necessarily all of
1603/// them.
1604///
1605/// Returns true on error.
1606static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1607 FunctionDecl *Fn = E->getDirectCallee();
1608 assert(Fn && "builtin call without direct callee!");
1609
1610 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1611 InitializedEntity Entity =
1612 InitializedEntity::InitializeParameter(S.Context, Param);
1613
1614 ExprResult Arg = E->getArg(0);
1615 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1616 if (Arg.isInvalid())
1617 return true;
1618
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001619 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001620 return false;
1621}
1622
Chris Lattnerdc046542009-05-08 06:58:22 +00001623/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1624/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1625/// type of its first argument. The main ActOnCallExpr routines have already
1626/// promoted the types of arguments because all of these calls are prototyped as
1627/// void(...).
1628///
1629/// This function goes through and does final semantic checking for these
1630/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001631ExprResult
1632Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001633 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001634 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1635 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1636
1637 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001638 if (TheCall->getNumArgs() < 1) {
1639 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1640 << 0 << 1 << TheCall->getNumArgs()
1641 << TheCall->getCallee()->getSourceRange();
1642 return ExprError();
1643 }
Mike Stump11289f42009-09-09 15:08:12 +00001644
Chris Lattnerdc046542009-05-08 06:58:22 +00001645 // Inspect the first argument of the atomic builtin. This should always be
1646 // a pointer type, whose element is an integral scalar or pointer type.
1647 // Because it is a pointer type, we don't have to worry about any implicit
1648 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001649 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001650 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001651 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1652 if (FirstArgResult.isInvalid())
1653 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001654 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001655 TheCall->setArg(0, FirstArg);
1656
John McCall31168b02011-06-15 23:02:42 +00001657 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1658 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001659 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1660 << FirstArg->getType() << FirstArg->getSourceRange();
1661 return ExprError();
1662 }
Mike Stump11289f42009-09-09 15:08:12 +00001663
John McCall31168b02011-06-15 23:02:42 +00001664 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001665 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001666 !ValType->isBlockPointerType()) {
1667 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1668 << FirstArg->getType() << FirstArg->getSourceRange();
1669 return ExprError();
1670 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001671
John McCall31168b02011-06-15 23:02:42 +00001672 switch (ValType.getObjCLifetime()) {
1673 case Qualifiers::OCL_None:
1674 case Qualifiers::OCL_ExplicitNone:
1675 // okay
1676 break;
1677
1678 case Qualifiers::OCL_Weak:
1679 case Qualifiers::OCL_Strong:
1680 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001681 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001682 << ValType << FirstArg->getSourceRange();
1683 return ExprError();
1684 }
1685
John McCallb50451a2011-10-05 07:41:44 +00001686 // Strip any qualifiers off ValType.
1687 ValType = ValType.getUnqualifiedType();
1688
Chandler Carruth3973af72010-07-18 20:54:12 +00001689 // The majority of builtins return a value, but a few have special return
1690 // types, so allow them to override appropriately below.
1691 QualType ResultType = ValType;
1692
Chris Lattnerdc046542009-05-08 06:58:22 +00001693 // We need to figure out which concrete builtin this maps onto. For example,
1694 // __sync_fetch_and_add with a 2 byte object turns into
1695 // __sync_fetch_and_add_2.
1696#define BUILTIN_ROW(x) \
1697 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1698 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001699
Chris Lattnerdc046542009-05-08 06:58:22 +00001700 static const unsigned BuiltinIndices[][5] = {
1701 BUILTIN_ROW(__sync_fetch_and_add),
1702 BUILTIN_ROW(__sync_fetch_and_sub),
1703 BUILTIN_ROW(__sync_fetch_and_or),
1704 BUILTIN_ROW(__sync_fetch_and_and),
1705 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001706 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001707
Chris Lattnerdc046542009-05-08 06:58:22 +00001708 BUILTIN_ROW(__sync_add_and_fetch),
1709 BUILTIN_ROW(__sync_sub_and_fetch),
1710 BUILTIN_ROW(__sync_and_and_fetch),
1711 BUILTIN_ROW(__sync_or_and_fetch),
1712 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001713 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001714
Chris Lattnerdc046542009-05-08 06:58:22 +00001715 BUILTIN_ROW(__sync_val_compare_and_swap),
1716 BUILTIN_ROW(__sync_bool_compare_and_swap),
1717 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001718 BUILTIN_ROW(__sync_lock_release),
1719 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001720 };
Mike Stump11289f42009-09-09 15:08:12 +00001721#undef BUILTIN_ROW
1722
Chris Lattnerdc046542009-05-08 06:58:22 +00001723 // Determine the index of the size.
1724 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001725 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001726 case 1: SizeIndex = 0; break;
1727 case 2: SizeIndex = 1; break;
1728 case 4: SizeIndex = 2; break;
1729 case 8: SizeIndex = 3; break;
1730 case 16: SizeIndex = 4; break;
1731 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001732 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1733 << FirstArg->getType() << FirstArg->getSourceRange();
1734 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001735 }
Mike Stump11289f42009-09-09 15:08:12 +00001736
Chris Lattnerdc046542009-05-08 06:58:22 +00001737 // Each of these builtins has one pointer argument, followed by some number of
1738 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1739 // that we ignore. Find out which row of BuiltinIndices to read from as well
1740 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001741 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001742 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001743 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001744 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001745 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001746 case Builtin::BI__sync_fetch_and_add:
1747 case Builtin::BI__sync_fetch_and_add_1:
1748 case Builtin::BI__sync_fetch_and_add_2:
1749 case Builtin::BI__sync_fetch_and_add_4:
1750 case Builtin::BI__sync_fetch_and_add_8:
1751 case Builtin::BI__sync_fetch_and_add_16:
1752 BuiltinIndex = 0;
1753 break;
1754
1755 case Builtin::BI__sync_fetch_and_sub:
1756 case Builtin::BI__sync_fetch_and_sub_1:
1757 case Builtin::BI__sync_fetch_and_sub_2:
1758 case Builtin::BI__sync_fetch_and_sub_4:
1759 case Builtin::BI__sync_fetch_and_sub_8:
1760 case Builtin::BI__sync_fetch_and_sub_16:
1761 BuiltinIndex = 1;
1762 break;
1763
1764 case Builtin::BI__sync_fetch_and_or:
1765 case Builtin::BI__sync_fetch_and_or_1:
1766 case Builtin::BI__sync_fetch_and_or_2:
1767 case Builtin::BI__sync_fetch_and_or_4:
1768 case Builtin::BI__sync_fetch_and_or_8:
1769 case Builtin::BI__sync_fetch_and_or_16:
1770 BuiltinIndex = 2;
1771 break;
1772
1773 case Builtin::BI__sync_fetch_and_and:
1774 case Builtin::BI__sync_fetch_and_and_1:
1775 case Builtin::BI__sync_fetch_and_and_2:
1776 case Builtin::BI__sync_fetch_and_and_4:
1777 case Builtin::BI__sync_fetch_and_and_8:
1778 case Builtin::BI__sync_fetch_and_and_16:
1779 BuiltinIndex = 3;
1780 break;
Mike Stump11289f42009-09-09 15:08:12 +00001781
Douglas Gregor73722482011-11-28 16:30:08 +00001782 case Builtin::BI__sync_fetch_and_xor:
1783 case Builtin::BI__sync_fetch_and_xor_1:
1784 case Builtin::BI__sync_fetch_and_xor_2:
1785 case Builtin::BI__sync_fetch_and_xor_4:
1786 case Builtin::BI__sync_fetch_and_xor_8:
1787 case Builtin::BI__sync_fetch_and_xor_16:
1788 BuiltinIndex = 4;
1789 break;
1790
Hal Finkeld2208b52014-10-02 20:53:50 +00001791 case Builtin::BI__sync_fetch_and_nand:
1792 case Builtin::BI__sync_fetch_and_nand_1:
1793 case Builtin::BI__sync_fetch_and_nand_2:
1794 case Builtin::BI__sync_fetch_and_nand_4:
1795 case Builtin::BI__sync_fetch_and_nand_8:
1796 case Builtin::BI__sync_fetch_and_nand_16:
1797 BuiltinIndex = 5;
1798 WarnAboutSemanticsChange = true;
1799 break;
1800
Douglas Gregor73722482011-11-28 16:30:08 +00001801 case Builtin::BI__sync_add_and_fetch:
1802 case Builtin::BI__sync_add_and_fetch_1:
1803 case Builtin::BI__sync_add_and_fetch_2:
1804 case Builtin::BI__sync_add_and_fetch_4:
1805 case Builtin::BI__sync_add_and_fetch_8:
1806 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001807 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00001808 break;
1809
1810 case Builtin::BI__sync_sub_and_fetch:
1811 case Builtin::BI__sync_sub_and_fetch_1:
1812 case Builtin::BI__sync_sub_and_fetch_2:
1813 case Builtin::BI__sync_sub_and_fetch_4:
1814 case Builtin::BI__sync_sub_and_fetch_8:
1815 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001816 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00001817 break;
1818
1819 case Builtin::BI__sync_and_and_fetch:
1820 case Builtin::BI__sync_and_and_fetch_1:
1821 case Builtin::BI__sync_and_and_fetch_2:
1822 case Builtin::BI__sync_and_and_fetch_4:
1823 case Builtin::BI__sync_and_and_fetch_8:
1824 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001825 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00001826 break;
1827
1828 case Builtin::BI__sync_or_and_fetch:
1829 case Builtin::BI__sync_or_and_fetch_1:
1830 case Builtin::BI__sync_or_and_fetch_2:
1831 case Builtin::BI__sync_or_and_fetch_4:
1832 case Builtin::BI__sync_or_and_fetch_8:
1833 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001834 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00001835 break;
1836
1837 case Builtin::BI__sync_xor_and_fetch:
1838 case Builtin::BI__sync_xor_and_fetch_1:
1839 case Builtin::BI__sync_xor_and_fetch_2:
1840 case Builtin::BI__sync_xor_and_fetch_4:
1841 case Builtin::BI__sync_xor_and_fetch_8:
1842 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001843 BuiltinIndex = 10;
1844 break;
1845
1846 case Builtin::BI__sync_nand_and_fetch:
1847 case Builtin::BI__sync_nand_and_fetch_1:
1848 case Builtin::BI__sync_nand_and_fetch_2:
1849 case Builtin::BI__sync_nand_and_fetch_4:
1850 case Builtin::BI__sync_nand_and_fetch_8:
1851 case Builtin::BI__sync_nand_and_fetch_16:
1852 BuiltinIndex = 11;
1853 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00001854 break;
Mike Stump11289f42009-09-09 15:08:12 +00001855
Chris Lattnerdc046542009-05-08 06:58:22 +00001856 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001857 case Builtin::BI__sync_val_compare_and_swap_1:
1858 case Builtin::BI__sync_val_compare_and_swap_2:
1859 case Builtin::BI__sync_val_compare_and_swap_4:
1860 case Builtin::BI__sync_val_compare_and_swap_8:
1861 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001862 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00001863 NumFixed = 2;
1864 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001865
Chris Lattnerdc046542009-05-08 06:58:22 +00001866 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001867 case Builtin::BI__sync_bool_compare_and_swap_1:
1868 case Builtin::BI__sync_bool_compare_and_swap_2:
1869 case Builtin::BI__sync_bool_compare_and_swap_4:
1870 case Builtin::BI__sync_bool_compare_and_swap_8:
1871 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001872 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001873 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001874 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001875 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001876
1877 case Builtin::BI__sync_lock_test_and_set:
1878 case Builtin::BI__sync_lock_test_and_set_1:
1879 case Builtin::BI__sync_lock_test_and_set_2:
1880 case Builtin::BI__sync_lock_test_and_set_4:
1881 case Builtin::BI__sync_lock_test_and_set_8:
1882 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001883 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00001884 break;
1885
Chris Lattnerdc046542009-05-08 06:58:22 +00001886 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001887 case Builtin::BI__sync_lock_release_1:
1888 case Builtin::BI__sync_lock_release_2:
1889 case Builtin::BI__sync_lock_release_4:
1890 case Builtin::BI__sync_lock_release_8:
1891 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001892 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00001893 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001894 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001895 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001896
1897 case Builtin::BI__sync_swap:
1898 case Builtin::BI__sync_swap_1:
1899 case Builtin::BI__sync_swap_2:
1900 case Builtin::BI__sync_swap_4:
1901 case Builtin::BI__sync_swap_8:
1902 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001903 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00001904 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001905 }
Mike Stump11289f42009-09-09 15:08:12 +00001906
Chris Lattnerdc046542009-05-08 06:58:22 +00001907 // Now that we know how many fixed arguments we expect, first check that we
1908 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001909 if (TheCall->getNumArgs() < 1+NumFixed) {
1910 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1911 << 0 << 1+NumFixed << TheCall->getNumArgs()
1912 << TheCall->getCallee()->getSourceRange();
1913 return ExprError();
1914 }
Mike Stump11289f42009-09-09 15:08:12 +00001915
Hal Finkeld2208b52014-10-02 20:53:50 +00001916 if (WarnAboutSemanticsChange) {
1917 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1918 << TheCall->getCallee()->getSourceRange();
1919 }
1920
Chris Lattner5b9241b2009-05-08 15:36:58 +00001921 // Get the decl for the concrete builtin from this, we can tell what the
1922 // concrete integer type we should convert to is.
1923 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1924 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001925 FunctionDecl *NewBuiltinDecl;
1926 if (NewBuiltinID == BuiltinID)
1927 NewBuiltinDecl = FDecl;
1928 else {
1929 // Perform builtin lookup to avoid redeclaring it.
1930 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1931 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1932 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1933 assert(Res.getFoundDecl());
1934 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001935 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001936 return ExprError();
1937 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001938
John McCallcf142162010-08-07 06:22:56 +00001939 // The first argument --- the pointer --- has a fixed type; we
1940 // deduce the types of the rest of the arguments accordingly. Walk
1941 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001942 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001943 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001944
Chris Lattnerdc046542009-05-08 06:58:22 +00001945 // GCC does an implicit conversion to the pointer or integer ValType. This
1946 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001947 // Initialize the argument.
1948 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1949 ValType, /*consume*/ false);
1950 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001951 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001952 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001953
Chris Lattnerdc046542009-05-08 06:58:22 +00001954 // Okay, we have something that *can* be converted to the right type. Check
1955 // to see if there is a potentially weird extension going on here. This can
1956 // happen when you do an atomic operation on something like an char* and
1957 // pass in 42. The 42 gets converted to char. This is even more strange
1958 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001959 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001960 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001961 }
Mike Stump11289f42009-09-09 15:08:12 +00001962
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001963 ASTContext& Context = this->getASTContext();
1964
1965 // Create a new DeclRefExpr to refer to the new decl.
1966 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1967 Context,
1968 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001969 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001970 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001971 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001972 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001973 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001974 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001975
Chris Lattnerdc046542009-05-08 06:58:22 +00001976 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001977 // FIXME: This loses syntactic information.
1978 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1979 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1980 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001981 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001982
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001983 // Change the result type of the call to match the original value type. This
1984 // is arbitrary, but the codegen for these builtins ins design to handle it
1985 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001986 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001987
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001988 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001989}
1990
Chris Lattner6436fb62009-02-18 06:01:06 +00001991/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001992/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001993/// Note: It might also make sense to do the UTF-16 conversion here (would
1994/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001995bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001996 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001997 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1998
Douglas Gregorfb65e592011-07-27 05:40:30 +00001999 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002000 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2001 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002002 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002003 }
Mike Stump11289f42009-09-09 15:08:12 +00002004
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002005 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002006 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002007 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002008 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002009 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002010 UTF16 *ToPtr = &ToBuf[0];
2011
2012 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2013 &ToPtr, ToPtr + NumBytes,
2014 strictConversion);
2015 // Check for conversion failure.
2016 if (Result != conversionOK)
2017 Diag(Arg->getLocStart(),
2018 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2019 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002020 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002021}
2022
Chris Lattnere202e6a2007-12-20 00:05:45 +00002023/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2024/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00002025bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2026 Expr *Fn = TheCall->getCallee();
2027 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002028 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002029 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002030 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2031 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002032 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002033 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002034 return true;
2035 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002036
2037 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002038 return Diag(TheCall->getLocEnd(),
2039 diag::err_typecheck_call_too_few_args_at_least)
2040 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002041 }
2042
John McCall29ad95b2011-08-27 01:09:30 +00002043 // Type-check the first argument normally.
2044 if (checkBuiltinArgument(*this, TheCall, 0))
2045 return true;
2046
Chris Lattnere202e6a2007-12-20 00:05:45 +00002047 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002048 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002049 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002050 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002051 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002052 else if (FunctionDecl *FD = getCurFunctionDecl())
2053 isVariadic = FD->isVariadic();
2054 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002055 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002056
Chris Lattnere202e6a2007-12-20 00:05:45 +00002057 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002058 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2059 return true;
2060 }
Mike Stump11289f42009-09-09 15:08:12 +00002061
Chris Lattner43be2e62007-12-19 23:59:04 +00002062 // Verify that the second argument to the builtin is the last argument of the
2063 // current function or method.
2064 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002065 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002066
Nico Weber9eea7642013-05-24 23:31:57 +00002067 // These are valid if SecondArgIsLastNamedArgument is false after the next
2068 // block.
2069 QualType Type;
2070 SourceLocation ParamLoc;
2071
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002072 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2073 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002074 // FIXME: This isn't correct for methods (results in bogus warning).
2075 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002076 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002077 if (CurBlock)
2078 LastArg = *(CurBlock->TheDecl->param_end()-1);
2079 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002080 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002081 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002082 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002083 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002084
2085 Type = PV->getType();
2086 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002087 }
2088 }
Mike Stump11289f42009-09-09 15:08:12 +00002089
Chris Lattner43be2e62007-12-19 23:59:04 +00002090 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002091 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002092 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002093 else if (Type->isReferenceType()) {
2094 Diag(Arg->getLocStart(),
2095 diag::warn_va_start_of_reference_type_is_undefined);
2096 Diag(ParamLoc, diag::note_parameter_type) << Type;
2097 }
2098
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002099 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002100 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002101}
Chris Lattner43be2e62007-12-19 23:59:04 +00002102
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002103bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2104 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2105 // const char *named_addr);
2106
2107 Expr *Func = Call->getCallee();
2108
2109 if (Call->getNumArgs() < 3)
2110 return Diag(Call->getLocEnd(),
2111 diag::err_typecheck_call_too_few_args_at_least)
2112 << 0 /*function call*/ << 3 << Call->getNumArgs();
2113
2114 // Determine whether the current function is variadic or not.
2115 bool IsVariadic;
2116 if (BlockScopeInfo *CurBlock = getCurBlock())
2117 IsVariadic = CurBlock->TheDecl->isVariadic();
2118 else if (FunctionDecl *FD = getCurFunctionDecl())
2119 IsVariadic = FD->isVariadic();
2120 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2121 IsVariadic = MD->isVariadic();
2122 else
2123 llvm_unreachable("unexpected statement type");
2124
2125 if (!IsVariadic) {
2126 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2127 return true;
2128 }
2129
2130 // Type-check the first argument normally.
2131 if (checkBuiltinArgument(*this, Call, 0))
2132 return true;
2133
2134 static const struct {
2135 unsigned ArgNo;
2136 QualType Type;
2137 } ArgumentTypes[] = {
2138 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2139 { 2, Context.getSizeType() },
2140 };
2141
2142 for (const auto &AT : ArgumentTypes) {
2143 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2144 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2145 continue;
2146 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2147 << Arg->getType() << AT.Type << 1 /* different class */
2148 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2149 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2150 }
2151
2152 return false;
2153}
2154
Chris Lattner2da14fb2007-12-20 00:26:33 +00002155/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2156/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002157bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2158 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002159 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002160 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002161 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002162 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002163 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002164 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002165 << SourceRange(TheCall->getArg(2)->getLocStart(),
2166 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002167
John Wiegley01296292011-04-08 18:41:53 +00002168 ExprResult OrigArg0 = TheCall->getArg(0);
2169 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002170
Chris Lattner2da14fb2007-12-20 00:26:33 +00002171 // Do standard promotions between the two arguments, returning their common
2172 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002173 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002174 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2175 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002176
2177 // Make sure any conversions are pushed back into the call; this is
2178 // type safe since unordered compare builtins are declared as "_Bool
2179 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002180 TheCall->setArg(0, OrigArg0.get());
2181 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002182
John Wiegley01296292011-04-08 18:41:53 +00002183 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002184 return false;
2185
Chris Lattner2da14fb2007-12-20 00:26:33 +00002186 // If the common type isn't a real floating type, then the arguments were
2187 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002188 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002189 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002190 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002191 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2192 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002193
Chris Lattner2da14fb2007-12-20 00:26:33 +00002194 return false;
2195}
2196
Benjamin Kramer634fc102010-02-15 22:42:31 +00002197/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2198/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002199/// to check everything. We expect the last argument to be a floating point
2200/// value.
2201bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2202 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002203 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002204 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002205 if (TheCall->getNumArgs() > NumArgs)
2206 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002207 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002208 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002209 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002210 (*(TheCall->arg_end()-1))->getLocEnd());
2211
Benjamin Kramer64aae502010-02-16 10:07:31 +00002212 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002213
Eli Friedman7e4faac2009-08-31 20:06:00 +00002214 if (OrigArg->isTypeDependent())
2215 return false;
2216
Chris Lattner68784ef2010-05-06 05:50:07 +00002217 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002218 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002219 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002220 diag::err_typecheck_call_invalid_unary_fp)
2221 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002222
Chris Lattner68784ef2010-05-06 05:50:07 +00002223 // If this is an implicit conversion from float -> double, remove it.
2224 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2225 Expr *CastArg = Cast->getSubExpr();
2226 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2227 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2228 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002229 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002230 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002231 }
2232 }
2233
Eli Friedman7e4faac2009-08-31 20:06:00 +00002234 return false;
2235}
2236
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002237/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2238// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002239ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002240 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002241 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002242 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002243 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2244 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002245
Nate Begemana0110022010-06-08 00:16:34 +00002246 // Determine which of the following types of shufflevector we're checking:
2247 // 1) unary, vector mask: (lhs, mask)
2248 // 2) binary, vector mask: (lhs, rhs, mask)
2249 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2250 QualType resType = TheCall->getArg(0)->getType();
2251 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002252
Douglas Gregorc25f7662009-05-19 22:10:17 +00002253 if (!TheCall->getArg(0)->isTypeDependent() &&
2254 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002255 QualType LHSType = TheCall->getArg(0)->getType();
2256 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002257
Craig Topperbaca3892013-07-29 06:47:04 +00002258 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2259 return ExprError(Diag(TheCall->getLocStart(),
2260 diag::err_shufflevector_non_vector)
2261 << SourceRange(TheCall->getArg(0)->getLocStart(),
2262 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002263
Nate Begemana0110022010-06-08 00:16:34 +00002264 numElements = LHSType->getAs<VectorType>()->getNumElements();
2265 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002266
Nate Begemana0110022010-06-08 00:16:34 +00002267 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2268 // with mask. If so, verify that RHS is an integer vector type with the
2269 // same number of elts as lhs.
2270 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002271 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002272 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002273 return ExprError(Diag(TheCall->getLocStart(),
2274 diag::err_shufflevector_incompatible_vector)
2275 << SourceRange(TheCall->getArg(1)->getLocStart(),
2276 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002277 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002278 return ExprError(Diag(TheCall->getLocStart(),
2279 diag::err_shufflevector_incompatible_vector)
2280 << SourceRange(TheCall->getArg(0)->getLocStart(),
2281 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002282 } else if (numElements != numResElements) {
2283 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002284 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002285 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002286 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002287 }
2288
2289 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002290 if (TheCall->getArg(i)->isTypeDependent() ||
2291 TheCall->getArg(i)->isValueDependent())
2292 continue;
2293
Nate Begemana0110022010-06-08 00:16:34 +00002294 llvm::APSInt Result(32);
2295 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2296 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002297 diag::err_shufflevector_nonconstant_argument)
2298 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002299
Craig Topper50ad5b72013-08-03 17:40:38 +00002300 // Allow -1 which will be translated to undef in the IR.
2301 if (Result.isSigned() && Result.isAllOnesValue())
2302 continue;
2303
Chris Lattner7ab824e2008-08-10 02:05:13 +00002304 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002305 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002306 diag::err_shufflevector_argument_too_large)
2307 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002308 }
2309
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002310 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002311
Chris Lattner7ab824e2008-08-10 02:05:13 +00002312 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002313 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002314 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002315 }
2316
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002317 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2318 TheCall->getCallee()->getLocStart(),
2319 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002320}
Chris Lattner43be2e62007-12-19 23:59:04 +00002321
Hal Finkelc4d7c822013-09-18 03:29:45 +00002322/// SemaConvertVectorExpr - Handle __builtin_convertvector
2323ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2324 SourceLocation BuiltinLoc,
2325 SourceLocation RParenLoc) {
2326 ExprValueKind VK = VK_RValue;
2327 ExprObjectKind OK = OK_Ordinary;
2328 QualType DstTy = TInfo->getType();
2329 QualType SrcTy = E->getType();
2330
2331 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2332 return ExprError(Diag(BuiltinLoc,
2333 diag::err_convertvector_non_vector)
2334 << E->getSourceRange());
2335 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2336 return ExprError(Diag(BuiltinLoc,
2337 diag::err_convertvector_non_vector_type));
2338
2339 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2340 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2341 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2342 if (SrcElts != DstElts)
2343 return ExprError(Diag(BuiltinLoc,
2344 diag::err_convertvector_incompatible_vector)
2345 << E->getSourceRange());
2346 }
2347
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002348 return new (Context)
2349 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002350}
2351
Daniel Dunbarb7257262008-07-21 22:59:13 +00002352/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2353// This is declared to take (const void*, ...) and can take two
2354// optional constant int args.
2355bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002356 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002357
Chris Lattner3b054132008-11-19 05:08:23 +00002358 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002359 return Diag(TheCall->getLocEnd(),
2360 diag::err_typecheck_call_too_many_args_at_most)
2361 << 0 /*function call*/ << 3 << NumArgs
2362 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002363
2364 // Argument 0 is checked for us and the remaining arguments must be
2365 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002366 for (unsigned i = 1; i != NumArgs; ++i)
2367 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002368 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002369
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002370 return false;
2371}
2372
Hal Finkelf0417332014-07-17 14:25:55 +00002373/// SemaBuiltinAssume - Handle __assume (MS Extension).
2374// __assume does not evaluate its arguments, and should warn if its argument
2375// has side effects.
2376bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2377 Expr *Arg = TheCall->getArg(0);
2378 if (Arg->isInstantiationDependent()) return false;
2379
2380 if (Arg->HasSideEffects(Context))
2381 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002382 << Arg->getSourceRange()
2383 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2384
2385 return false;
2386}
2387
2388/// Handle __builtin_assume_aligned. This is declared
2389/// as (const void*, size_t, ...) and can take one optional constant int arg.
2390bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2391 unsigned NumArgs = TheCall->getNumArgs();
2392
2393 if (NumArgs > 3)
2394 return Diag(TheCall->getLocEnd(),
2395 diag::err_typecheck_call_too_many_args_at_most)
2396 << 0 /*function call*/ << 3 << NumArgs
2397 << TheCall->getSourceRange();
2398
2399 // The alignment must be a constant integer.
2400 Expr *Arg = TheCall->getArg(1);
2401
2402 // We can't check the value of a dependent argument.
2403 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2404 llvm::APSInt Result;
2405 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2406 return true;
2407
2408 if (!Result.isPowerOf2())
2409 return Diag(TheCall->getLocStart(),
2410 diag::err_alignment_not_power_of_two)
2411 << Arg->getSourceRange();
2412 }
2413
2414 if (NumArgs > 2) {
2415 ExprResult Arg(TheCall->getArg(2));
2416 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2417 Context.getSizeType(), false);
2418 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2419 if (Arg.isInvalid()) return true;
2420 TheCall->setArg(2, Arg.get());
2421 }
Hal Finkelf0417332014-07-17 14:25:55 +00002422
2423 return false;
2424}
2425
Eric Christopher8d0c6212010-04-17 02:26:23 +00002426/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2427/// TheCall is a constant expression.
2428bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2429 llvm::APSInt &Result) {
2430 Expr *Arg = TheCall->getArg(ArgNum);
2431 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2432 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2433
2434 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2435
2436 if (!Arg->isIntegerConstantExpr(Result, Context))
2437 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002438 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002439
Chris Lattnerd545ad12009-09-23 06:06:36 +00002440 return false;
2441}
2442
Richard Sandiford28940af2014-04-16 08:47:51 +00002443/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2444/// TheCall is a constant expression in the range [Low, High].
2445bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2446 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002447 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002448
2449 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002450 Expr *Arg = TheCall->getArg(ArgNum);
2451 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002452 return false;
2453
Eric Christopher8d0c6212010-04-17 02:26:23 +00002454 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002455 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002456 return true;
2457
Richard Sandiford28940af2014-04-16 08:47:51 +00002458 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002459 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002460 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002461
2462 return false;
2463}
2464
Eli Friedmanc97d0142009-05-03 06:04:26 +00002465/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002466/// This checks that val is a constant 1.
2467bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2468 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002469 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002470
Eric Christopher8d0c6212010-04-17 02:26:23 +00002471 // TODO: This is less than ideal. Overload this to take a value.
2472 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2473 return true;
2474
2475 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002476 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2477 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2478
2479 return false;
2480}
2481
Richard Smithd7293d72013-08-05 18:49:43 +00002482namespace {
2483enum StringLiteralCheckType {
2484 SLCT_NotALiteral,
2485 SLCT_UncheckedLiteral,
2486 SLCT_CheckedLiteral
2487};
2488}
2489
Richard Smith55ce3522012-06-25 20:30:08 +00002490// Determine if an expression is a string literal or constant string.
2491// If this function returns false on the arguments to a function expecting a
2492// format string, we will usually need to emit a warning.
2493// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002494static StringLiteralCheckType
2495checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2496 bool HasVAListArg, unsigned format_idx,
2497 unsigned firstDataArg, Sema::FormatStringType Type,
2498 Sema::VariadicCallType CallType, bool InFunctionCall,
2499 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002500 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002501 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002502 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002503
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002504 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002505
Richard Smithd7293d72013-08-05 18:49:43 +00002506 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002507 // Technically -Wformat-nonliteral does not warn about this case.
2508 // The behavior of printf and friends in this case is implementation
2509 // dependent. Ideally if the format string cannot be null then
2510 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002511 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002512
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002513 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002514 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002515 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002516 // The expression is a literal if both sub-expressions were, and it was
2517 // completely checked only if both sub-expressions were checked.
2518 const AbstractConditionalOperator *C =
2519 cast<AbstractConditionalOperator>(E);
2520 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002521 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002522 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002523 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002524 if (Left == SLCT_NotALiteral)
2525 return SLCT_NotALiteral;
2526 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002527 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002528 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002529 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002530 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002531 }
2532
2533 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002534 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2535 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002536 }
2537
John McCallc07a0c72011-02-17 10:25:35 +00002538 case Stmt::OpaqueValueExprClass:
2539 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2540 E = src;
2541 goto tryAgain;
2542 }
Richard Smith55ce3522012-06-25 20:30:08 +00002543 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002544
Ted Kremeneka8890832011-02-24 23:03:04 +00002545 case Stmt::PredefinedExprClass:
2546 // While __func__, etc., are technically not string literals, they
2547 // cannot contain format specifiers and thus are not a security
2548 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002549 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002550
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002551 case Stmt::DeclRefExprClass: {
2552 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002553
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002554 // As an exception, do not flag errors for variables binding to
2555 // const string literals.
2556 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2557 bool isConstant = false;
2558 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002559
Richard Smithd7293d72013-08-05 18:49:43 +00002560 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2561 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002562 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002563 isConstant = T.isConstant(S.Context) &&
2564 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002565 } else if (T->isObjCObjectPointerType()) {
2566 // In ObjC, there is usually no "const ObjectPointer" type,
2567 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002568 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002569 }
Mike Stump11289f42009-09-09 15:08:12 +00002570
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002571 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002572 if (const Expr *Init = VD->getAnyInitializer()) {
2573 // Look through initializers like const char c[] = { "foo" }
2574 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2575 if (InitList->isStringLiteralInit())
2576 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2577 }
Richard Smithd7293d72013-08-05 18:49:43 +00002578 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002579 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002580 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002581 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002582 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002583 }
Mike Stump11289f42009-09-09 15:08:12 +00002584
Anders Carlssonb012ca92009-06-28 19:55:58 +00002585 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2586 // special check to see if the format string is a function parameter
2587 // of the function calling the printf function. If the function
2588 // has an attribute indicating it is a printf-like function, then we
2589 // should suppress warnings concerning non-literals being used in a call
2590 // to a vprintf function. For example:
2591 //
2592 // void
2593 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2594 // va_list ap;
2595 // va_start(ap, fmt);
2596 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2597 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002598 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002599 if (HasVAListArg) {
2600 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2601 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2602 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002603 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002604 // adjust for implicit parameter
2605 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2606 if (MD->isInstance())
2607 ++PVIndex;
2608 // We also check if the formats are compatible.
2609 // We can't pass a 'scanf' string to a 'printf' function.
2610 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002611 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002612 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002613 }
2614 }
2615 }
2616 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002617 }
Mike Stump11289f42009-09-09 15:08:12 +00002618
Richard Smith55ce3522012-06-25 20:30:08 +00002619 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002620 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002621
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002622 case Stmt::CallExprClass:
2623 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002624 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002625 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2626 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2627 unsigned ArgIndex = FA->getFormatIdx();
2628 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2629 if (MD->isInstance())
2630 --ArgIndex;
2631 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002632
Richard Smithd7293d72013-08-05 18:49:43 +00002633 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002634 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002635 Type, CallType, InFunctionCall,
2636 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002637 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2638 unsigned BuiltinID = FD->getBuiltinID();
2639 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2640 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2641 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002642 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002643 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002644 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002645 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002646 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002647 }
2648 }
Mike Stump11289f42009-09-09 15:08:12 +00002649
Richard Smith55ce3522012-06-25 20:30:08 +00002650 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002651 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002652 case Stmt::ObjCStringLiteralClass:
2653 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002654 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002655
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002656 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002657 StrE = ObjCFExpr->getString();
2658 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002659 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002660
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002661 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002662 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2663 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002664 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002665 }
Mike Stump11289f42009-09-09 15:08:12 +00002666
Richard Smith55ce3522012-06-25 20:30:08 +00002667 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002668 }
Mike Stump11289f42009-09-09 15:08:12 +00002669
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002670 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002671 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002672 }
2673}
2674
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002675Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002676 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002677 .Case("scanf", FST_Scanf)
2678 .Cases("printf", "printf0", FST_Printf)
2679 .Cases("NSString", "CFString", FST_NSString)
2680 .Case("strftime", FST_Strftime)
2681 .Case("strfmon", FST_Strfmon)
2682 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00002683 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00002684 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002685 .Default(FST_Unknown);
2686}
2687
Jordan Rose3e0ec582012-07-19 18:10:23 +00002688/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002689/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002690/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002691bool Sema::CheckFormatArguments(const FormatAttr *Format,
2692 ArrayRef<const Expr *> Args,
2693 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002694 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002695 SourceLocation Loc, SourceRange Range,
2696 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002697 FormatStringInfo FSI;
2698 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002699 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002700 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002701 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002702 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002703}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002704
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002705bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002706 bool HasVAListArg, unsigned format_idx,
2707 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002708 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002709 SourceLocation Loc, SourceRange Range,
2710 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002711 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002712 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002713 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002714 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002715 }
Mike Stump11289f42009-09-09 15:08:12 +00002716
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002717 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002718
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002719 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002720 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002721 // Dynamically generated format strings are difficult to
2722 // automatically vet at compile time. Requiring that format strings
2723 // are string literals: (1) permits the checking of format strings by
2724 // the compiler and thereby (2) can practically remove the source of
2725 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002726
Mike Stump11289f42009-09-09 15:08:12 +00002727 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002728 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002729 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002730 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002731 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002732 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2733 format_idx, firstDataArg, Type, CallType,
2734 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002735 if (CT != SLCT_NotALiteral)
2736 // Literal format string found, check done!
2737 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002738
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002739 // Strftime is particular as it always uses a single 'time' argument,
2740 // so it is safe to pass a non-literal string.
2741 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002742 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002743
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002744 // Do not emit diag when the string param is a macro expansion and the
2745 // format is either NSString or CFString. This is a hack to prevent
2746 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2747 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002748 if (Type == FST_NSString &&
2749 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002750 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002751
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002752 // If there are no arguments specified, warn with -Wformat-security, otherwise
2753 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002754 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002755 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002756 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002757 << OrigFormatExpr->getSourceRange();
2758 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002759 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002760 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002761 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002762 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002763}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002764
Ted Kremenekab278de2010-01-28 23:39:18 +00002765namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002766class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2767protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002768 Sema &S;
2769 const StringLiteral *FExpr;
2770 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002771 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002772 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002773 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002774 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002775 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002776 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002777 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002778 bool usesPositionalArgs;
2779 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002780 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002781 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002782 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002783public:
Ted Kremenek02087932010-07-16 02:11:22 +00002784 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002785 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002786 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002787 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002788 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002789 Sema::VariadicCallType callType,
2790 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002791 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002792 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2793 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002794 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002795 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002796 inFunctionCall(inFunctionCall), CallType(callType),
2797 CheckedVarArgs(CheckedVarArgs) {
2798 CoveredArgs.resize(numDataArgs);
2799 CoveredArgs.reset();
2800 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002801
Ted Kremenek019d2242010-01-29 01:50:07 +00002802 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002803
Ted Kremenek02087932010-07-16 02:11:22 +00002804 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002805 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002806
Jordan Rose92303592012-09-08 04:00:03 +00002807 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002808 const analyze_format_string::FormatSpecifier &FS,
2809 const analyze_format_string::ConversionSpecifier &CS,
2810 const char *startSpecifier, unsigned specifierLen,
2811 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002812
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002813 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002814 const analyze_format_string::FormatSpecifier &FS,
2815 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002816
2817 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002818 const analyze_format_string::ConversionSpecifier &CS,
2819 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002820
Craig Toppere14c0f82014-03-12 04:55:44 +00002821 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002822
Craig Toppere14c0f82014-03-12 04:55:44 +00002823 void HandleInvalidPosition(const char *startSpecifier,
2824 unsigned specifierLen,
2825 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002826
Craig Toppere14c0f82014-03-12 04:55:44 +00002827 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002828
Craig Toppere14c0f82014-03-12 04:55:44 +00002829 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002830
Richard Trieu03cf7b72011-10-28 00:41:25 +00002831 template <typename Range>
2832 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2833 const Expr *ArgumentExpr,
2834 PartialDiagnostic PDiag,
2835 SourceLocation StringLoc,
2836 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002837 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002838
Ted Kremenek02087932010-07-16 02:11:22 +00002839protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002840 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2841 const char *startSpec,
2842 unsigned specifierLen,
2843 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002844
2845 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2846 const char *startSpec,
2847 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002848
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002849 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002850 CharSourceRange getSpecifierRange(const char *startSpecifier,
2851 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002852 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002853
Ted Kremenek5739de72010-01-29 01:06:55 +00002854 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002855
2856 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2857 const analyze_format_string::ConversionSpecifier &CS,
2858 const char *startSpecifier, unsigned specifierLen,
2859 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002860
2861 template <typename Range>
2862 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2863 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002864 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002865};
2866}
2867
Ted Kremenek02087932010-07-16 02:11:22 +00002868SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002869 return OrigFormatExpr->getSourceRange();
2870}
2871
Ted Kremenek02087932010-07-16 02:11:22 +00002872CharSourceRange CheckFormatHandler::
2873getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002874 SourceLocation Start = getLocationOfByte(startSpecifier);
2875 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2876
2877 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002878 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002879
2880 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002881}
2882
Ted Kremenek02087932010-07-16 02:11:22 +00002883SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002884 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002885}
2886
Ted Kremenek02087932010-07-16 02:11:22 +00002887void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2888 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002889 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2890 getLocationOfByte(startSpecifier),
2891 /*IsStringLocation*/true,
2892 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002893}
2894
Jordan Rose92303592012-09-08 04:00:03 +00002895void CheckFormatHandler::HandleInvalidLengthModifier(
2896 const analyze_format_string::FormatSpecifier &FS,
2897 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002898 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002899 using namespace analyze_format_string;
2900
2901 const LengthModifier &LM = FS.getLengthModifier();
2902 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2903
2904 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002905 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002906 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002907 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002908 getLocationOfByte(LM.getStart()),
2909 /*IsStringLocation*/true,
2910 getSpecifierRange(startSpecifier, specifierLen));
2911
2912 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2913 << FixedLM->toString()
2914 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2915
2916 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002917 FixItHint Hint;
2918 if (DiagID == diag::warn_format_nonsensical_length)
2919 Hint = FixItHint::CreateRemoval(LMRange);
2920
2921 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002922 getLocationOfByte(LM.getStart()),
2923 /*IsStringLocation*/true,
2924 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002925 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002926 }
2927}
2928
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002929void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002930 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002931 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002932 using namespace analyze_format_string;
2933
2934 const LengthModifier &LM = FS.getLengthModifier();
2935 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2936
2937 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002938 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002939 if (FixedLM) {
2940 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2941 << LM.toString() << 0,
2942 getLocationOfByte(LM.getStart()),
2943 /*IsStringLocation*/true,
2944 getSpecifierRange(startSpecifier, specifierLen));
2945
2946 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2947 << FixedLM->toString()
2948 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2949
2950 } else {
2951 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2952 << LM.toString() << 0,
2953 getLocationOfByte(LM.getStart()),
2954 /*IsStringLocation*/true,
2955 getSpecifierRange(startSpecifier, specifierLen));
2956 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002957}
2958
2959void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2960 const analyze_format_string::ConversionSpecifier &CS,
2961 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002962 using namespace analyze_format_string;
2963
2964 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002965 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002966 if (FixedCS) {
2967 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2968 << CS.toString() << /*conversion specifier*/1,
2969 getLocationOfByte(CS.getStart()),
2970 /*IsStringLocation*/true,
2971 getSpecifierRange(startSpecifier, specifierLen));
2972
2973 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2974 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2975 << FixedCS->toString()
2976 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2977 } else {
2978 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2979 << CS.toString() << /*conversion specifier*/1,
2980 getLocationOfByte(CS.getStart()),
2981 /*IsStringLocation*/true,
2982 getSpecifierRange(startSpecifier, specifierLen));
2983 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002984}
2985
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002986void CheckFormatHandler::HandlePosition(const char *startPos,
2987 unsigned posLen) {
2988 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2989 getLocationOfByte(startPos),
2990 /*IsStringLocation*/true,
2991 getSpecifierRange(startPos, posLen));
2992}
2993
Ted Kremenekd1668192010-02-27 01:41:03 +00002994void
Ted Kremenek02087932010-07-16 02:11:22 +00002995CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2996 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002997 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2998 << (unsigned) p,
2999 getLocationOfByte(startPos), /*IsStringLocation*/true,
3000 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003001}
3002
Ted Kremenek02087932010-07-16 02:11:22 +00003003void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003004 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003005 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3006 getLocationOfByte(startPos),
3007 /*IsStringLocation*/true,
3008 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003009}
3010
Ted Kremenek02087932010-07-16 02:11:22 +00003011void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003012 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003013 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003014 EmitFormatDiagnostic(
3015 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3016 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3017 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003018 }
Ted Kremenek02087932010-07-16 02:11:22 +00003019}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003020
Jordan Rose58bbe422012-07-19 18:10:08 +00003021// Note that this may return NULL if there was an error parsing or building
3022// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003023const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003024 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003025}
3026
3027void CheckFormatHandler::DoneProcessing() {
3028 // Does the number of data arguments exceed the number of
3029 // format conversions in the format string?
3030 if (!HasVAListArg) {
3031 // Find any arguments that weren't covered.
3032 CoveredArgs.flip();
3033 signed notCoveredArg = CoveredArgs.find_first();
3034 if (notCoveredArg >= 0) {
3035 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003036 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3037 SourceLocation Loc = E->getLocStart();
3038 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3039 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3040 Loc, /*IsStringLocation*/false,
3041 getFormatStringRange());
3042 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003043 }
Ted Kremenek02087932010-07-16 02:11:22 +00003044 }
3045 }
3046}
3047
Ted Kremenekce815422010-07-19 21:25:57 +00003048bool
3049CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3050 SourceLocation Loc,
3051 const char *startSpec,
3052 unsigned specifierLen,
3053 const char *csStart,
3054 unsigned csLen) {
3055
3056 bool keepGoing = true;
3057 if (argIndex < NumDataArgs) {
3058 // Consider the argument coverered, even though the specifier doesn't
3059 // make sense.
3060 CoveredArgs.set(argIndex);
3061 }
3062 else {
3063 // If argIndex exceeds the number of data arguments we
3064 // don't issue a warning because that is just a cascade of warnings (and
3065 // they may have intended '%%' anyway). We don't want to continue processing
3066 // the format string after this point, however, as we will like just get
3067 // gibberish when trying to match arguments.
3068 keepGoing = false;
3069 }
3070
Richard Trieu03cf7b72011-10-28 00:41:25 +00003071 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3072 << StringRef(csStart, csLen),
3073 Loc, /*IsStringLocation*/true,
3074 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003075
3076 return keepGoing;
3077}
3078
Richard Trieu03cf7b72011-10-28 00:41:25 +00003079void
3080CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3081 const char *startSpec,
3082 unsigned specifierLen) {
3083 EmitFormatDiagnostic(
3084 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3085 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3086}
3087
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003088bool
3089CheckFormatHandler::CheckNumArgs(
3090 const analyze_format_string::FormatSpecifier &FS,
3091 const analyze_format_string::ConversionSpecifier &CS,
3092 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3093
3094 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003095 PartialDiagnostic PDiag = FS.usesPositionalArg()
3096 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3097 << (argIndex+1) << NumDataArgs)
3098 : S.PDiag(diag::warn_printf_insufficient_data_args);
3099 EmitFormatDiagnostic(
3100 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3101 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003102 return false;
3103 }
3104 return true;
3105}
3106
Richard Trieu03cf7b72011-10-28 00:41:25 +00003107template<typename Range>
3108void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3109 SourceLocation Loc,
3110 bool IsStringLocation,
3111 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003112 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003113 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003114 Loc, IsStringLocation, StringRange, FixIt);
3115}
3116
3117/// \brief If the format string is not within the funcion call, emit a note
3118/// so that the function call and string are in diagnostic messages.
3119///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003120/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003121/// call and only one diagnostic message will be produced. Otherwise, an
3122/// extra note will be emitted pointing to location of the format string.
3123///
3124/// \param ArgumentExpr the expression that is passed as the format string
3125/// argument in the function call. Used for getting locations when two
3126/// diagnostics are emitted.
3127///
3128/// \param PDiag the callee should already have provided any strings for the
3129/// diagnostic message. This function only adds locations and fixits
3130/// to diagnostics.
3131///
3132/// \param Loc primary location for diagnostic. If two diagnostics are
3133/// required, one will be at Loc and a new SourceLocation will be created for
3134/// the other one.
3135///
3136/// \param IsStringLocation if true, Loc points to the format string should be
3137/// used for the note. Otherwise, Loc points to the argument list and will
3138/// be used with PDiag.
3139///
3140/// \param StringRange some or all of the string to highlight. This is
3141/// templated so it can accept either a CharSourceRange or a SourceRange.
3142///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003143/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003144template<typename Range>
3145void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3146 const Expr *ArgumentExpr,
3147 PartialDiagnostic PDiag,
3148 SourceLocation Loc,
3149 bool IsStringLocation,
3150 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003151 ArrayRef<FixItHint> FixIt) {
3152 if (InFunctionCall) {
3153 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3154 D << StringRange;
3155 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3156 I != E; ++I) {
3157 D << *I;
3158 }
3159 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003160 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3161 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003162
3163 const Sema::SemaDiagnosticBuilder &Note =
3164 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3165 diag::note_format_string_defined);
3166
3167 Note << StringRange;
3168 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3169 I != E; ++I) {
3170 Note << *I;
3171 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00003172 }
3173}
3174
Ted Kremenek02087932010-07-16 02:11:22 +00003175//===--- CHECK: Printf format string checking ------------------------------===//
3176
3177namespace {
3178class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003179 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003180public:
3181 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3182 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003183 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003184 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003185 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003186 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003187 Sema::VariadicCallType CallType,
3188 llvm::SmallBitVector &CheckedVarArgs)
3189 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3190 numDataArgs, beg, hasVAListArg, Args,
3191 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3192 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003193 {}
3194
Craig Toppere14c0f82014-03-12 04:55:44 +00003195
Ted Kremenek02087932010-07-16 02:11:22 +00003196 bool HandleInvalidPrintfConversionSpecifier(
3197 const analyze_printf::PrintfSpecifier &FS,
3198 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003199 unsigned specifierLen) override;
3200
Ted Kremenek02087932010-07-16 02:11:22 +00003201 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3202 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003203 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003204 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3205 const char *StartSpecifier,
3206 unsigned SpecifierLen,
3207 const Expr *E);
3208
Ted Kremenek02087932010-07-16 02:11:22 +00003209 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3210 const char *startSpecifier, unsigned specifierLen);
3211 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3212 const analyze_printf::OptionalAmount &Amt,
3213 unsigned type,
3214 const char *startSpecifier, unsigned specifierLen);
3215 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3216 const analyze_printf::OptionalFlag &flag,
3217 const char *startSpecifier, unsigned specifierLen);
3218 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3219 const analyze_printf::OptionalFlag &ignoredFlag,
3220 const analyze_printf::OptionalFlag &flag,
3221 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003222 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003223 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003224
Ted Kremenek02087932010-07-16 02:11:22 +00003225};
3226}
3227
3228bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3229 const analyze_printf::PrintfSpecifier &FS,
3230 const char *startSpecifier,
3231 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003232 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003233 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003234
Ted Kremenekce815422010-07-19 21:25:57 +00003235 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3236 getLocationOfByte(CS.getStart()),
3237 startSpecifier, specifierLen,
3238 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003239}
3240
Ted Kremenek02087932010-07-16 02:11:22 +00003241bool CheckPrintfHandler::HandleAmount(
3242 const analyze_format_string::OptionalAmount &Amt,
3243 unsigned k, const char *startSpecifier,
3244 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003245
3246 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003247 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003248 unsigned argIndex = Amt.getArgIndex();
3249 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003250 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3251 << k,
3252 getLocationOfByte(Amt.getStart()),
3253 /*IsStringLocation*/true,
3254 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003255 // Don't do any more checking. We will just emit
3256 // spurious errors.
3257 return false;
3258 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003259
Ted Kremenek5739de72010-01-29 01:06:55 +00003260 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003261 // Although not in conformance with C99, we also allow the argument to be
3262 // an 'unsigned int' as that is a reasonably safe case. GCC also
3263 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003264 CoveredArgs.set(argIndex);
3265 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003266 if (!Arg)
3267 return false;
3268
Ted Kremenek5739de72010-01-29 01:06:55 +00003269 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003270
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003271 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3272 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003273
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003274 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003275 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003276 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003277 << T << Arg->getSourceRange(),
3278 getLocationOfByte(Amt.getStart()),
3279 /*IsStringLocation*/true,
3280 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003281 // Don't do any more checking. We will just emit
3282 // spurious errors.
3283 return false;
3284 }
3285 }
3286 }
3287 return true;
3288}
Ted Kremenek5739de72010-01-29 01:06:55 +00003289
Tom Careb49ec692010-06-17 19:00:27 +00003290void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003291 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003292 const analyze_printf::OptionalAmount &Amt,
3293 unsigned type,
3294 const char *startSpecifier,
3295 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003296 const analyze_printf::PrintfConversionSpecifier &CS =
3297 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003298
Richard Trieu03cf7b72011-10-28 00:41:25 +00003299 FixItHint fixit =
3300 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3301 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3302 Amt.getConstantLength()))
3303 : FixItHint();
3304
3305 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3306 << type << CS.toString(),
3307 getLocationOfByte(Amt.getStart()),
3308 /*IsStringLocation*/true,
3309 getSpecifierRange(startSpecifier, specifierLen),
3310 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003311}
3312
Ted Kremenek02087932010-07-16 02:11:22 +00003313void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003314 const analyze_printf::OptionalFlag &flag,
3315 const char *startSpecifier,
3316 unsigned specifierLen) {
3317 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003318 const analyze_printf::PrintfConversionSpecifier &CS =
3319 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003320 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3321 << flag.toString() << CS.toString(),
3322 getLocationOfByte(flag.getPosition()),
3323 /*IsStringLocation*/true,
3324 getSpecifierRange(startSpecifier, specifierLen),
3325 FixItHint::CreateRemoval(
3326 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003327}
3328
3329void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003330 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003331 const analyze_printf::OptionalFlag &ignoredFlag,
3332 const analyze_printf::OptionalFlag &flag,
3333 const char *startSpecifier,
3334 unsigned specifierLen) {
3335 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003336 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3337 << ignoredFlag.toString() << flag.toString(),
3338 getLocationOfByte(ignoredFlag.getPosition()),
3339 /*IsStringLocation*/true,
3340 getSpecifierRange(startSpecifier, specifierLen),
3341 FixItHint::CreateRemoval(
3342 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003343}
3344
Richard Smith55ce3522012-06-25 20:30:08 +00003345// Determines if the specified is a C++ class or struct containing
3346// a member with the specified name and kind (e.g. a CXXMethodDecl named
3347// "c_str()").
3348template<typename MemberKind>
3349static llvm::SmallPtrSet<MemberKind*, 1>
3350CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3351 const RecordType *RT = Ty->getAs<RecordType>();
3352 llvm::SmallPtrSet<MemberKind*, 1> Results;
3353
3354 if (!RT)
3355 return Results;
3356 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003357 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003358 return Results;
3359
Alp Tokerb6cc5922014-05-03 03:45:55 +00003360 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003361 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003362 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003363
3364 // We just need to include all members of the right kind turned up by the
3365 // filter, at this point.
3366 if (S.LookupQualifiedName(R, RT->getDecl()))
3367 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3368 NamedDecl *decl = (*I)->getUnderlyingDecl();
3369 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3370 Results.insert(FK);
3371 }
3372 return Results;
3373}
3374
Richard Smith2868a732014-02-28 01:36:39 +00003375/// Check if we could call '.c_str()' on an object.
3376///
3377/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3378/// allow the call, or if it would be ambiguous).
3379bool Sema::hasCStrMethod(const Expr *E) {
3380 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3381 MethodSet Results =
3382 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3383 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3384 MI != ME; ++MI)
3385 if ((*MI)->getMinRequiredArguments() == 0)
3386 return true;
3387 return false;
3388}
3389
Richard Smith55ce3522012-06-25 20:30:08 +00003390// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003391// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003392// Returns true when a c_str() conversion method is found.
3393bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003394 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003395 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3396
3397 MethodSet Results =
3398 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3399
3400 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3401 MI != ME; ++MI) {
3402 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003403 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003404 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003405 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003406 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003407 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3408 << "c_str()"
3409 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3410 return true;
3411 }
3412 }
3413
3414 return false;
3415}
3416
Ted Kremenekab278de2010-01-28 23:39:18 +00003417bool
Ted Kremenek02087932010-07-16 02:11:22 +00003418CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003419 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003420 const char *startSpecifier,
3421 unsigned specifierLen) {
3422
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003423 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003424 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003425 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003426
Ted Kremenek6cd69422010-07-19 22:01:06 +00003427 if (FS.consumesDataArgument()) {
3428 if (atFirstArg) {
3429 atFirstArg = false;
3430 usesPositionalArgs = FS.usesPositionalArg();
3431 }
3432 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003433 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3434 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003435 return false;
3436 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003437 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003438
Ted Kremenekd1668192010-02-27 01:41:03 +00003439 // First check if the field width, precision, and conversion specifier
3440 // have matching data arguments.
3441 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3442 startSpecifier, specifierLen)) {
3443 return false;
3444 }
3445
3446 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3447 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003448 return false;
3449 }
3450
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003451 if (!CS.consumesDataArgument()) {
3452 // FIXME: Technically specifying a precision or field width here
3453 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003454 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003455 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003456
Ted Kremenek4a49d982010-02-26 19:18:41 +00003457 // Consume the argument.
3458 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003459 if (argIndex < NumDataArgs) {
3460 // The check to see if the argIndex is valid will come later.
3461 // We set the bit here because we may exit early from this
3462 // function if we encounter some other error.
3463 CoveredArgs.set(argIndex);
3464 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003465
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003466 // FreeBSD kernel extensions.
3467 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3468 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3469 // We need at least two arguments.
3470 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3471 return false;
3472
3473 // Claim the second argument.
3474 CoveredArgs.set(argIndex + 1);
3475
3476 // Type check the first argument (int for %b, pointer for %D)
3477 const Expr *Ex = getDataArg(argIndex);
3478 const analyze_printf::ArgType &AT =
3479 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3480 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3481 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3482 EmitFormatDiagnostic(
3483 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3484 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3485 << false << Ex->getSourceRange(),
3486 Ex->getLocStart(), /*IsStringLocation*/false,
3487 getSpecifierRange(startSpecifier, specifierLen));
3488
3489 // Type check the second argument (char * for both %b and %D)
3490 Ex = getDataArg(argIndex + 1);
3491 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3492 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3493 EmitFormatDiagnostic(
3494 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3495 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3496 << false << Ex->getSourceRange(),
3497 Ex->getLocStart(), /*IsStringLocation*/false,
3498 getSpecifierRange(startSpecifier, specifierLen));
3499
3500 return true;
3501 }
3502
Ted Kremenek4a49d982010-02-26 19:18:41 +00003503 // Check for using an Objective-C specific conversion specifier
3504 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003505 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003506 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3507 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003508 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003509
Tom Careb49ec692010-06-17 19:00:27 +00003510 // Check for invalid use of field width
3511 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003512 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003513 startSpecifier, specifierLen);
3514 }
3515
3516 // Check for invalid use of precision
3517 if (!FS.hasValidPrecision()) {
3518 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3519 startSpecifier, specifierLen);
3520 }
3521
3522 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003523 if (!FS.hasValidThousandsGroupingPrefix())
3524 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003525 if (!FS.hasValidLeadingZeros())
3526 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3527 if (!FS.hasValidPlusPrefix())
3528 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003529 if (!FS.hasValidSpacePrefix())
3530 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003531 if (!FS.hasValidAlternativeForm())
3532 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3533 if (!FS.hasValidLeftJustified())
3534 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3535
3536 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003537 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3538 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3539 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003540 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3541 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3542 startSpecifier, specifierLen);
3543
3544 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003545 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003546 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3547 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003548 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003549 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003550 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003551 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3552 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003553
Jordan Rose92303592012-09-08 04:00:03 +00003554 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3555 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3556
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003557 // The remaining checks depend on the data arguments.
3558 if (HasVAListArg)
3559 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003560
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003561 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003562 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003563
Jordan Rose58bbe422012-07-19 18:10:08 +00003564 const Expr *Arg = getDataArg(argIndex);
3565 if (!Arg)
3566 return true;
3567
3568 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003569}
3570
Jordan Roseaee34382012-09-05 22:56:26 +00003571static bool requiresParensToAddCast(const Expr *E) {
3572 // FIXME: We should have a general way to reason about operator
3573 // precedence and whether parens are actually needed here.
3574 // Take care of a few common cases where they aren't.
3575 const Expr *Inside = E->IgnoreImpCasts();
3576 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3577 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3578
3579 switch (Inside->getStmtClass()) {
3580 case Stmt::ArraySubscriptExprClass:
3581 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003582 case Stmt::CharacterLiteralClass:
3583 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003584 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003585 case Stmt::FloatingLiteralClass:
3586 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003587 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003588 case Stmt::ObjCArrayLiteralClass:
3589 case Stmt::ObjCBoolLiteralExprClass:
3590 case Stmt::ObjCBoxedExprClass:
3591 case Stmt::ObjCDictionaryLiteralClass:
3592 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003593 case Stmt::ObjCIvarRefExprClass:
3594 case Stmt::ObjCMessageExprClass:
3595 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003596 case Stmt::ObjCStringLiteralClass:
3597 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003598 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003599 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003600 case Stmt::UnaryOperatorClass:
3601 return false;
3602 default:
3603 return true;
3604 }
3605}
3606
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003607static std::pair<QualType, StringRef>
3608shouldNotPrintDirectly(const ASTContext &Context,
3609 QualType IntendedTy,
3610 const Expr *E) {
3611 // Use a 'while' to peel off layers of typedefs.
3612 QualType TyTy = IntendedTy;
3613 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3614 StringRef Name = UserTy->getDecl()->getName();
3615 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3616 .Case("NSInteger", Context.LongTy)
3617 .Case("NSUInteger", Context.UnsignedLongTy)
3618 .Case("SInt32", Context.IntTy)
3619 .Case("UInt32", Context.UnsignedIntTy)
3620 .Default(QualType());
3621
3622 if (!CastTy.isNull())
3623 return std::make_pair(CastTy, Name);
3624
3625 TyTy = UserTy->desugar();
3626 }
3627
3628 // Strip parens if necessary.
3629 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3630 return shouldNotPrintDirectly(Context,
3631 PE->getSubExpr()->getType(),
3632 PE->getSubExpr());
3633
3634 // If this is a conditional expression, then its result type is constructed
3635 // via usual arithmetic conversions and thus there might be no necessary
3636 // typedef sugar there. Recurse to operands to check for NSInteger &
3637 // Co. usage condition.
3638 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3639 QualType TrueTy, FalseTy;
3640 StringRef TrueName, FalseName;
3641
3642 std::tie(TrueTy, TrueName) =
3643 shouldNotPrintDirectly(Context,
3644 CO->getTrueExpr()->getType(),
3645 CO->getTrueExpr());
3646 std::tie(FalseTy, FalseName) =
3647 shouldNotPrintDirectly(Context,
3648 CO->getFalseExpr()->getType(),
3649 CO->getFalseExpr());
3650
3651 if (TrueTy == FalseTy)
3652 return std::make_pair(TrueTy, TrueName);
3653 else if (TrueTy.isNull())
3654 return std::make_pair(FalseTy, FalseName);
3655 else if (FalseTy.isNull())
3656 return std::make_pair(TrueTy, TrueName);
3657 }
3658
3659 return std::make_pair(QualType(), StringRef());
3660}
3661
Richard Smith55ce3522012-06-25 20:30:08 +00003662bool
3663CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3664 const char *StartSpecifier,
3665 unsigned SpecifierLen,
3666 const Expr *E) {
3667 using namespace analyze_format_string;
3668 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003669 // Now type check the data expression that matches the
3670 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003671 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3672 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003673 if (!AT.isValid())
3674 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003675
Jordan Rose598ec092012-12-05 18:44:40 +00003676 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003677 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3678 ExprTy = TET->getUnderlyingExpr()->getType();
3679 }
3680
Jordan Rose598ec092012-12-05 18:44:40 +00003681 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003682 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003683
Jordan Rose22b74712012-09-05 22:56:19 +00003684 // Look through argument promotions for our error message's reported type.
3685 // This includes the integral and floating promotions, but excludes array
3686 // and function pointer decay; seeing that an argument intended to be a
3687 // string has type 'char [6]' is probably more confusing than 'char *'.
3688 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3689 if (ICE->getCastKind() == CK_IntegralCast ||
3690 ICE->getCastKind() == CK_FloatingCast) {
3691 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003692 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003693
3694 // Check if we didn't match because of an implicit cast from a 'char'
3695 // or 'short' to an 'int'. This is done because printf is a varargs
3696 // function.
3697 if (ICE->getType() == S.Context.IntTy ||
3698 ICE->getType() == S.Context.UnsignedIntTy) {
3699 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003700 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003701 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003702 }
Jordan Rose98709982012-06-04 22:48:57 +00003703 }
Jordan Rose598ec092012-12-05 18:44:40 +00003704 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3705 // Special case for 'a', which has type 'int' in C.
3706 // Note, however, that we do /not/ want to treat multibyte constants like
3707 // 'MooV' as characters! This form is deprecated but still exists.
3708 if (ExprTy == S.Context.IntTy)
3709 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3710 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003711 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003712
Jordan Rosebc53ed12014-05-31 04:12:14 +00003713 // Look through enums to their underlying type.
3714 bool IsEnum = false;
3715 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3716 ExprTy = EnumTy->getDecl()->getIntegerType();
3717 IsEnum = true;
3718 }
3719
Jordan Rose0e5badd2012-12-05 18:44:49 +00003720 // %C in an Objective-C context prints a unichar, not a wchar_t.
3721 // If the argument is an integer of some kind, believe the %C and suggest
3722 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003723 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003724 if (ObjCContext &&
3725 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3726 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3727 !ExprTy->isCharType()) {
3728 // 'unichar' is defined as a typedef of unsigned short, but we should
3729 // prefer using the typedef if it is visible.
3730 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003731
3732 // While we are here, check if the value is an IntegerLiteral that happens
3733 // to be within the valid range.
3734 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3735 const llvm::APInt &V = IL->getValue();
3736 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3737 return true;
3738 }
3739
Jordan Rose0e5badd2012-12-05 18:44:49 +00003740 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3741 Sema::LookupOrdinaryName);
3742 if (S.LookupName(Result, S.getCurScope())) {
3743 NamedDecl *ND = Result.getFoundDecl();
3744 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3745 if (TD->getUnderlyingType() == IntendedTy)
3746 IntendedTy = S.Context.getTypedefType(TD);
3747 }
3748 }
3749 }
3750
3751 // Special-case some of Darwin's platform-independence types by suggesting
3752 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003753 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00003754 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003755 QualType CastTy;
3756 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3757 if (!CastTy.isNull()) {
3758 IntendedTy = CastTy;
3759 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00003760 }
3761 }
3762
Jordan Rose22b74712012-09-05 22:56:19 +00003763 // We may be able to offer a FixItHint if it is a supported type.
3764 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003765 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003766 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003767
Jordan Rose22b74712012-09-05 22:56:19 +00003768 if (success) {
3769 // Get the fix string from the fixed format specifier
3770 SmallString<16> buf;
3771 llvm::raw_svector_ostream os(buf);
3772 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003773
Jordan Roseaee34382012-09-05 22:56:26 +00003774 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3775
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003776 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Jordan Rose0e5badd2012-12-05 18:44:49 +00003777 // In this case, the specifier is wrong and should be changed to match
3778 // the argument.
3779 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003780 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3781 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003782 << E->getSourceRange(),
3783 E->getLocStart(),
3784 /*IsStringLocation*/false,
3785 SpecRange,
3786 FixItHint::CreateReplacement(SpecRange, os.str()));
3787
3788 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003789 // The canonical type for formatting this value is different from the
3790 // actual type of the expression. (This occurs, for example, with Darwin's
3791 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3792 // should be printed as 'long' for 64-bit compatibility.)
3793 // Rather than emitting a normal format/argument mismatch, we want to
3794 // add a cast to the recommended type (and correct the format string
3795 // if necessary).
3796 SmallString<16> CastBuf;
3797 llvm::raw_svector_ostream CastFix(CastBuf);
3798 CastFix << "(";
3799 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3800 CastFix << ")";
3801
3802 SmallVector<FixItHint,4> Hints;
3803 if (!AT.matchesType(S.Context, IntendedTy))
3804 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3805
3806 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3807 // If there's already a cast present, just replace it.
3808 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3809 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3810
3811 } else if (!requiresParensToAddCast(E)) {
3812 // If the expression has high enough precedence,
3813 // just write the C-style cast.
3814 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3815 CastFix.str()));
3816 } else {
3817 // Otherwise, add parens around the expression as well as the cast.
3818 CastFix << "(";
3819 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3820 CastFix.str()));
3821
Alp Tokerb6cc5922014-05-03 03:45:55 +00003822 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003823 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3824 }
3825
Jordan Rose0e5badd2012-12-05 18:44:49 +00003826 if (ShouldNotPrintDirectly) {
3827 // The expression has a type that should not be printed directly.
3828 // We extract the name from the typedef because we don't want to show
3829 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003830 StringRef Name;
3831 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3832 Name = TypedefTy->getDecl()->getName();
3833 else
3834 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003835 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003836 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003837 << E->getSourceRange(),
3838 E->getLocStart(), /*IsStringLocation=*/false,
3839 SpecRange, Hints);
3840 } else {
3841 // In this case, the expression could be printed using a different
3842 // specifier, but we've decided that the specifier is probably correct
3843 // and we should cast instead. Just use the normal warning message.
3844 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003845 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3846 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003847 << E->getSourceRange(),
3848 E->getLocStart(), /*IsStringLocation*/false,
3849 SpecRange, Hints);
3850 }
Jordan Roseaee34382012-09-05 22:56:26 +00003851 }
Jordan Rose22b74712012-09-05 22:56:19 +00003852 } else {
3853 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3854 SpecifierLen);
3855 // Since the warning for passing non-POD types to variadic functions
3856 // was deferred until now, we emit a warning for non-POD
3857 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003858 switch (S.isValidVarArgType(ExprTy)) {
3859 case Sema::VAK_Valid:
3860 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003861 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003862 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3863 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003864 << CSR
3865 << E->getSourceRange(),
3866 E->getLocStart(), /*IsStringLocation*/false, CSR);
3867 break;
3868
3869 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00003870 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00003871 EmitFormatDiagnostic(
3872 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003873 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003874 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003875 << CallType
3876 << AT.getRepresentativeTypeName(S.Context)
3877 << CSR
3878 << E->getSourceRange(),
3879 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003880 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003881 break;
3882
3883 case Sema::VAK_Invalid:
3884 if (ExprTy->isObjCObjectType())
3885 EmitFormatDiagnostic(
3886 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3887 << S.getLangOpts().CPlusPlus11
3888 << ExprTy
3889 << CallType
3890 << AT.getRepresentativeTypeName(S.Context)
3891 << CSR
3892 << E->getSourceRange(),
3893 E->getLocStart(), /*IsStringLocation*/false, CSR);
3894 else
3895 // FIXME: If this is an initializer list, suggest removing the braces
3896 // or inserting a cast to the target type.
3897 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3898 << isa<InitListExpr>(E) << ExprTy << CallType
3899 << AT.getRepresentativeTypeName(S.Context)
3900 << E->getSourceRange();
3901 break;
3902 }
3903
3904 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3905 "format string specifier index out of range");
3906 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003907 }
3908
Ted Kremenekab278de2010-01-28 23:39:18 +00003909 return true;
3910}
3911
Ted Kremenek02087932010-07-16 02:11:22 +00003912//===--- CHECK: Scanf format string checking ------------------------------===//
3913
3914namespace {
3915class CheckScanfHandler : public CheckFormatHandler {
3916public:
3917 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3918 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003919 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003920 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003921 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003922 Sema::VariadicCallType CallType,
3923 llvm::SmallBitVector &CheckedVarArgs)
3924 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3925 numDataArgs, beg, hasVAListArg,
3926 Args, formatIdx, inFunctionCall, CallType,
3927 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003928 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003929
3930 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3931 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003932 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003933
3934 bool HandleInvalidScanfConversionSpecifier(
3935 const analyze_scanf::ScanfSpecifier &FS,
3936 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003937 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003938
Craig Toppere14c0f82014-03-12 04:55:44 +00003939 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003940};
Ted Kremenek019d2242010-01-29 01:50:07 +00003941}
Ted Kremenekab278de2010-01-28 23:39:18 +00003942
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003943void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3944 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003945 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3946 getLocationOfByte(end), /*IsStringLocation*/true,
3947 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003948}
3949
Ted Kremenekce815422010-07-19 21:25:57 +00003950bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3951 const analyze_scanf::ScanfSpecifier &FS,
3952 const char *startSpecifier,
3953 unsigned specifierLen) {
3954
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003955 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003956 FS.getConversionSpecifier();
3957
3958 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3959 getLocationOfByte(CS.getStart()),
3960 startSpecifier, specifierLen,
3961 CS.getStart(), CS.getLength());
3962}
3963
Ted Kremenek02087932010-07-16 02:11:22 +00003964bool CheckScanfHandler::HandleScanfSpecifier(
3965 const analyze_scanf::ScanfSpecifier &FS,
3966 const char *startSpecifier,
3967 unsigned specifierLen) {
3968
3969 using namespace analyze_scanf;
3970 using namespace analyze_format_string;
3971
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003972 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003973
Ted Kremenek6cd69422010-07-19 22:01:06 +00003974 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3975 // be used to decide if we are using positional arguments consistently.
3976 if (FS.consumesDataArgument()) {
3977 if (atFirstArg) {
3978 atFirstArg = false;
3979 usesPositionalArgs = FS.usesPositionalArg();
3980 }
3981 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003982 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3983 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003984 return false;
3985 }
Ted Kremenek02087932010-07-16 02:11:22 +00003986 }
3987
3988 // Check if the field with is non-zero.
3989 const OptionalAmount &Amt = FS.getFieldWidth();
3990 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3991 if (Amt.getConstantAmount() == 0) {
3992 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3993 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003994 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3995 getLocationOfByte(Amt.getStart()),
3996 /*IsStringLocation*/true, R,
3997 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003998 }
3999 }
4000
4001 if (!FS.consumesDataArgument()) {
4002 // FIXME: Technically specifying a precision or field width here
4003 // makes no sense. Worth issuing a warning at some point.
4004 return true;
4005 }
4006
4007 // Consume the argument.
4008 unsigned argIndex = FS.getArgIndex();
4009 if (argIndex < NumDataArgs) {
4010 // The check to see if the argIndex is valid will come later.
4011 // We set the bit here because we may exit early from this
4012 // function if we encounter some other error.
4013 CoveredArgs.set(argIndex);
4014 }
4015
Ted Kremenek4407ea42010-07-20 20:04:47 +00004016 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004017 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004018 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4019 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004020 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004021 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004022 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004023 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4024 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004025
Jordan Rose92303592012-09-08 04:00:03 +00004026 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4027 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4028
Ted Kremenek02087932010-07-16 02:11:22 +00004029 // The remaining checks depend on the data arguments.
4030 if (HasVAListArg)
4031 return true;
4032
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004033 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004034 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00004035
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004036 // Check that the argument type matches the format specifier.
4037 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004038 if (!Ex)
4039 return true;
4040
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004041 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
4042 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004043 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00004044 bool success = fixedFS.fixType(Ex->getType(),
4045 Ex->IgnoreImpCasts()->getType(),
4046 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004047
4048 if (success) {
4049 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004050 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004051 llvm::raw_svector_ostream os(buf);
4052 fixedFS.toString(os);
4053
4054 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004055 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4056 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004057 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00004058 Ex->getLocStart(),
4059 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004060 getSpecifierRange(startSpecifier, specifierLen),
4061 FixItHint::CreateReplacement(
4062 getSpecifierRange(startSpecifier, specifierLen),
4063 os.str()));
4064 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00004065 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004066 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4067 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00004068 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00004069 Ex->getLocStart(),
4070 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00004071 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004072 }
4073 }
4074
Ted Kremenek02087932010-07-16 02:11:22 +00004075 return true;
4076}
4077
4078void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004079 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004080 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004081 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004082 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004083 bool inFunctionCall, VariadicCallType CallType,
4084 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004085
Ted Kremenekab278de2010-01-28 23:39:18 +00004086 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004087 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004088 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004089 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004090 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4091 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004092 return;
4093 }
Ted Kremenek02087932010-07-16 02:11:22 +00004094
Ted Kremenekab278de2010-01-28 23:39:18 +00004095 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004096 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004097 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004098 // Account for cases where the string literal is truncated in a declaration.
4099 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4100 assert(T && "String literal not of constant array type!");
4101 size_t TypeSize = T->getSize().getZExtValue();
4102 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004103 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004104
4105 // Emit a warning if the string literal is truncated and does not contain an
4106 // embedded null character.
4107 if (TypeSize <= StrRef.size() &&
4108 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4109 CheckFormatHandler::EmitFormatDiagnostic(
4110 *this, inFunctionCall, Args[format_idx],
4111 PDiag(diag::warn_printf_format_string_not_null_terminated),
4112 FExpr->getLocStart(),
4113 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4114 return;
4115 }
4116
Ted Kremenekab278de2010-01-28 23:39:18 +00004117 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004118 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004119 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004120 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004121 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4122 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004123 return;
4124 }
Ted Kremenek02087932010-07-16 02:11:22 +00004125
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004126 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004127 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004128 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004129 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004130 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004131 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004132
Hans Wennborg23926bd2011-12-15 10:25:47 +00004133 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004134 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004135 Context.getTargetInfo(),
4136 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004137 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004138 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004139 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004140 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004141 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004142
Hans Wennborg23926bd2011-12-15 10:25:47 +00004143 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004144 getLangOpts(),
4145 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004146 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004147 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004148}
4149
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004150bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4151 // Str - The format string. NOTE: this is NOT null-terminated!
4152 StringRef StrRef = FExpr->getString();
4153 const char *Str = StrRef.data();
4154 // Account for cases where the string literal is truncated in a declaration.
4155 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4156 assert(T && "String literal not of constant array type!");
4157 size_t TypeSize = T->getSize().getZExtValue();
4158 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4159 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4160 getLangOpts(),
4161 Context.getTargetInfo());
4162}
4163
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004164//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4165
4166// Returns the related absolute value function that is larger, of 0 if one
4167// does not exist.
4168static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4169 switch (AbsFunction) {
4170 default:
4171 return 0;
4172
4173 case Builtin::BI__builtin_abs:
4174 return Builtin::BI__builtin_labs;
4175 case Builtin::BI__builtin_labs:
4176 return Builtin::BI__builtin_llabs;
4177 case Builtin::BI__builtin_llabs:
4178 return 0;
4179
4180 case Builtin::BI__builtin_fabsf:
4181 return Builtin::BI__builtin_fabs;
4182 case Builtin::BI__builtin_fabs:
4183 return Builtin::BI__builtin_fabsl;
4184 case Builtin::BI__builtin_fabsl:
4185 return 0;
4186
4187 case Builtin::BI__builtin_cabsf:
4188 return Builtin::BI__builtin_cabs;
4189 case Builtin::BI__builtin_cabs:
4190 return Builtin::BI__builtin_cabsl;
4191 case Builtin::BI__builtin_cabsl:
4192 return 0;
4193
4194 case Builtin::BIabs:
4195 return Builtin::BIlabs;
4196 case Builtin::BIlabs:
4197 return Builtin::BIllabs;
4198 case Builtin::BIllabs:
4199 return 0;
4200
4201 case Builtin::BIfabsf:
4202 return Builtin::BIfabs;
4203 case Builtin::BIfabs:
4204 return Builtin::BIfabsl;
4205 case Builtin::BIfabsl:
4206 return 0;
4207
4208 case Builtin::BIcabsf:
4209 return Builtin::BIcabs;
4210 case Builtin::BIcabs:
4211 return Builtin::BIcabsl;
4212 case Builtin::BIcabsl:
4213 return 0;
4214 }
4215}
4216
4217// Returns the argument type of the absolute value function.
4218static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4219 unsigned AbsType) {
4220 if (AbsType == 0)
4221 return QualType();
4222
4223 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4224 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4225 if (Error != ASTContext::GE_None)
4226 return QualType();
4227
4228 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4229 if (!FT)
4230 return QualType();
4231
4232 if (FT->getNumParams() != 1)
4233 return QualType();
4234
4235 return FT->getParamType(0);
4236}
4237
4238// Returns the best absolute value function, or zero, based on type and
4239// current absolute value function.
4240static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4241 unsigned AbsFunctionKind) {
4242 unsigned BestKind = 0;
4243 uint64_t ArgSize = Context.getTypeSize(ArgType);
4244 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4245 Kind = getLargerAbsoluteValueFunction(Kind)) {
4246 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4247 if (Context.getTypeSize(ParamType) >= ArgSize) {
4248 if (BestKind == 0)
4249 BestKind = Kind;
4250 else if (Context.hasSameType(ParamType, ArgType)) {
4251 BestKind = Kind;
4252 break;
4253 }
4254 }
4255 }
4256 return BestKind;
4257}
4258
4259enum AbsoluteValueKind {
4260 AVK_Integer,
4261 AVK_Floating,
4262 AVK_Complex
4263};
4264
4265static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4266 if (T->isIntegralOrEnumerationType())
4267 return AVK_Integer;
4268 if (T->isRealFloatingType())
4269 return AVK_Floating;
4270 if (T->isAnyComplexType())
4271 return AVK_Complex;
4272
4273 llvm_unreachable("Type not integer, floating, or complex");
4274}
4275
4276// Changes the absolute value function to a different type. Preserves whether
4277// the function is a builtin.
4278static unsigned changeAbsFunction(unsigned AbsKind,
4279 AbsoluteValueKind ValueKind) {
4280 switch (ValueKind) {
4281 case AVK_Integer:
4282 switch (AbsKind) {
4283 default:
4284 return 0;
4285 case Builtin::BI__builtin_fabsf:
4286 case Builtin::BI__builtin_fabs:
4287 case Builtin::BI__builtin_fabsl:
4288 case Builtin::BI__builtin_cabsf:
4289 case Builtin::BI__builtin_cabs:
4290 case Builtin::BI__builtin_cabsl:
4291 return Builtin::BI__builtin_abs;
4292 case Builtin::BIfabsf:
4293 case Builtin::BIfabs:
4294 case Builtin::BIfabsl:
4295 case Builtin::BIcabsf:
4296 case Builtin::BIcabs:
4297 case Builtin::BIcabsl:
4298 return Builtin::BIabs;
4299 }
4300 case AVK_Floating:
4301 switch (AbsKind) {
4302 default:
4303 return 0;
4304 case Builtin::BI__builtin_abs:
4305 case Builtin::BI__builtin_labs:
4306 case Builtin::BI__builtin_llabs:
4307 case Builtin::BI__builtin_cabsf:
4308 case Builtin::BI__builtin_cabs:
4309 case Builtin::BI__builtin_cabsl:
4310 return Builtin::BI__builtin_fabsf;
4311 case Builtin::BIabs:
4312 case Builtin::BIlabs:
4313 case Builtin::BIllabs:
4314 case Builtin::BIcabsf:
4315 case Builtin::BIcabs:
4316 case Builtin::BIcabsl:
4317 return Builtin::BIfabsf;
4318 }
4319 case AVK_Complex:
4320 switch (AbsKind) {
4321 default:
4322 return 0;
4323 case Builtin::BI__builtin_abs:
4324 case Builtin::BI__builtin_labs:
4325 case Builtin::BI__builtin_llabs:
4326 case Builtin::BI__builtin_fabsf:
4327 case Builtin::BI__builtin_fabs:
4328 case Builtin::BI__builtin_fabsl:
4329 return Builtin::BI__builtin_cabsf;
4330 case Builtin::BIabs:
4331 case Builtin::BIlabs:
4332 case Builtin::BIllabs:
4333 case Builtin::BIfabsf:
4334 case Builtin::BIfabs:
4335 case Builtin::BIfabsl:
4336 return Builtin::BIcabsf;
4337 }
4338 }
4339 llvm_unreachable("Unable to convert function");
4340}
4341
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004342static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004343 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4344 if (!FnInfo)
4345 return 0;
4346
4347 switch (FDecl->getBuiltinID()) {
4348 default:
4349 return 0;
4350 case Builtin::BI__builtin_abs:
4351 case Builtin::BI__builtin_fabs:
4352 case Builtin::BI__builtin_fabsf:
4353 case Builtin::BI__builtin_fabsl:
4354 case Builtin::BI__builtin_labs:
4355 case Builtin::BI__builtin_llabs:
4356 case Builtin::BI__builtin_cabs:
4357 case Builtin::BI__builtin_cabsf:
4358 case Builtin::BI__builtin_cabsl:
4359 case Builtin::BIabs:
4360 case Builtin::BIlabs:
4361 case Builtin::BIllabs:
4362 case Builtin::BIfabs:
4363 case Builtin::BIfabsf:
4364 case Builtin::BIfabsl:
4365 case Builtin::BIcabs:
4366 case Builtin::BIcabsf:
4367 case Builtin::BIcabsl:
4368 return FDecl->getBuiltinID();
4369 }
4370 llvm_unreachable("Unknown Builtin type");
4371}
4372
4373// If the replacement is valid, emit a note with replacement function.
4374// Additionally, suggest including the proper header if not already included.
4375static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004376 unsigned AbsKind, QualType ArgType) {
4377 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004378 const char *HeaderName = nullptr;
4379 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004380 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4381 FunctionName = "std::abs";
4382 if (ArgType->isIntegralOrEnumerationType()) {
4383 HeaderName = "cstdlib";
4384 } else if (ArgType->isRealFloatingType()) {
4385 HeaderName = "cmath";
4386 } else {
4387 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004388 }
Richard Trieubeffb832014-04-15 23:47:53 +00004389
4390 // Lookup all std::abs
4391 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004392 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004393 R.suppressDiagnostics();
4394 S.LookupQualifiedName(R, Std);
4395
4396 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004397 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004398 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4399 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4400 } else {
4401 FDecl = dyn_cast<FunctionDecl>(I);
4402 }
4403 if (!FDecl)
4404 continue;
4405
4406 // Found std::abs(), check that they are the right ones.
4407 if (FDecl->getNumParams() != 1)
4408 continue;
4409
4410 // Check that the parameter type can handle the argument.
4411 QualType ParamType = FDecl->getParamDecl(0)->getType();
4412 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4413 S.Context.getTypeSize(ArgType) <=
4414 S.Context.getTypeSize(ParamType)) {
4415 // Found a function, don't need the header hint.
4416 EmitHeaderHint = false;
4417 break;
4418 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004419 }
Richard Trieubeffb832014-04-15 23:47:53 +00004420 }
4421 } else {
4422 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4423 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4424
4425 if (HeaderName) {
4426 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4427 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4428 R.suppressDiagnostics();
4429 S.LookupName(R, S.getCurScope());
4430
4431 if (R.isSingleResult()) {
4432 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4433 if (FD && FD->getBuiltinID() == AbsKind) {
4434 EmitHeaderHint = false;
4435 } else {
4436 return;
4437 }
4438 } else if (!R.empty()) {
4439 return;
4440 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004441 }
4442 }
4443
4444 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004445 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004446
Richard Trieubeffb832014-04-15 23:47:53 +00004447 if (!HeaderName)
4448 return;
4449
4450 if (!EmitHeaderHint)
4451 return;
4452
Alp Toker5d96e0a2014-07-11 20:53:51 +00004453 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4454 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004455}
4456
4457static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4458 if (!FDecl)
4459 return false;
4460
4461 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4462 return false;
4463
4464 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4465
4466 while (ND && ND->isInlineNamespace()) {
4467 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004468 }
Richard Trieubeffb832014-04-15 23:47:53 +00004469
4470 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4471 return false;
4472
4473 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4474 return false;
4475
4476 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004477}
4478
4479// Warn when using the wrong abs() function.
4480void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4481 const FunctionDecl *FDecl,
4482 IdentifierInfo *FnInfo) {
4483 if (Call->getNumArgs() != 1)
4484 return;
4485
4486 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004487 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4488 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004489 return;
4490
4491 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4492 QualType ParamType = Call->getArg(0)->getType();
4493
Alp Toker5d96e0a2014-07-11 20:53:51 +00004494 // Unsigned types cannot be negative. Suggest removing the absolute value
4495 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004496 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004497 const char *FunctionName =
4498 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004499 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4500 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004501 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004502 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4503 return;
4504 }
4505
Richard Trieubeffb832014-04-15 23:47:53 +00004506 // std::abs has overloads which prevent most of the absolute value problems
4507 // from occurring.
4508 if (IsStdAbs)
4509 return;
4510
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004511 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4512 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4513
4514 // The argument and parameter are the same kind. Check if they are the right
4515 // size.
4516 if (ArgValueKind == ParamValueKind) {
4517 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4518 return;
4519
4520 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4521 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4522 << FDecl << ArgType << ParamType;
4523
4524 if (NewAbsKind == 0)
4525 return;
4526
4527 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004528 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004529 return;
4530 }
4531
4532 // ArgValueKind != ParamValueKind
4533 // The wrong type of absolute value function was used. Attempt to find the
4534 // proper one.
4535 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4536 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4537 if (NewAbsKind == 0)
4538 return;
4539
4540 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4541 << FDecl << ParamValueKind << ArgValueKind;
4542
4543 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004544 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004545 return;
4546}
4547
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004548//===--- CHECK: Standard memory functions ---------------------------------===//
4549
Nico Weber0e6daef2013-12-26 23:38:39 +00004550/// \brief Takes the expression passed to the size_t parameter of functions
4551/// such as memcmp, strncat, etc and warns if it's a comparison.
4552///
4553/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4554static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4555 IdentifierInfo *FnName,
4556 SourceLocation FnLoc,
4557 SourceLocation RParenLoc) {
4558 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4559 if (!Size)
4560 return false;
4561
4562 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4563 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4564 return false;
4565
Nico Weber0e6daef2013-12-26 23:38:39 +00004566 SourceRange SizeRange = Size->getSourceRange();
4567 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4568 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004569 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004570 << FnName << FixItHint::CreateInsertion(
4571 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004572 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004573 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004574 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004575 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4576 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004577
4578 return true;
4579}
4580
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004581/// \brief Determine whether the given type is or contains a dynamic class type
4582/// (e.g., whether it has a vtable).
4583static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4584 bool &IsContained) {
4585 // Look through array types while ignoring qualifiers.
4586 const Type *Ty = T->getBaseElementTypeUnsafe();
4587 IsContained = false;
4588
4589 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4590 RD = RD ? RD->getDefinition() : nullptr;
4591 if (!RD)
4592 return nullptr;
4593
4594 if (RD->isDynamicClass())
4595 return RD;
4596
4597 // Check all the fields. If any bases were dynamic, the class is dynamic.
4598 // It's impossible for a class to transitively contain itself by value, so
4599 // infinite recursion is impossible.
4600 for (auto *FD : RD->fields()) {
4601 bool SubContained;
4602 if (const CXXRecordDecl *ContainedRD =
4603 getContainedDynamicClass(FD->getType(), SubContained)) {
4604 IsContained = true;
4605 return ContainedRD;
4606 }
4607 }
4608
4609 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004610}
4611
Chandler Carruth889ed862011-06-21 23:04:20 +00004612/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004613/// otherwise returns NULL.
4614static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004615 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004616 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4617 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4618 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004619
Craig Topperc3ec1492014-05-26 06:22:03 +00004620 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004621}
4622
Chandler Carruth889ed862011-06-21 23:04:20 +00004623/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004624static QualType getSizeOfArgType(const Expr* E) {
4625 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4626 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4627 if (SizeOf->getKind() == clang::UETT_SizeOf)
4628 return SizeOf->getTypeOfArgument();
4629
4630 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004631}
4632
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004633/// \brief Check for dangerous or invalid arguments to memset().
4634///
Chandler Carruthac687262011-06-03 06:23:57 +00004635/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004636/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4637/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004638///
4639/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004640void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004641 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004642 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004643 assert(BId != 0);
4644
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004645 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004646 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004647 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004648 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004649 return;
4650
Anna Zaks22122702012-01-17 00:37:07 +00004651 unsigned LastArg = (BId == Builtin::BImemset ||
4652 BId == Builtin::BIstrndup ? 1 : 2);
4653 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004654 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004655
Nico Weber0e6daef2013-12-26 23:38:39 +00004656 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4657 Call->getLocStart(), Call->getRParenLoc()))
4658 return;
4659
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004660 // We have special checking when the length is a sizeof expression.
4661 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4662 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4663 llvm::FoldingSetNodeID SizeOfArgID;
4664
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004665 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4666 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004667 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004668
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004669 QualType DestTy = Dest->getType();
4670 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4671 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004672
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004673 // Never warn about void type pointers. This can be used to suppress
4674 // false positives.
4675 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004676 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004677
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004678 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4679 // actually comparing the expressions for equality. Because computing the
4680 // expression IDs can be expensive, we only do this if the diagnostic is
4681 // enabled.
4682 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004683 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4684 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004685 // We only compute IDs for expressions if the warning is enabled, and
4686 // cache the sizeof arg's ID.
4687 if (SizeOfArgID == llvm::FoldingSetNodeID())
4688 SizeOfArg->Profile(SizeOfArgID, Context, true);
4689 llvm::FoldingSetNodeID DestID;
4690 Dest->Profile(DestID, Context, true);
4691 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004692 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4693 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004694 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004695 StringRef ReadableName = FnName->getName();
4696
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004697 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004698 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004699 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004700 if (!PointeeTy->isIncompleteType() &&
4701 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004702 ActionIdx = 2; // If the pointee's size is sizeof(char),
4703 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004704
4705 // If the function is defined as a builtin macro, do not show macro
4706 // expansion.
4707 SourceLocation SL = SizeOfArg->getExprLoc();
4708 SourceRange DSR = Dest->getSourceRange();
4709 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004710 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004711
4712 if (SM.isMacroArgExpansion(SL)) {
4713 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4714 SL = SM.getSpellingLoc(SL);
4715 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4716 SM.getSpellingLoc(DSR.getEnd()));
4717 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4718 SM.getSpellingLoc(SSR.getEnd()));
4719 }
4720
Anna Zaksd08d9152012-05-30 23:14:52 +00004721 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004722 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004723 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004724 << PointeeTy
4725 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004726 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004727 << SSR);
4728 DiagRuntimeBehavior(SL, SizeOfArg,
4729 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4730 << ActionIdx
4731 << SSR);
4732
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004733 break;
4734 }
4735 }
4736
4737 // Also check for cases where the sizeof argument is the exact same
4738 // type as the memory argument, and where it points to a user-defined
4739 // record type.
4740 if (SizeOfArgTy != QualType()) {
4741 if (PointeeTy->isRecordType() &&
4742 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4743 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4744 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4745 << FnName << SizeOfArgTy << ArgIdx
4746 << PointeeTy << Dest->getSourceRange()
4747 << LenExpr->getSourceRange());
4748 break;
4749 }
Nico Weberc5e73862011-06-14 16:14:58 +00004750 }
4751
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004752 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004753 bool IsContained;
4754 if (const CXXRecordDecl *ContainedRD =
4755 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004756
4757 unsigned OperationType = 0;
4758 // "overwritten" if we're warning about the destination for any call
4759 // but memcmp; otherwise a verb appropriate to the call.
4760 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4761 if (BId == Builtin::BImemcpy)
4762 OperationType = 1;
4763 else if(BId == Builtin::BImemmove)
4764 OperationType = 2;
4765 else if (BId == Builtin::BImemcmp)
4766 OperationType = 3;
4767 }
4768
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004769 DiagRuntimeBehavior(
4770 Dest->getExprLoc(), Dest,
4771 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004772 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004773 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004774 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004775 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4776 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004777 DiagRuntimeBehavior(
4778 Dest->getExprLoc(), Dest,
4779 PDiag(diag::warn_arc_object_memaccess)
4780 << ArgIdx << FnName << PointeeTy
4781 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004782 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004783 continue;
John McCall31168b02011-06-15 23:02:42 +00004784
4785 DiagRuntimeBehavior(
4786 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004787 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004788 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4789 break;
4790 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004791 }
4792}
4793
Ted Kremenek6865f772011-08-18 20:55:45 +00004794// A little helper routine: ignore addition and subtraction of integer literals.
4795// This intentionally does not ignore all integer constant expressions because
4796// we don't want to remove sizeof().
4797static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4798 Ex = Ex->IgnoreParenCasts();
4799
4800 for (;;) {
4801 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4802 if (!BO || !BO->isAdditiveOp())
4803 break;
4804
4805 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4806 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4807
4808 if (isa<IntegerLiteral>(RHS))
4809 Ex = LHS;
4810 else if (isa<IntegerLiteral>(LHS))
4811 Ex = RHS;
4812 else
4813 break;
4814 }
4815
4816 return Ex;
4817}
4818
Anna Zaks13b08572012-08-08 21:42:23 +00004819static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4820 ASTContext &Context) {
4821 // Only handle constant-sized or VLAs, but not flexible members.
4822 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4823 // Only issue the FIXIT for arrays of size > 1.
4824 if (CAT->getSize().getSExtValue() <= 1)
4825 return false;
4826 } else if (!Ty->isVariableArrayType()) {
4827 return false;
4828 }
4829 return true;
4830}
4831
Ted Kremenek6865f772011-08-18 20:55:45 +00004832// Warn if the user has made the 'size' argument to strlcpy or strlcat
4833// be the size of the source, instead of the destination.
4834void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4835 IdentifierInfo *FnName) {
4836
4837 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004838 unsigned NumArgs = Call->getNumArgs();
4839 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004840 return;
4841
4842 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4843 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004844 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004845
4846 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4847 Call->getLocStart(), Call->getRParenLoc()))
4848 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004849
4850 // Look for 'strlcpy(dst, x, sizeof(x))'
4851 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4852 CompareWithSrc = Ex;
4853 else {
4854 // Look for 'strlcpy(dst, x, strlen(x))'
4855 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004856 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4857 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004858 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4859 }
4860 }
4861
4862 if (!CompareWithSrc)
4863 return;
4864
4865 // Determine if the argument to sizeof/strlen is equal to the source
4866 // argument. In principle there's all kinds of things you could do
4867 // here, for instance creating an == expression and evaluating it with
4868 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4869 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4870 if (!SrcArgDRE)
4871 return;
4872
4873 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4874 if (!CompareWithSrcDRE ||
4875 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4876 return;
4877
4878 const Expr *OriginalSizeArg = Call->getArg(2);
4879 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4880 << OriginalSizeArg->getSourceRange() << FnName;
4881
4882 // Output a FIXIT hint if the destination is an array (rather than a
4883 // pointer to an array). This could be enhanced to handle some
4884 // pointers if we know the actual size, like if DstArg is 'array+2'
4885 // we could say 'sizeof(array)-2'.
4886 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004887 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004888 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004889
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004890 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004891 llvm::raw_svector_ostream OS(sizeString);
4892 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004893 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004894 OS << ")";
4895
4896 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4897 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4898 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004899}
4900
Anna Zaks314cd092012-02-01 19:08:57 +00004901/// Check if two expressions refer to the same declaration.
4902static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4903 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4904 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4905 return D1->getDecl() == D2->getDecl();
4906 return false;
4907}
4908
4909static const Expr *getStrlenExprArg(const Expr *E) {
4910 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4911 const FunctionDecl *FD = CE->getDirectCallee();
4912 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004913 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004914 return CE->getArg(0)->IgnoreParenCasts();
4915 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004916 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004917}
4918
4919// Warn on anti-patterns as the 'size' argument to strncat.
4920// The correct size argument should look like following:
4921// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4922void Sema::CheckStrncatArguments(const CallExpr *CE,
4923 IdentifierInfo *FnName) {
4924 // Don't crash if the user has the wrong number of arguments.
4925 if (CE->getNumArgs() < 3)
4926 return;
4927 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4928 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4929 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4930
Nico Weber0e6daef2013-12-26 23:38:39 +00004931 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4932 CE->getRParenLoc()))
4933 return;
4934
Anna Zaks314cd092012-02-01 19:08:57 +00004935 // Identify common expressions, which are wrongly used as the size argument
4936 // to strncat and may lead to buffer overflows.
4937 unsigned PatternType = 0;
4938 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4939 // - sizeof(dst)
4940 if (referToTheSameDecl(SizeOfArg, DstArg))
4941 PatternType = 1;
4942 // - sizeof(src)
4943 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4944 PatternType = 2;
4945 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4946 if (BE->getOpcode() == BO_Sub) {
4947 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4948 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4949 // - sizeof(dst) - strlen(dst)
4950 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4951 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4952 PatternType = 1;
4953 // - sizeof(src) - (anything)
4954 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4955 PatternType = 2;
4956 }
4957 }
4958
4959 if (PatternType == 0)
4960 return;
4961
Anna Zaks5069aa32012-02-03 01:27:37 +00004962 // Generate the diagnostic.
4963 SourceLocation SL = LenArg->getLocStart();
4964 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004965 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004966
4967 // If the function is defined as a builtin macro, do not show macro expansion.
4968 if (SM.isMacroArgExpansion(SL)) {
4969 SL = SM.getSpellingLoc(SL);
4970 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4971 SM.getSpellingLoc(SR.getEnd()));
4972 }
4973
Anna Zaks13b08572012-08-08 21:42:23 +00004974 // Check if the destination is an array (rather than a pointer to an array).
4975 QualType DstTy = DstArg->getType();
4976 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4977 Context);
4978 if (!isKnownSizeArray) {
4979 if (PatternType == 1)
4980 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4981 else
4982 Diag(SL, diag::warn_strncat_src_size) << SR;
4983 return;
4984 }
4985
Anna Zaks314cd092012-02-01 19:08:57 +00004986 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004987 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004988 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004989 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004990
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004991 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004992 llvm::raw_svector_ostream OS(sizeString);
4993 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004994 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004995 OS << ") - ";
4996 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004997 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004998 OS << ") - 1";
4999
Anna Zaks5069aa32012-02-03 01:27:37 +00005000 Diag(SL, diag::note_strncat_wrong_size)
5001 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005002}
5003
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005004//===--- CHECK: Return Address of Stack Variable --------------------------===//
5005
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005006static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5007 Decl *ParentDecl);
5008static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5009 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005010
5011/// CheckReturnStackAddr - Check if a return statement returns the address
5012/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005013static void
5014CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5015 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005016
Craig Topperc3ec1492014-05-26 06:22:03 +00005017 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005018 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005019
5020 // Perform checking for returned stack addresses, local blocks,
5021 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005022 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005023 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005024 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005025 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005026 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005027 }
5028
Craig Topperc3ec1492014-05-26 06:22:03 +00005029 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005030 return; // Nothing suspicious was found.
5031
5032 SourceLocation diagLoc;
5033 SourceRange diagRange;
5034 if (refVars.empty()) {
5035 diagLoc = stackE->getLocStart();
5036 diagRange = stackE->getSourceRange();
5037 } else {
5038 // We followed through a reference variable. 'stackE' contains the
5039 // problematic expression but we will warn at the return statement pointing
5040 // at the reference variable. We will later display the "trail" of
5041 // reference variables using notes.
5042 diagLoc = refVars[0]->getLocStart();
5043 diagRange = refVars[0]->getSourceRange();
5044 }
5045
5046 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005047 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005048 : diag::warn_ret_stack_addr)
5049 << DR->getDecl()->getDeclName() << diagRange;
5050 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005051 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005052 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005053 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005054 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005055 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5056 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005057 << diagRange;
5058 }
5059
5060 // Display the "trail" of reference variables that we followed until we
5061 // found the problematic expression using notes.
5062 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5063 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5064 // If this var binds to another reference var, show the range of the next
5065 // var, otherwise the var binds to the problematic expression, in which case
5066 // show the range of the expression.
5067 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5068 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005069 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5070 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005071 }
5072}
5073
5074/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5075/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005076/// to a location on the stack, a local block, an address of a label, or a
5077/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005078/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005079/// encounter a subexpression that (1) clearly does not lead to one of the
5080/// above problematic expressions (2) is something we cannot determine leads to
5081/// a problematic expression based on such local checking.
5082///
5083/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5084/// the expression that they point to. Such variables are added to the
5085/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005086///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005087/// EvalAddr processes expressions that are pointers that are used as
5088/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005089/// At the base case of the recursion is a check for the above problematic
5090/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005091///
5092/// This implementation handles:
5093///
5094/// * pointer-to-pointer casts
5095/// * implicit conversions from array references to pointers
5096/// * taking the address of fields
5097/// * arbitrary interplay between "&" and "*" operators
5098/// * pointer arithmetic from an address of a stack variable
5099/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005100static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5101 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005102 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005103 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005104
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005105 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005106 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005107 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005108 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005109 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005110
Peter Collingbourne91147592011-04-15 00:35:48 +00005111 E = E->IgnoreParens();
5112
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005113 // Our "symbolic interpreter" is just a dispatch off the currently
5114 // viewed AST node. We then recursively traverse the AST by calling
5115 // EvalAddr and EvalVal appropriately.
5116 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005117 case Stmt::DeclRefExprClass: {
5118 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5119
Richard Smith40f08eb2014-01-30 22:05:38 +00005120 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005121 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005122 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005123
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005124 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5125 // If this is a reference variable, follow through to the expression that
5126 // it points to.
5127 if (V->hasLocalStorage() &&
5128 V->getType()->isReferenceType() && V->hasInit()) {
5129 // Add the reference variable to the "trail".
5130 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005131 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005132 }
5133
Craig Topperc3ec1492014-05-26 06:22:03 +00005134 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005135 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005136
Chris Lattner934edb22007-12-28 05:31:15 +00005137 case Stmt::UnaryOperatorClass: {
5138 // The only unary operator that make sense to handle here
5139 // is AddrOf. All others don't make sense as pointers.
5140 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005141
John McCalle3027922010-08-25 11:45:40 +00005142 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005143 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005144 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005145 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005146 }
Mike Stump11289f42009-09-09 15:08:12 +00005147
Chris Lattner934edb22007-12-28 05:31:15 +00005148 case Stmt::BinaryOperatorClass: {
5149 // Handle pointer arithmetic. All other binary operators are not valid
5150 // in this context.
5151 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005152 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005153
John McCalle3027922010-08-25 11:45:40 +00005154 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005155 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005156
Chris Lattner934edb22007-12-28 05:31:15 +00005157 Expr *Base = B->getLHS();
5158
5159 // Determine which argument is the real pointer base. It could be
5160 // the RHS argument instead of the LHS.
5161 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005162
Chris Lattner934edb22007-12-28 05:31:15 +00005163 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005164 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005165 }
Steve Naroff2752a172008-09-10 19:17:48 +00005166
Chris Lattner934edb22007-12-28 05:31:15 +00005167 // For conditional operators we need to see if either the LHS or RHS are
5168 // valid DeclRefExpr*s. If one of them is valid, we return it.
5169 case Stmt::ConditionalOperatorClass: {
5170 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005171
Chris Lattner934edb22007-12-28 05:31:15 +00005172 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005173 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5174 if (Expr *LHSExpr = C->getLHS()) {
5175 // In C++, we can have a throw-expression, which has 'void' type.
5176 if (!LHSExpr->getType()->isVoidType())
5177 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005178 return LHS;
5179 }
Chris Lattner934edb22007-12-28 05:31:15 +00005180
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005181 // In C++, we can have a throw-expression, which has 'void' type.
5182 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005183 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005184
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005185 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005186 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005187
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005188 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005189 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005190 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005191 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005192
5193 case Stmt::AddrLabelExprClass:
5194 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005195
John McCall28fc7092011-11-10 05:35:25 +00005196 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005197 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5198 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005199
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005200 // For casts, we need to handle conversions from arrays to
5201 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005202 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005203 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005204 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005205 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005206 case Stmt::CXXStaticCastExprClass:
5207 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005208 case Stmt::CXXConstCastExprClass:
5209 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005210 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5211 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005212 case CK_LValueToRValue:
5213 case CK_NoOp:
5214 case CK_BaseToDerived:
5215 case CK_DerivedToBase:
5216 case CK_UncheckedDerivedToBase:
5217 case CK_Dynamic:
5218 case CK_CPointerToObjCPointerCast:
5219 case CK_BlockPointerToObjCPointerCast:
5220 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005221 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005222
5223 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005224 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005225
Richard Trieudadefde2014-07-02 04:39:38 +00005226 case CK_BitCast:
5227 if (SubExpr->getType()->isAnyPointerType() ||
5228 SubExpr->getType()->isBlockPointerType() ||
5229 SubExpr->getType()->isObjCQualifiedIdType())
5230 return EvalAddr(SubExpr, refVars, ParentDecl);
5231 else
5232 return nullptr;
5233
Eli Friedman8195ad72012-02-23 23:04:32 +00005234 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005235 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005236 }
Chris Lattner934edb22007-12-28 05:31:15 +00005237 }
Mike Stump11289f42009-09-09 15:08:12 +00005238
Douglas Gregorfe314812011-06-21 17:03:29 +00005239 case Stmt::MaterializeTemporaryExprClass:
5240 if (Expr *Result = EvalAddr(
5241 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005242 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005243 return Result;
5244
5245 return E;
5246
Chris Lattner934edb22007-12-28 05:31:15 +00005247 // Everything else: we simply don't reason about them.
5248 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005249 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005250 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005251}
Mike Stump11289f42009-09-09 15:08:12 +00005252
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005253
5254/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5255/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005256static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5257 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005258do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005259 // We should only be called for evaluating non-pointer expressions, or
5260 // expressions with a pointer type that are not used as references but instead
5261 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005262
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005263 // Our "symbolic interpreter" is just a dispatch off the currently
5264 // viewed AST node. We then recursively traverse the AST by calling
5265 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005266
5267 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005268 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005269 case Stmt::ImplicitCastExprClass: {
5270 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005271 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005272 E = IE->getSubExpr();
5273 continue;
5274 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005275 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005276 }
5277
John McCall28fc7092011-11-10 05:35:25 +00005278 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005279 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005280
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005281 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005282 // When we hit a DeclRefExpr we are looking at code that refers to a
5283 // variable's name. If it's not a reference variable we check if it has
5284 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005285 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005286
Richard Smith40f08eb2014-01-30 22:05:38 +00005287 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005288 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005289 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005290
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005291 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5292 // Check if it refers to itself, e.g. "int& i = i;".
5293 if (V == ParentDecl)
5294 return DR;
5295
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005296 if (V->hasLocalStorage()) {
5297 if (!V->getType()->isReferenceType())
5298 return DR;
5299
5300 // Reference variable, follow through to the expression that
5301 // it points to.
5302 if (V->hasInit()) {
5303 // Add the reference variable to the "trail".
5304 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005305 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005306 }
5307 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005308 }
Mike Stump11289f42009-09-09 15:08:12 +00005309
Craig Topperc3ec1492014-05-26 06:22:03 +00005310 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005311 }
Mike Stump11289f42009-09-09 15:08:12 +00005312
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005313 case Stmt::UnaryOperatorClass: {
5314 // The only unary operator that make sense to handle here
5315 // is Deref. All others don't resolve to a "name." This includes
5316 // handling all sorts of rvalues passed to a unary operator.
5317 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005318
John McCalle3027922010-08-25 11:45:40 +00005319 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005320 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005321
Craig Topperc3ec1492014-05-26 06:22:03 +00005322 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005323 }
Mike Stump11289f42009-09-09 15:08:12 +00005324
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005325 case Stmt::ArraySubscriptExprClass: {
5326 // Array subscripts are potential references to data on the stack. We
5327 // retrieve the DeclRefExpr* for the array variable if it indeed
5328 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005329 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005330 }
Mike Stump11289f42009-09-09 15:08:12 +00005331
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005332 case Stmt::ConditionalOperatorClass: {
5333 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005334 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005335 ConditionalOperator *C = cast<ConditionalOperator>(E);
5336
Anders Carlsson801c5c72007-11-30 19:04:31 +00005337 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005338 if (Expr *LHSExpr = C->getLHS()) {
5339 // In C++, we can have a throw-expression, which has 'void' type.
5340 if (!LHSExpr->getType()->isVoidType())
5341 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5342 return LHS;
5343 }
5344
5345 // In C++, we can have a throw-expression, which has 'void' type.
5346 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005347 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005348
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005349 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005350 }
Mike Stump11289f42009-09-09 15:08:12 +00005351
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005352 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005353 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005354 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005355
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005356 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005357 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005358 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005359
5360 // Check whether the member type is itself a reference, in which case
5361 // we're not going to refer to the member, but to what the member refers to.
5362 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005363 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005364
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005365 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005366 }
Mike Stump11289f42009-09-09 15:08:12 +00005367
Douglas Gregorfe314812011-06-21 17:03:29 +00005368 case Stmt::MaterializeTemporaryExprClass:
5369 if (Expr *Result = EvalVal(
5370 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005371 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005372 return Result;
5373
5374 return E;
5375
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005376 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005377 // Check that we don't return or take the address of a reference to a
5378 // temporary. This is only useful in C++.
5379 if (!E->isTypeDependent() && E->isRValue())
5380 return E;
5381
5382 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005383 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005384 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005385} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005386}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005387
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005388void
5389Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5390 SourceLocation ReturnLoc,
5391 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005392 const AttrVec *Attrs,
5393 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005394 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5395
5396 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005397 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5398 CheckNonNullExpr(*this, RetValExp))
5399 Diag(ReturnLoc, diag::warn_null_ret)
5400 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005401
5402 // C++11 [basic.stc.dynamic.allocation]p4:
5403 // If an allocation function declared with a non-throwing
5404 // exception-specification fails to allocate storage, it shall return
5405 // a null pointer. Any other allocation function that fails to allocate
5406 // storage shall indicate failure only by throwing an exception [...]
5407 if (FD) {
5408 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5409 if (Op == OO_New || Op == OO_Array_New) {
5410 const FunctionProtoType *Proto
5411 = FD->getType()->castAs<FunctionProtoType>();
5412 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5413 CheckNonNullExpr(*this, RetValExp))
5414 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5415 << FD << getLangOpts().CPlusPlus11;
5416 }
5417 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005418}
5419
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005420//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5421
5422/// Check for comparisons of floating point operands using != and ==.
5423/// Issue a warning if these are no self-comparisons, as they are not likely
5424/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005425void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005426 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5427 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005428
5429 // Special case: check for x == x (which is OK).
5430 // Do not emit warnings for such cases.
5431 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5432 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5433 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005434 return;
Mike Stump11289f42009-09-09 15:08:12 +00005435
5436
Ted Kremenekeda40e22007-11-29 00:59:04 +00005437 // Special case: check for comparisons against literals that can be exactly
5438 // represented by APFloat. In such cases, do not emit a warning. This
5439 // is a heuristic: often comparison against such literals are used to
5440 // detect if a value in a variable has not changed. This clearly can
5441 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005442 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5443 if (FLL->isExact())
5444 return;
5445 } else
5446 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5447 if (FLR->isExact())
5448 return;
Mike Stump11289f42009-09-09 15:08:12 +00005449
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005450 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005451 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005452 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005453 return;
Mike Stump11289f42009-09-09 15:08:12 +00005454
David Blaikie1f4ff152012-07-16 20:47:22 +00005455 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005456 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005457 return;
Mike Stump11289f42009-09-09 15:08:12 +00005458
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005459 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005460 Diag(Loc, diag::warn_floatingpoint_eq)
5461 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005462}
John McCallca01b222010-01-04 23:21:16 +00005463
John McCall70aa5392010-01-06 05:24:50 +00005464//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5465//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005466
John McCall70aa5392010-01-06 05:24:50 +00005467namespace {
John McCallca01b222010-01-04 23:21:16 +00005468
John McCall70aa5392010-01-06 05:24:50 +00005469/// Structure recording the 'active' range of an integer-valued
5470/// expression.
5471struct IntRange {
5472 /// The number of bits active in the int.
5473 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005474
John McCall70aa5392010-01-06 05:24:50 +00005475 /// True if the int is known not to have negative values.
5476 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005477
John McCall70aa5392010-01-06 05:24:50 +00005478 IntRange(unsigned Width, bool NonNegative)
5479 : Width(Width), NonNegative(NonNegative)
5480 {}
John McCallca01b222010-01-04 23:21:16 +00005481
John McCall817d4af2010-11-10 23:38:19 +00005482 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005483 static IntRange forBoolType() {
5484 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005485 }
5486
John McCall817d4af2010-11-10 23:38:19 +00005487 /// Returns the range of an opaque value of the given integral type.
5488 static IntRange forValueOfType(ASTContext &C, QualType T) {
5489 return forValueOfCanonicalType(C,
5490 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005491 }
5492
John McCall817d4af2010-11-10 23:38:19 +00005493 /// Returns the range of an opaque value of a canonical integral type.
5494 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005495 assert(T->isCanonicalUnqualified());
5496
5497 if (const VectorType *VT = dyn_cast<VectorType>(T))
5498 T = VT->getElementType().getTypePtr();
5499 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5500 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005501 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5502 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005503
David Majnemer6a426652013-06-07 22:07:20 +00005504 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005505 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005506 EnumDecl *Enum = ET->getDecl();
5507 if (!Enum->isCompleteDefinition())
5508 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005509
David Majnemer6a426652013-06-07 22:07:20 +00005510 unsigned NumPositive = Enum->getNumPositiveBits();
5511 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005512
David Majnemer6a426652013-06-07 22:07:20 +00005513 if (NumNegative == 0)
5514 return IntRange(NumPositive, true/*NonNegative*/);
5515 else
5516 return IntRange(std::max(NumPositive + 1, NumNegative),
5517 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005518 }
John McCall70aa5392010-01-06 05:24:50 +00005519
5520 const BuiltinType *BT = cast<BuiltinType>(T);
5521 assert(BT->isInteger());
5522
5523 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5524 }
5525
John McCall817d4af2010-11-10 23:38:19 +00005526 /// Returns the "target" range of a canonical integral type, i.e.
5527 /// the range of values expressible in the type.
5528 ///
5529 /// This matches forValueOfCanonicalType except that enums have the
5530 /// full range of their type, not the range of their enumerators.
5531 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5532 assert(T->isCanonicalUnqualified());
5533
5534 if (const VectorType *VT = dyn_cast<VectorType>(T))
5535 T = VT->getElementType().getTypePtr();
5536 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5537 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005538 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5539 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005540 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005541 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005542
5543 const BuiltinType *BT = cast<BuiltinType>(T);
5544 assert(BT->isInteger());
5545
5546 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5547 }
5548
5549 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005550 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005551 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005552 L.NonNegative && R.NonNegative);
5553 }
5554
John McCall817d4af2010-11-10 23:38:19 +00005555 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005556 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005557 return IntRange(std::min(L.Width, R.Width),
5558 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005559 }
5560};
5561
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005562static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5563 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005564 if (value.isSigned() && value.isNegative())
5565 return IntRange(value.getMinSignedBits(), false);
5566
5567 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005568 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005569
5570 // isNonNegative() just checks the sign bit without considering
5571 // signedness.
5572 return IntRange(value.getActiveBits(), true);
5573}
5574
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005575static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5576 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005577 if (result.isInt())
5578 return GetValueRange(C, result.getInt(), MaxWidth);
5579
5580 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005581 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5582 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5583 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5584 R = IntRange::join(R, El);
5585 }
John McCall70aa5392010-01-06 05:24:50 +00005586 return R;
5587 }
5588
5589 if (result.isComplexInt()) {
5590 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5591 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5592 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005593 }
5594
5595 // This can happen with lossless casts to intptr_t of "based" lvalues.
5596 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005597 // FIXME: The only reason we need to pass the type in here is to get
5598 // the sign right on this one case. It would be nice if APValue
5599 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005600 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005601 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005602}
John McCall70aa5392010-01-06 05:24:50 +00005603
Eli Friedmane6d33952013-07-08 20:20:06 +00005604static QualType GetExprType(Expr *E) {
5605 QualType Ty = E->getType();
5606 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5607 Ty = AtomicRHS->getValueType();
5608 return Ty;
5609}
5610
John McCall70aa5392010-01-06 05:24:50 +00005611/// Pseudo-evaluate the given integer expression, estimating the
5612/// range of values it might take.
5613///
5614/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005615static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005616 E = E->IgnoreParens();
5617
5618 // Try a full evaluation first.
5619 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005620 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005621 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005622
5623 // I think we only want to look through implicit casts here; if the
5624 // user has an explicit widening cast, we should treat the value as
5625 // being of the new, wider type.
5626 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005627 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005628 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5629
Eli Friedmane6d33952013-07-08 20:20:06 +00005630 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005631
John McCalle3027922010-08-25 11:45:40 +00005632 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005633
John McCall70aa5392010-01-06 05:24:50 +00005634 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005635 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005636 return OutputTypeRange;
5637
5638 IntRange SubRange
5639 = GetExprRange(C, CE->getSubExpr(),
5640 std::min(MaxWidth, OutputTypeRange.Width));
5641
5642 // Bail out if the subexpr's range is as wide as the cast type.
5643 if (SubRange.Width >= OutputTypeRange.Width)
5644 return OutputTypeRange;
5645
5646 // Otherwise, we take the smaller width, and we're non-negative if
5647 // either the output type or the subexpr is.
5648 return IntRange(SubRange.Width,
5649 SubRange.NonNegative || OutputTypeRange.NonNegative);
5650 }
5651
5652 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5653 // If we can fold the condition, just take that operand.
5654 bool CondResult;
5655 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5656 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5657 : CO->getFalseExpr(),
5658 MaxWidth);
5659
5660 // Otherwise, conservatively merge.
5661 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5662 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5663 return IntRange::join(L, R);
5664 }
5665
5666 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5667 switch (BO->getOpcode()) {
5668
5669 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005670 case BO_LAnd:
5671 case BO_LOr:
5672 case BO_LT:
5673 case BO_GT:
5674 case BO_LE:
5675 case BO_GE:
5676 case BO_EQ:
5677 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005678 return IntRange::forBoolType();
5679
John McCallc3688382011-07-13 06:35:24 +00005680 // The type of the assignments is the type of the LHS, so the RHS
5681 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005682 case BO_MulAssign:
5683 case BO_DivAssign:
5684 case BO_RemAssign:
5685 case BO_AddAssign:
5686 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005687 case BO_XorAssign:
5688 case BO_OrAssign:
5689 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005690 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005691
John McCallc3688382011-07-13 06:35:24 +00005692 // Simple assignments just pass through the RHS, which will have
5693 // been coerced to the LHS type.
5694 case BO_Assign:
5695 // TODO: bitfields?
5696 return GetExprRange(C, BO->getRHS(), MaxWidth);
5697
John McCall70aa5392010-01-06 05:24:50 +00005698 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005699 case BO_PtrMemD:
5700 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005701 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005702
John McCall2ce81ad2010-01-06 22:07:33 +00005703 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005704 case BO_And:
5705 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005706 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5707 GetExprRange(C, BO->getRHS(), MaxWidth));
5708
John McCall70aa5392010-01-06 05:24:50 +00005709 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005710 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005711 // ...except that we want to treat '1 << (blah)' as logically
5712 // positive. It's an important idiom.
5713 if (IntegerLiteral *I
5714 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5715 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005716 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005717 return IntRange(R.Width, /*NonNegative*/ true);
5718 }
5719 }
5720 // fallthrough
5721
John McCalle3027922010-08-25 11:45:40 +00005722 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005723 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005724
John McCall2ce81ad2010-01-06 22:07:33 +00005725 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005726 case BO_Shr:
5727 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005728 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5729
5730 // If the shift amount is a positive constant, drop the width by
5731 // that much.
5732 llvm::APSInt shift;
5733 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5734 shift.isNonNegative()) {
5735 unsigned zext = shift.getZExtValue();
5736 if (zext >= L.Width)
5737 L.Width = (L.NonNegative ? 0 : 1);
5738 else
5739 L.Width -= zext;
5740 }
5741
5742 return L;
5743 }
5744
5745 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005746 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005747 return GetExprRange(C, BO->getRHS(), MaxWidth);
5748
John McCall2ce81ad2010-01-06 22:07:33 +00005749 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005750 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005751 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005752 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005753 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005754
John McCall51431812011-07-14 22:39:48 +00005755 // The width of a division result is mostly determined by the size
5756 // of the LHS.
5757 case BO_Div: {
5758 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005759 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005760 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5761
5762 // If the divisor is constant, use that.
5763 llvm::APSInt divisor;
5764 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5765 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5766 if (log2 >= L.Width)
5767 L.Width = (L.NonNegative ? 0 : 1);
5768 else
5769 L.Width = std::min(L.Width - log2, MaxWidth);
5770 return L;
5771 }
5772
5773 // Otherwise, just use the LHS's width.
5774 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5775 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5776 }
5777
5778 // The result of a remainder can't be larger than the result of
5779 // either side.
5780 case BO_Rem: {
5781 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005782 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005783 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5784 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5785
5786 IntRange meet = IntRange::meet(L, R);
5787 meet.Width = std::min(meet.Width, MaxWidth);
5788 return meet;
5789 }
5790
5791 // The default behavior is okay for these.
5792 case BO_Mul:
5793 case BO_Add:
5794 case BO_Xor:
5795 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005796 break;
5797 }
5798
John McCall51431812011-07-14 22:39:48 +00005799 // The default case is to treat the operation as if it were closed
5800 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005801 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5802 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5803 return IntRange::join(L, R);
5804 }
5805
5806 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5807 switch (UO->getOpcode()) {
5808 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005809 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005810 return IntRange::forBoolType();
5811
5812 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005813 case UO_Deref:
5814 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005815 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005816
5817 default:
5818 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5819 }
5820 }
5821
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005822 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5823 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5824
John McCalld25db7e2013-05-06 21:39:12 +00005825 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005826 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005827 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005828
Eli Friedmane6d33952013-07-08 20:20:06 +00005829 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005830}
John McCall263a48b2010-01-04 23:31:57 +00005831
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005832static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005833 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005834}
5835
John McCall263a48b2010-01-04 23:31:57 +00005836/// Checks whether the given value, which currently has the given
5837/// source semantics, has the same value when coerced through the
5838/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005839static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5840 const llvm::fltSemantics &Src,
5841 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005842 llvm::APFloat truncated = value;
5843
5844 bool ignored;
5845 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5846 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5847
5848 return truncated.bitwiseIsEqual(value);
5849}
5850
5851/// Checks whether the given value, which currently has the given
5852/// source semantics, has the same value when coerced through the
5853/// target semantics.
5854///
5855/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005856static bool IsSameFloatAfterCast(const APValue &value,
5857 const llvm::fltSemantics &Src,
5858 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005859 if (value.isFloat())
5860 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5861
5862 if (value.isVector()) {
5863 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5864 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5865 return false;
5866 return true;
5867 }
5868
5869 assert(value.isComplexFloat());
5870 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5871 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5872}
5873
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005874static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005875
Ted Kremenek6274be42010-09-23 21:43:44 +00005876static bool IsZero(Sema &S, Expr *E) {
5877 // Suppress cases where we are comparing against an enum constant.
5878 if (const DeclRefExpr *DR =
5879 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5880 if (isa<EnumConstantDecl>(DR->getDecl()))
5881 return false;
5882
5883 // Suppress cases where the '0' value is expanded from a macro.
5884 if (E->getLocStart().isMacroID())
5885 return false;
5886
John McCallcc7e5bf2010-05-06 08:58:33 +00005887 llvm::APSInt Value;
5888 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5889}
5890
John McCall2551c1b2010-10-06 00:25:24 +00005891static bool HasEnumType(Expr *E) {
5892 // Strip off implicit integral promotions.
5893 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005894 if (ICE->getCastKind() != CK_IntegralCast &&
5895 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005896 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005897 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005898 }
5899
5900 return E->getType()->isEnumeralType();
5901}
5902
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005903static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005904 // Disable warning in template instantiations.
5905 if (!S.ActiveTemplateInstantiations.empty())
5906 return;
5907
John McCalle3027922010-08-25 11:45:40 +00005908 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005909 if (E->isValueDependent())
5910 return;
5911
John McCalle3027922010-08-25 11:45:40 +00005912 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005913 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005914 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005915 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005916 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005917 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005918 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005919 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005920 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005921 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005922 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005923 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005924 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005925 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005926 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005927 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5928 }
5929}
5930
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005931static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005932 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005933 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005934 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005935 // Disable warning in template instantiations.
5936 if (!S.ActiveTemplateInstantiations.empty())
5937 return;
5938
Richard Trieu0f097742014-04-04 04:13:47 +00005939 // TODO: Investigate using GetExprRange() to get tighter bounds
5940 // on the bit ranges.
5941 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005942 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5943 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005944 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5945 unsigned OtherWidth = OtherRange.Width;
5946
5947 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5948
Richard Trieu560910c2012-11-14 22:50:24 +00005949 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005950 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005951 return;
5952
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005953 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005954 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005955
Richard Trieu0f097742014-04-04 04:13:47 +00005956 // Used for diagnostic printout.
5957 enum {
5958 LiteralConstant = 0,
5959 CXXBoolLiteralTrue,
5960 CXXBoolLiteralFalse
5961 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005962
Richard Trieu0f097742014-04-04 04:13:47 +00005963 if (!OtherIsBooleanType) {
5964 QualType ConstantT = Constant->getType();
5965 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005966
Richard Trieu0f097742014-04-04 04:13:47 +00005967 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5968 return;
5969 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5970 "comparison with non-integer type");
5971
5972 bool ConstantSigned = ConstantT->isSignedIntegerType();
5973 bool CommonSigned = CommonT->isSignedIntegerType();
5974
5975 bool EqualityOnly = false;
5976
5977 if (CommonSigned) {
5978 // The common type is signed, therefore no signed to unsigned conversion.
5979 if (!OtherRange.NonNegative) {
5980 // Check that the constant is representable in type OtherT.
5981 if (ConstantSigned) {
5982 if (OtherWidth >= Value.getMinSignedBits())
5983 return;
5984 } else { // !ConstantSigned
5985 if (OtherWidth >= Value.getActiveBits() + 1)
5986 return;
5987 }
5988 } else { // !OtherSigned
5989 // Check that the constant is representable in type OtherT.
5990 // Negative values are out of range.
5991 if (ConstantSigned) {
5992 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5993 return;
5994 } else { // !ConstantSigned
5995 if (OtherWidth >= Value.getActiveBits())
5996 return;
5997 }
Richard Trieu560910c2012-11-14 22:50:24 +00005998 }
Richard Trieu0f097742014-04-04 04:13:47 +00005999 } else { // !CommonSigned
6000 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006001 if (OtherWidth >= Value.getActiveBits())
6002 return;
Craig Toppercf360162014-06-18 05:13:11 +00006003 } else { // OtherSigned
6004 assert(!ConstantSigned &&
6005 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006006 // Check to see if the constant is representable in OtherT.
6007 if (OtherWidth > Value.getActiveBits())
6008 return;
6009 // Check to see if the constant is equivalent to a negative value
6010 // cast to CommonT.
6011 if (S.Context.getIntWidth(ConstantT) ==
6012 S.Context.getIntWidth(CommonT) &&
6013 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6014 return;
6015 // The constant value rests between values that OtherT can represent
6016 // after conversion. Relational comparison still works, but equality
6017 // comparisons will be tautological.
6018 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006019 }
6020 }
Richard Trieu0f097742014-04-04 04:13:47 +00006021
6022 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6023
6024 if (op == BO_EQ || op == BO_NE) {
6025 IsTrue = op == BO_NE;
6026 } else if (EqualityOnly) {
6027 return;
6028 } else if (RhsConstant) {
6029 if (op == BO_GT || op == BO_GE)
6030 IsTrue = !PositiveConstant;
6031 else // op == BO_LT || op == BO_LE
6032 IsTrue = PositiveConstant;
6033 } else {
6034 if (op == BO_LT || op == BO_LE)
6035 IsTrue = !PositiveConstant;
6036 else // op == BO_GT || op == BO_GE
6037 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006038 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006039 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006040 // Other isKnownToHaveBooleanValue
6041 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6042 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6043 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6044
6045 static const struct LinkedConditions {
6046 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6047 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6048 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6049 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6050 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6051 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6052
6053 } TruthTable = {
6054 // Constant on LHS. | Constant on RHS. |
6055 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6056 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6057 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6058 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6059 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6060 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6061 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6062 };
6063
6064 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6065
6066 enum ConstantValue ConstVal = Zero;
6067 if (Value.isUnsigned() || Value.isNonNegative()) {
6068 if (Value == 0) {
6069 LiteralOrBoolConstant =
6070 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6071 ConstVal = Zero;
6072 } else if (Value == 1) {
6073 LiteralOrBoolConstant =
6074 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6075 ConstVal = One;
6076 } else {
6077 LiteralOrBoolConstant = LiteralConstant;
6078 ConstVal = GT_One;
6079 }
6080 } else {
6081 ConstVal = LT_Zero;
6082 }
6083
6084 CompareBoolWithConstantResult CmpRes;
6085
6086 switch (op) {
6087 case BO_LT:
6088 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6089 break;
6090 case BO_GT:
6091 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6092 break;
6093 case BO_LE:
6094 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6095 break;
6096 case BO_GE:
6097 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6098 break;
6099 case BO_EQ:
6100 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6101 break;
6102 case BO_NE:
6103 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6104 break;
6105 default:
6106 CmpRes = Unkwn;
6107 break;
6108 }
6109
6110 if (CmpRes == AFals) {
6111 IsTrue = false;
6112 } else if (CmpRes == ATrue) {
6113 IsTrue = true;
6114 } else {
6115 return;
6116 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006117 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006118
6119 // If this is a comparison to an enum constant, include that
6120 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006121 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006122 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6123 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6124
6125 SmallString<64> PrettySourceValue;
6126 llvm::raw_svector_ostream OS(PrettySourceValue);
6127 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006128 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006129 else
6130 OS << Value;
6131
Richard Trieu0f097742014-04-04 04:13:47 +00006132 S.DiagRuntimeBehavior(
6133 E->getOperatorLoc(), E,
6134 S.PDiag(diag::warn_out_of_range_compare)
6135 << OS.str() << LiteralOrBoolConstant
6136 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6137 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006138}
6139
John McCallcc7e5bf2010-05-06 08:58:33 +00006140/// Analyze the operands of the given comparison. Implements the
6141/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006142static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006143 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6144 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006145}
John McCall263a48b2010-01-04 23:31:57 +00006146
John McCallca01b222010-01-04 23:21:16 +00006147/// \brief Implements -Wsign-compare.
6148///
Richard Trieu82402a02011-09-15 21:56:47 +00006149/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006150static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006151 // The type the comparison is being performed in.
6152 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006153
6154 // Only analyze comparison operators where both sides have been converted to
6155 // the same type.
6156 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6157 return AnalyzeImpConvsInComparison(S, E);
6158
6159 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006160 if (E->isValueDependent())
6161 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006162
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006163 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6164 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006165
6166 bool IsComparisonConstant = false;
6167
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006168 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006169 // of 'true' or 'false'.
6170 if (T->isIntegralType(S.Context)) {
6171 llvm::APSInt RHSValue;
6172 bool IsRHSIntegralLiteral =
6173 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6174 llvm::APSInt LHSValue;
6175 bool IsLHSIntegralLiteral =
6176 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6177 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6178 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6179 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6180 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6181 else
6182 IsComparisonConstant =
6183 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006184 } else if (!T->hasUnsignedIntegerRepresentation())
6185 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006186
John McCallcc7e5bf2010-05-06 08:58:33 +00006187 // We don't do anything special if this isn't an unsigned integral
6188 // comparison: we're only interested in integral comparisons, and
6189 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006190 //
6191 // We also don't care about value-dependent expressions or expressions
6192 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006193 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006194 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006195
John McCallcc7e5bf2010-05-06 08:58:33 +00006196 // Check to see if one of the (unmodified) operands is of different
6197 // signedness.
6198 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006199 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6200 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006201 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006202 signedOperand = LHS;
6203 unsignedOperand = RHS;
6204 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6205 signedOperand = RHS;
6206 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006207 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006208 CheckTrivialUnsignedComparison(S, E);
6209 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006210 }
6211
John McCallcc7e5bf2010-05-06 08:58:33 +00006212 // Otherwise, calculate the effective range of the signed operand.
6213 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006214
John McCallcc7e5bf2010-05-06 08:58:33 +00006215 // Go ahead and analyze implicit conversions in the operands. Note
6216 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006217 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6218 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006219
John McCallcc7e5bf2010-05-06 08:58:33 +00006220 // If the signed range is non-negative, -Wsign-compare won't fire,
6221 // but we should still check for comparisons which are always true
6222 // or false.
6223 if (signedRange.NonNegative)
6224 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006225
6226 // For (in)equality comparisons, if the unsigned operand is a
6227 // constant which cannot collide with a overflowed signed operand,
6228 // then reinterpreting the signed operand as unsigned will not
6229 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006230 if (E->isEqualityOp()) {
6231 unsigned comparisonWidth = S.Context.getIntWidth(T);
6232 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006233
John McCallcc7e5bf2010-05-06 08:58:33 +00006234 // We should never be unable to prove that the unsigned operand is
6235 // non-negative.
6236 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6237
6238 if (unsignedRange.Width < comparisonWidth)
6239 return;
6240 }
6241
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006242 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6243 S.PDiag(diag::warn_mixed_sign_comparison)
6244 << LHS->getType() << RHS->getType()
6245 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006246}
6247
John McCall1f425642010-11-11 03:21:53 +00006248/// Analyzes an attempt to assign the given value to a bitfield.
6249///
6250/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006251static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6252 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006253 assert(Bitfield->isBitField());
6254 if (Bitfield->isInvalidDecl())
6255 return false;
6256
John McCalldeebbcf2010-11-11 05:33:51 +00006257 // White-list bool bitfields.
6258 if (Bitfield->getType()->isBooleanType())
6259 return false;
6260
Douglas Gregor789adec2011-02-04 13:09:01 +00006261 // Ignore value- or type-dependent expressions.
6262 if (Bitfield->getBitWidth()->isValueDependent() ||
6263 Bitfield->getBitWidth()->isTypeDependent() ||
6264 Init->isValueDependent() ||
6265 Init->isTypeDependent())
6266 return false;
6267
John McCall1f425642010-11-11 03:21:53 +00006268 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6269
Richard Smith5fab0c92011-12-28 19:48:30 +00006270 llvm::APSInt Value;
6271 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006272 return false;
6273
John McCall1f425642010-11-11 03:21:53 +00006274 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006275 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006276
6277 if (OriginalWidth <= FieldWidth)
6278 return false;
6279
Eli Friedmanc267a322012-01-26 23:11:39 +00006280 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006281 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006282 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006283
Eli Friedmanc267a322012-01-26 23:11:39 +00006284 // Check whether the stored value is equal to the original value.
6285 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006286 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006287 return false;
6288
Eli Friedmanc267a322012-01-26 23:11:39 +00006289 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006290 // therefore don't strictly fit into a signed bitfield of width 1.
6291 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006292 return false;
6293
John McCall1f425642010-11-11 03:21:53 +00006294 std::string PrettyValue = Value.toString(10);
6295 std::string PrettyTrunc = TruncatedValue.toString(10);
6296
6297 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6298 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6299 << Init->getSourceRange();
6300
6301 return true;
6302}
6303
John McCalld2a53122010-11-09 23:24:47 +00006304/// Analyze the given simple or compound assignment for warning-worthy
6305/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006306static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006307 // Just recurse on the LHS.
6308 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6309
6310 // We want to recurse on the RHS as normal unless we're assigning to
6311 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006312 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006313 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006314 E->getOperatorLoc())) {
6315 // Recurse, ignoring any implicit conversions on the RHS.
6316 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6317 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006318 }
6319 }
6320
6321 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6322}
6323
John McCall263a48b2010-01-04 23:31:57 +00006324/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006325static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006326 SourceLocation CContext, unsigned diag,
6327 bool pruneControlFlow = false) {
6328 if (pruneControlFlow) {
6329 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6330 S.PDiag(diag)
6331 << SourceType << T << E->getSourceRange()
6332 << SourceRange(CContext));
6333 return;
6334 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006335 S.Diag(E->getExprLoc(), diag)
6336 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6337}
6338
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006339/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006340static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006341 SourceLocation CContext, unsigned diag,
6342 bool pruneControlFlow = false) {
6343 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006344}
6345
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006346/// Diagnose an implicit cast from a literal expression. Does not warn when the
6347/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006348void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6349 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006350 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006351 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006352 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006353 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6354 T->hasUnsignedIntegerRepresentation());
6355 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006356 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006357 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006358 return;
6359
Eli Friedman07185912013-08-29 23:44:43 +00006360 // FIXME: Force the precision of the source value down so we don't print
6361 // digits which are usually useless (we don't really care here if we
6362 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6363 // would automatically print the shortest representation, but it's a bit
6364 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006365 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006366 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6367 precision = (precision * 59 + 195) / 196;
6368 Value.toString(PrettySourceValue, precision);
6369
David Blaikie9b88cc02012-05-15 17:18:27 +00006370 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006371 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6372 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6373 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006374 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006375
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006376 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006377 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6378 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006379}
6380
John McCall18a2c2c2010-11-09 22:22:12 +00006381std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6382 if (!Range.Width) return "0";
6383
6384 llvm::APSInt ValueInRange = Value;
6385 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006386 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006387 return ValueInRange.toString(10);
6388}
6389
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006390static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6391 if (!isa<ImplicitCastExpr>(Ex))
6392 return false;
6393
6394 Expr *InnerE = Ex->IgnoreParenImpCasts();
6395 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6396 const Type *Source =
6397 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6398 if (Target->isDependentType())
6399 return false;
6400
6401 const BuiltinType *FloatCandidateBT =
6402 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6403 const Type *BoolCandidateType = ToBool ? Target : Source;
6404
6405 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6406 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6407}
6408
6409void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6410 SourceLocation CC) {
6411 unsigned NumArgs = TheCall->getNumArgs();
6412 for (unsigned i = 0; i < NumArgs; ++i) {
6413 Expr *CurrA = TheCall->getArg(i);
6414 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6415 continue;
6416
6417 bool IsSwapped = ((i > 0) &&
6418 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6419 IsSwapped |= ((i < (NumArgs - 1)) &&
6420 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6421 if (IsSwapped) {
6422 // Warn on this floating-point to bool conversion.
6423 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6424 CurrA->getType(), CC,
6425 diag::warn_impcast_floating_point_to_bool);
6426 }
6427 }
6428}
6429
Richard Trieu5b993502014-10-15 03:42:06 +00006430static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6431 SourceLocation CC) {
6432 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6433 E->getExprLoc()))
6434 return;
6435
6436 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6437 const Expr::NullPointerConstantKind NullKind =
6438 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6439 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6440 return;
6441
6442 // Return if target type is a safe conversion.
6443 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6444 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6445 return;
6446
6447 SourceLocation Loc = E->getSourceRange().getBegin();
6448
6449 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6450 if (NullKind == Expr::NPCK_GNUNull) {
6451 if (Loc.isMacroID())
6452 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6453 }
6454
6455 // Only warn if the null and context location are in the same macro expansion.
6456 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6457 return;
6458
6459 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6460 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6461 << FixItHint::CreateReplacement(Loc,
6462 S.getFixItZeroLiteralForType(T, Loc));
6463}
6464
John McCallcc7e5bf2010-05-06 08:58:33 +00006465void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006466 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006467 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006468
John McCallcc7e5bf2010-05-06 08:58:33 +00006469 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6470 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6471 if (Source == Target) return;
6472 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006473
Chandler Carruthc22845a2011-07-26 05:40:03 +00006474 // If the conversion context location is invalid don't complain. We also
6475 // don't want to emit a warning if the issue occurs from the expansion of
6476 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6477 // delay this check as long as possible. Once we detect we are in that
6478 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006479 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006480 return;
6481
Richard Trieu021baa32011-09-23 20:10:00 +00006482 // Diagnose implicit casts to bool.
6483 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6484 if (isa<StringLiteral>(E))
6485 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006486 // and expressions, for instance, assert(0 && "error here"), are
6487 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006488 return DiagnoseImpCast(S, E, T, CC,
6489 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006490 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6491 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6492 // This covers the literal expressions that evaluate to Objective-C
6493 // objects.
6494 return DiagnoseImpCast(S, E, T, CC,
6495 diag::warn_impcast_objective_c_literal_to_bool);
6496 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006497 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6498 // Warn on pointer to bool conversion that is always true.
6499 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6500 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006501 }
Richard Trieu021baa32011-09-23 20:10:00 +00006502 }
John McCall263a48b2010-01-04 23:31:57 +00006503
6504 // Strip vector types.
6505 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006506 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006507 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006508 return;
John McCallacf0ee52010-10-08 02:01:28 +00006509 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006510 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006511
6512 // If the vector cast is cast between two vectors of the same size, it is
6513 // a bitcast, not a conversion.
6514 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6515 return;
John McCall263a48b2010-01-04 23:31:57 +00006516
6517 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6518 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6519 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006520 if (auto VecTy = dyn_cast<VectorType>(Target))
6521 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006522
6523 // Strip complex types.
6524 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006525 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006526 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006527 return;
6528
John McCallacf0ee52010-10-08 02:01:28 +00006529 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006530 }
John McCall263a48b2010-01-04 23:31:57 +00006531
6532 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6533 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6534 }
6535
6536 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6537 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6538
6539 // If the source is floating point...
6540 if (SourceBT && SourceBT->isFloatingPoint()) {
6541 // ...and the target is floating point...
6542 if (TargetBT && TargetBT->isFloatingPoint()) {
6543 // ...then warn if we're dropping FP rank.
6544
6545 // Builtin FP kinds are ordered by increasing FP rank.
6546 if (SourceBT->getKind() > TargetBT->getKind()) {
6547 // Don't warn about float constants that are precisely
6548 // representable in the target type.
6549 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006550 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006551 // Value might be a float, a float vector, or a float complex.
6552 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006553 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6554 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006555 return;
6556 }
6557
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006558 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006559 return;
6560
John McCallacf0ee52010-10-08 02:01:28 +00006561 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006562 }
6563 return;
6564 }
6565
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006566 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006567 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006568 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006569 return;
6570
Chandler Carruth22c7a792011-02-17 11:05:49 +00006571 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006572 // We also want to warn on, e.g., "int i = -1.234"
6573 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6574 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6575 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6576
Chandler Carruth016ef402011-04-10 08:36:24 +00006577 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6578 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006579 } else {
6580 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6581 }
6582 }
John McCall263a48b2010-01-04 23:31:57 +00006583
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006584 // If the target is bool, warn if expr is a function or method call.
6585 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6586 isa<CallExpr>(E)) {
6587 // Check last argument of function call to see if it is an
6588 // implicit cast from a type matching the type the result
6589 // is being cast to.
6590 CallExpr *CEx = cast<CallExpr>(E);
6591 unsigned NumArgs = CEx->getNumArgs();
6592 if (NumArgs > 0) {
6593 Expr *LastA = CEx->getArg(NumArgs - 1);
6594 Expr *InnerE = LastA->IgnoreParenImpCasts();
6595 const Type *InnerType =
6596 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6597 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6598 // Warn on this floating-point to bool conversion
6599 DiagnoseImpCast(S, E, T, CC,
6600 diag::warn_impcast_floating_point_to_bool);
6601 }
6602 }
6603 }
John McCall263a48b2010-01-04 23:31:57 +00006604 return;
6605 }
6606
Richard Trieu5b993502014-10-15 03:42:06 +00006607 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006608
David Blaikie9366d2b2012-06-19 21:19:06 +00006609 if (!Source->isIntegerType() || !Target->isIntegerType())
6610 return;
6611
David Blaikie7555b6a2012-05-15 16:56:36 +00006612 // TODO: remove this early return once the false positives for constant->bool
6613 // in templates, macros, etc, are reduced or removed.
6614 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6615 return;
6616
John McCallcc7e5bf2010-05-06 08:58:33 +00006617 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006618 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006619
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006620 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006621 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006622 // TODO: this should happen for bitfield stores, too.
6623 llvm::APSInt Value(32);
6624 if (E->isIntegerConstantExpr(Value, S.Context)) {
6625 if (S.SourceMgr.isInSystemMacro(CC))
6626 return;
6627
John McCall18a2c2c2010-11-09 22:22:12 +00006628 std::string PrettySourceValue = Value.toString(10);
6629 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006630
Ted Kremenek33ba9952011-10-22 02:37:33 +00006631 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6632 S.PDiag(diag::warn_impcast_integer_precision_constant)
6633 << PrettySourceValue << PrettyTargetValue
6634 << E->getType() << T << E->getSourceRange()
6635 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006636 return;
6637 }
6638
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006639 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6640 if (S.SourceMgr.isInSystemMacro(CC))
6641 return;
6642
David Blaikie9455da02012-04-12 22:40:54 +00006643 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006644 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6645 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006646 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006647 }
6648
6649 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6650 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6651 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006652
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006653 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006654 return;
6655
John McCallcc7e5bf2010-05-06 08:58:33 +00006656 unsigned DiagID = diag::warn_impcast_integer_sign;
6657
6658 // Traditionally, gcc has warned about this under -Wsign-compare.
6659 // We also want to warn about it in -Wconversion.
6660 // So if -Wconversion is off, use a completely identical diagnostic
6661 // in the sign-compare group.
6662 // The conditional-checking code will
6663 if (ICContext) {
6664 DiagID = diag::warn_impcast_integer_sign_conditional;
6665 *ICContext = true;
6666 }
6667
John McCallacf0ee52010-10-08 02:01:28 +00006668 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006669 }
6670
Douglas Gregora78f1932011-02-22 02:45:07 +00006671 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006672 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6673 // type, to give us better diagnostics.
6674 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006675 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006676 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6677 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6678 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6679 SourceType = S.Context.getTypeDeclType(Enum);
6680 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6681 }
6682 }
6683
Douglas Gregora78f1932011-02-22 02:45:07 +00006684 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6685 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006686 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6687 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006688 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006689 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006690 return;
6691
Douglas Gregor364f7db2011-03-12 00:14:31 +00006692 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006693 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006694 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006695
John McCall263a48b2010-01-04 23:31:57 +00006696 return;
6697}
6698
David Blaikie18e9ac72012-05-15 21:57:38 +00006699void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6700 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006701
6702void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006703 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006704 E = E->IgnoreParenImpCasts();
6705
6706 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006707 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006708
John McCallacf0ee52010-10-08 02:01:28 +00006709 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006710 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006711 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006712 return;
6713}
6714
David Blaikie18e9ac72012-05-15 21:57:38 +00006715void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6716 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006717 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006718
6719 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006720 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6721 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006722
6723 // If -Wconversion would have warned about either of the candidates
6724 // for a signedness conversion to the context type...
6725 if (!Suspicious) return;
6726
6727 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006728 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006729 return;
6730
John McCallcc7e5bf2010-05-06 08:58:33 +00006731 // ...then check whether it would have warned about either of the
6732 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006733 if (E->getType() == T) return;
6734
6735 Suspicious = false;
6736 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6737 E->getType(), CC, &Suspicious);
6738 if (!Suspicious)
6739 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006740 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006741}
6742
Richard Trieu65724892014-11-15 06:37:39 +00006743/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6744/// Input argument E is a logical expression.
6745static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6746 if (S.getLangOpts().Bool)
6747 return;
6748 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6749}
6750
John McCallcc7e5bf2010-05-06 08:58:33 +00006751/// AnalyzeImplicitConversions - Find and report any interesting
6752/// implicit conversions in the given expression. There are a couple
6753/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006754void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006755 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006756 Expr *E = OrigE->IgnoreParenImpCasts();
6757
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006758 if (E->isTypeDependent() || E->isValueDependent())
6759 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006760
John McCallcc7e5bf2010-05-06 08:58:33 +00006761 // For conditional operators, we analyze the arguments as if they
6762 // were being fed directly into the output.
6763 if (isa<ConditionalOperator>(E)) {
6764 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006765 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006766 return;
6767 }
6768
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006769 // Check implicit argument conversions for function calls.
6770 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6771 CheckImplicitArgumentConversions(S, Call, CC);
6772
John McCallcc7e5bf2010-05-06 08:58:33 +00006773 // Go ahead and check any implicit conversions we might have skipped.
6774 // The non-canonical typecheck is just an optimization;
6775 // CheckImplicitConversion will filter out dead implicit conversions.
6776 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006777 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006778
6779 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006780
6781 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006782 if (POE->getResultExpr())
6783 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006784 }
6785
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006786 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6787 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6788
John McCallcc7e5bf2010-05-06 08:58:33 +00006789 // Skip past explicit casts.
6790 if (isa<ExplicitCastExpr>(E)) {
6791 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006792 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006793 }
6794
John McCalld2a53122010-11-09 23:24:47 +00006795 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6796 // Do a somewhat different check with comparison operators.
6797 if (BO->isComparisonOp())
6798 return AnalyzeComparison(S, BO);
6799
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006800 // And with simple assignments.
6801 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006802 return AnalyzeAssignment(S, BO);
6803 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006804
6805 // These break the otherwise-useful invariant below. Fortunately,
6806 // we don't really need to recurse into them, because any internal
6807 // expressions should have been analyzed already when they were
6808 // built into statements.
6809 if (isa<StmtExpr>(E)) return;
6810
6811 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006812 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006813
6814 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006815 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006816 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006817 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006818 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006819 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006820 if (!ChildExpr)
6821 continue;
6822
Richard Trieu955231d2014-01-25 01:10:35 +00006823 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006824 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006825 // Ignore checking string literals that are in logical and operators.
6826 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006827 continue;
6828 AnalyzeImplicitConversions(S, ChildExpr, CC);
6829 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006830
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006831 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006832 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6833 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006834 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00006835
6836 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6837 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006838 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006839 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006840
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006841 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6842 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00006843 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006844}
6845
6846} // end anonymous namespace
6847
Richard Trieu3bb8b562014-02-26 02:36:06 +00006848enum {
6849 AddressOf,
6850 FunctionPointer,
6851 ArrayPointer
6852};
6853
Richard Trieuc1888e02014-06-28 23:25:37 +00006854// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6855// Returns true when emitting a warning about taking the address of a reference.
6856static bool CheckForReference(Sema &SemaRef, const Expr *E,
6857 PartialDiagnostic PD) {
6858 E = E->IgnoreParenImpCasts();
6859
6860 const FunctionDecl *FD = nullptr;
6861
6862 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6863 if (!DRE->getDecl()->getType()->isReferenceType())
6864 return false;
6865 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6866 if (!M->getMemberDecl()->getType()->isReferenceType())
6867 return false;
6868 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6869 if (!Call->getCallReturnType()->isReferenceType())
6870 return false;
6871 FD = Call->getDirectCallee();
6872 } else {
6873 return false;
6874 }
6875
6876 SemaRef.Diag(E->getExprLoc(), PD);
6877
6878 // If possible, point to location of function.
6879 if (FD) {
6880 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6881 }
6882
6883 return true;
6884}
6885
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006886// Returns true if the SourceLocation is expanded from any macro body.
6887// Returns false if the SourceLocation is invalid, is from not in a macro
6888// expansion, or is from expanded from a top-level macro argument.
6889static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6890 if (Loc.isInvalid())
6891 return false;
6892
6893 while (Loc.isMacroID()) {
6894 if (SM.isMacroBodyExpansion(Loc))
6895 return true;
6896 Loc = SM.getImmediateMacroCallerLoc(Loc);
6897 }
6898
6899 return false;
6900}
6901
Richard Trieu3bb8b562014-02-26 02:36:06 +00006902/// \brief Diagnose pointers that are always non-null.
6903/// \param E the expression containing the pointer
6904/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6905/// compared to a null pointer
6906/// \param IsEqual True when the comparison is equal to a null pointer
6907/// \param Range Extra SourceRange to highlight in the diagnostic
6908void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6909 Expr::NullPointerConstantKind NullKind,
6910 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006911 if (!E)
6912 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006913
6914 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006915 if (E->getExprLoc().isMacroID()) {
6916 const SourceManager &SM = getSourceManager();
6917 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6918 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006919 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006920 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006921 E = E->IgnoreImpCasts();
6922
6923 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6924
Richard Trieuf7432752014-06-06 21:39:26 +00006925 if (isa<CXXThisExpr>(E)) {
6926 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6927 : diag::warn_this_bool_conversion;
6928 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6929 return;
6930 }
6931
Richard Trieu3bb8b562014-02-26 02:36:06 +00006932 bool IsAddressOf = false;
6933
6934 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6935 if (UO->getOpcode() != UO_AddrOf)
6936 return;
6937 IsAddressOf = true;
6938 E = UO->getSubExpr();
6939 }
6940
Richard Trieuc1888e02014-06-28 23:25:37 +00006941 if (IsAddressOf) {
6942 unsigned DiagID = IsCompare
6943 ? diag::warn_address_of_reference_null_compare
6944 : diag::warn_address_of_reference_bool_conversion;
6945 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6946 << IsEqual;
6947 if (CheckForReference(*this, E, PD)) {
6948 return;
6949 }
6950 }
6951
Richard Trieu3bb8b562014-02-26 02:36:06 +00006952 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006953 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006954 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6955 D = R->getDecl();
6956 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6957 D = M->getMemberDecl();
6958 }
6959
6960 // Weak Decls can be null.
6961 if (!D || D->isWeak())
6962 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006963
6964 // Check for parameter decl with nonnull attribute
6965 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6966 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6967 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6968 unsigned NumArgs = FD->getNumParams();
6969 llvm::SmallBitVector AttrNonNull(NumArgs);
6970 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6971 if (!NonNull->args_size()) {
6972 AttrNonNull.set(0, NumArgs);
6973 break;
6974 }
6975 for (unsigned Val : NonNull->args()) {
6976 if (Val >= NumArgs)
6977 continue;
6978 AttrNonNull.set(Val);
6979 }
6980 }
6981 if (!AttrNonNull.empty())
6982 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00006983 if (FD->getParamDecl(i) == PV &&
6984 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006985 std::string Str;
6986 llvm::raw_string_ostream S(Str);
6987 E->printPretty(S, nullptr, getPrintingPolicy());
6988 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
6989 : diag::warn_cast_nonnull_to_bool;
6990 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
6991 << Range << IsEqual;
6992 return;
6993 }
6994 }
6995 }
6996
Richard Trieu3bb8b562014-02-26 02:36:06 +00006997 QualType T = D->getType();
6998 const bool IsArray = T->isArrayType();
6999 const bool IsFunction = T->isFunctionType();
7000
Richard Trieuc1888e02014-06-28 23:25:37 +00007001 // Address of function is used to silence the function warning.
7002 if (IsAddressOf && IsFunction) {
7003 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007004 }
7005
7006 // Found nothing.
7007 if (!IsAddressOf && !IsFunction && !IsArray)
7008 return;
7009
7010 // Pretty print the expression for the diagnostic.
7011 std::string Str;
7012 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007013 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007014
7015 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7016 : diag::warn_impcast_pointer_to_bool;
7017 unsigned DiagType;
7018 if (IsAddressOf)
7019 DiagType = AddressOf;
7020 else if (IsFunction)
7021 DiagType = FunctionPointer;
7022 else if (IsArray)
7023 DiagType = ArrayPointer;
7024 else
7025 llvm_unreachable("Could not determine diagnostic.");
7026 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7027 << Range << IsEqual;
7028
7029 if (!IsFunction)
7030 return;
7031
7032 // Suggest '&' to silence the function warning.
7033 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7034 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7035
7036 // Check to see if '()' fixit should be emitted.
7037 QualType ReturnType;
7038 UnresolvedSet<4> NonTemplateOverloads;
7039 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7040 if (ReturnType.isNull())
7041 return;
7042
7043 if (IsCompare) {
7044 // There are two cases here. If there is null constant, the only suggest
7045 // for a pointer return type. If the null is 0, then suggest if the return
7046 // type is a pointer or an integer type.
7047 if (!ReturnType->isPointerType()) {
7048 if (NullKind == Expr::NPCK_ZeroExpression ||
7049 NullKind == Expr::NPCK_ZeroLiteral) {
7050 if (!ReturnType->isIntegerType())
7051 return;
7052 } else {
7053 return;
7054 }
7055 }
7056 } else { // !IsCompare
7057 // For function to bool, only suggest if the function pointer has bool
7058 // return type.
7059 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7060 return;
7061 }
7062 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007063 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007064}
7065
7066
John McCallcc7e5bf2010-05-06 08:58:33 +00007067/// Diagnoses "dangerous" implicit conversions within the given
7068/// expression (which is a full expression). Implements -Wconversion
7069/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007070///
7071/// \param CC the "context" location of the implicit conversion, i.e.
7072/// the most location of the syntactic entity requiring the implicit
7073/// conversion
7074void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007075 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007076 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007077 return;
7078
7079 // Don't diagnose for value- or type-dependent expressions.
7080 if (E->isTypeDependent() || E->isValueDependent())
7081 return;
7082
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007083 // Check for array bounds violations in cases where the check isn't triggered
7084 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7085 // ArraySubscriptExpr is on the RHS of a variable initialization.
7086 CheckArrayAccess(E);
7087
John McCallacf0ee52010-10-08 02:01:28 +00007088 // This is not the right CC for (e.g.) a variable initialization.
7089 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007090}
7091
Richard Trieu65724892014-11-15 06:37:39 +00007092/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7093/// Input argument E is a logical expression.
7094void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7095 ::CheckBoolLikeConversion(*this, E, CC);
7096}
7097
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007098/// Diagnose when expression is an integer constant expression and its evaluation
7099/// results in integer overflow
7100void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007101 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7102 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007103}
7104
Richard Smithc406cb72013-01-17 01:17:56 +00007105namespace {
7106/// \brief Visitor for expressions which looks for unsequenced operations on the
7107/// same object.
7108class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007109 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7110
Richard Smithc406cb72013-01-17 01:17:56 +00007111 /// \brief A tree of sequenced regions within an expression. Two regions are
7112 /// unsequenced if one is an ancestor or a descendent of the other. When we
7113 /// finish processing an expression with sequencing, such as a comma
7114 /// expression, we fold its tree nodes into its parent, since they are
7115 /// unsequenced with respect to nodes we will visit later.
7116 class SequenceTree {
7117 struct Value {
7118 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7119 unsigned Parent : 31;
7120 bool Merged : 1;
7121 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007122 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007123
7124 public:
7125 /// \brief A region within an expression which may be sequenced with respect
7126 /// to some other region.
7127 class Seq {
7128 explicit Seq(unsigned N) : Index(N) {}
7129 unsigned Index;
7130 friend class SequenceTree;
7131 public:
7132 Seq() : Index(0) {}
7133 };
7134
7135 SequenceTree() { Values.push_back(Value(0)); }
7136 Seq root() const { return Seq(0); }
7137
7138 /// \brief Create a new sequence of operations, which is an unsequenced
7139 /// subset of \p Parent. This sequence of operations is sequenced with
7140 /// respect to other children of \p Parent.
7141 Seq allocate(Seq Parent) {
7142 Values.push_back(Value(Parent.Index));
7143 return Seq(Values.size() - 1);
7144 }
7145
7146 /// \brief Merge a sequence of operations into its parent.
7147 void merge(Seq S) {
7148 Values[S.Index].Merged = true;
7149 }
7150
7151 /// \brief Determine whether two operations are unsequenced. This operation
7152 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7153 /// should have been merged into its parent as appropriate.
7154 bool isUnsequenced(Seq Cur, Seq Old) {
7155 unsigned C = representative(Cur.Index);
7156 unsigned Target = representative(Old.Index);
7157 while (C >= Target) {
7158 if (C == Target)
7159 return true;
7160 C = Values[C].Parent;
7161 }
7162 return false;
7163 }
7164
7165 private:
7166 /// \brief Pick a representative for a sequence.
7167 unsigned representative(unsigned K) {
7168 if (Values[K].Merged)
7169 // Perform path compression as we go.
7170 return Values[K].Parent = representative(Values[K].Parent);
7171 return K;
7172 }
7173 };
7174
7175 /// An object for which we can track unsequenced uses.
7176 typedef NamedDecl *Object;
7177
7178 /// Different flavors of object usage which we track. We only track the
7179 /// least-sequenced usage of each kind.
7180 enum UsageKind {
7181 /// A read of an object. Multiple unsequenced reads are OK.
7182 UK_Use,
7183 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007184 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007185 UK_ModAsValue,
7186 /// A modification of an object which is not sequenced before the value
7187 /// computation of the expression, such as n++.
7188 UK_ModAsSideEffect,
7189
7190 UK_Count = UK_ModAsSideEffect + 1
7191 };
7192
7193 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007194 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007195 Expr *Use;
7196 SequenceTree::Seq Seq;
7197 };
7198
7199 struct UsageInfo {
7200 UsageInfo() : Diagnosed(false) {}
7201 Usage Uses[UK_Count];
7202 /// Have we issued a diagnostic for this variable already?
7203 bool Diagnosed;
7204 };
7205 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7206
7207 Sema &SemaRef;
7208 /// Sequenced regions within the expression.
7209 SequenceTree Tree;
7210 /// Declaration modifications and references which we have seen.
7211 UsageInfoMap UsageMap;
7212 /// The region we are currently within.
7213 SequenceTree::Seq Region;
7214 /// Filled in with declarations which were modified as a side-effect
7215 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007216 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007217 /// Expressions to check later. We defer checking these to reduce
7218 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007219 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007220
7221 /// RAII object wrapping the visitation of a sequenced subexpression of an
7222 /// expression. At the end of this process, the side-effects of the evaluation
7223 /// become sequenced with respect to the value computation of the result, so
7224 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7225 /// UK_ModAsValue.
7226 struct SequencedSubexpression {
7227 SequencedSubexpression(SequenceChecker &Self)
7228 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7229 Self.ModAsSideEffect = &ModAsSideEffect;
7230 }
7231 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007232 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7233 MI != ME; ++MI) {
7234 UsageInfo &U = Self.UsageMap[MI->first];
7235 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7236 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7237 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007238 }
7239 Self.ModAsSideEffect = OldModAsSideEffect;
7240 }
7241
7242 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007243 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7244 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007245 };
7246
Richard Smith40238f02013-06-20 22:21:56 +00007247 /// RAII object wrapping the visitation of a subexpression which we might
7248 /// choose to evaluate as a constant. If any subexpression is evaluated and
7249 /// found to be non-constant, this allows us to suppress the evaluation of
7250 /// the outer expression.
7251 class EvaluationTracker {
7252 public:
7253 EvaluationTracker(SequenceChecker &Self)
7254 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7255 Self.EvalTracker = this;
7256 }
7257 ~EvaluationTracker() {
7258 Self.EvalTracker = Prev;
7259 if (Prev)
7260 Prev->EvalOK &= EvalOK;
7261 }
7262
7263 bool evaluate(const Expr *E, bool &Result) {
7264 if (!EvalOK || E->isValueDependent())
7265 return false;
7266 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7267 return EvalOK;
7268 }
7269
7270 private:
7271 SequenceChecker &Self;
7272 EvaluationTracker *Prev;
7273 bool EvalOK;
7274 } *EvalTracker;
7275
Richard Smithc406cb72013-01-17 01:17:56 +00007276 /// \brief Find the object which is produced by the specified expression,
7277 /// if any.
7278 Object getObject(Expr *E, bool Mod) const {
7279 E = E->IgnoreParenCasts();
7280 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7281 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7282 return getObject(UO->getSubExpr(), Mod);
7283 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7284 if (BO->getOpcode() == BO_Comma)
7285 return getObject(BO->getRHS(), Mod);
7286 if (Mod && BO->isAssignmentOp())
7287 return getObject(BO->getLHS(), Mod);
7288 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7289 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7290 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7291 return ME->getMemberDecl();
7292 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7293 // FIXME: If this is a reference, map through to its value.
7294 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007295 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007296 }
7297
7298 /// \brief Note that an object was modified or used by an expression.
7299 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7300 Usage &U = UI.Uses[UK];
7301 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7302 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7303 ModAsSideEffect->push_back(std::make_pair(O, U));
7304 U.Use = Ref;
7305 U.Seq = Region;
7306 }
7307 }
7308 /// \brief Check whether a modification or use conflicts with a prior usage.
7309 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7310 bool IsModMod) {
7311 if (UI.Diagnosed)
7312 return;
7313
7314 const Usage &U = UI.Uses[OtherKind];
7315 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7316 return;
7317
7318 Expr *Mod = U.Use;
7319 Expr *ModOrUse = Ref;
7320 if (OtherKind == UK_Use)
7321 std::swap(Mod, ModOrUse);
7322
7323 SemaRef.Diag(Mod->getExprLoc(),
7324 IsModMod ? diag::warn_unsequenced_mod_mod
7325 : diag::warn_unsequenced_mod_use)
7326 << O << SourceRange(ModOrUse->getExprLoc());
7327 UI.Diagnosed = true;
7328 }
7329
7330 void notePreUse(Object O, Expr *Use) {
7331 UsageInfo &U = UsageMap[O];
7332 // Uses conflict with other modifications.
7333 checkUsage(O, U, Use, UK_ModAsValue, false);
7334 }
7335 void notePostUse(Object O, Expr *Use) {
7336 UsageInfo &U = UsageMap[O];
7337 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7338 addUsage(U, O, Use, UK_Use);
7339 }
7340
7341 void notePreMod(Object O, Expr *Mod) {
7342 UsageInfo &U = UsageMap[O];
7343 // Modifications conflict with other modifications and with uses.
7344 checkUsage(O, U, Mod, UK_ModAsValue, true);
7345 checkUsage(O, U, Mod, UK_Use, false);
7346 }
7347 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7348 UsageInfo &U = UsageMap[O];
7349 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7350 addUsage(U, O, Use, UK);
7351 }
7352
7353public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007354 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007355 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7356 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007357 Visit(E);
7358 }
7359
7360 void VisitStmt(Stmt *S) {
7361 // Skip all statements which aren't expressions for now.
7362 }
7363
7364 void VisitExpr(Expr *E) {
7365 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007366 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007367 }
7368
7369 void VisitCastExpr(CastExpr *E) {
7370 Object O = Object();
7371 if (E->getCastKind() == CK_LValueToRValue)
7372 O = getObject(E->getSubExpr(), false);
7373
7374 if (O)
7375 notePreUse(O, E);
7376 VisitExpr(E);
7377 if (O)
7378 notePostUse(O, E);
7379 }
7380
7381 void VisitBinComma(BinaryOperator *BO) {
7382 // C++11 [expr.comma]p1:
7383 // Every value computation and side effect associated with the left
7384 // expression is sequenced before every value computation and side
7385 // effect associated with the right expression.
7386 SequenceTree::Seq LHS = Tree.allocate(Region);
7387 SequenceTree::Seq RHS = Tree.allocate(Region);
7388 SequenceTree::Seq OldRegion = Region;
7389
7390 {
7391 SequencedSubexpression SeqLHS(*this);
7392 Region = LHS;
7393 Visit(BO->getLHS());
7394 }
7395
7396 Region = RHS;
7397 Visit(BO->getRHS());
7398
7399 Region = OldRegion;
7400
7401 // Forget that LHS and RHS are sequenced. They are both unsequenced
7402 // with respect to other stuff.
7403 Tree.merge(LHS);
7404 Tree.merge(RHS);
7405 }
7406
7407 void VisitBinAssign(BinaryOperator *BO) {
7408 // The modification is sequenced after the value computation of the LHS
7409 // and RHS, so check it before inspecting the operands and update the
7410 // map afterwards.
7411 Object O = getObject(BO->getLHS(), true);
7412 if (!O)
7413 return VisitExpr(BO);
7414
7415 notePreMod(O, BO);
7416
7417 // C++11 [expr.ass]p7:
7418 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7419 // only once.
7420 //
7421 // Therefore, for a compound assignment operator, O is considered used
7422 // everywhere except within the evaluation of E1 itself.
7423 if (isa<CompoundAssignOperator>(BO))
7424 notePreUse(O, BO);
7425
7426 Visit(BO->getLHS());
7427
7428 if (isa<CompoundAssignOperator>(BO))
7429 notePostUse(O, BO);
7430
7431 Visit(BO->getRHS());
7432
Richard Smith83e37bee2013-06-26 23:16:51 +00007433 // C++11 [expr.ass]p1:
7434 // the assignment is sequenced [...] before the value computation of the
7435 // assignment expression.
7436 // C11 6.5.16/3 has no such rule.
7437 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7438 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007439 }
7440 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7441 VisitBinAssign(CAO);
7442 }
7443
7444 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7445 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7446 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7447 Object O = getObject(UO->getSubExpr(), true);
7448 if (!O)
7449 return VisitExpr(UO);
7450
7451 notePreMod(O, UO);
7452 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007453 // C++11 [expr.pre.incr]p1:
7454 // the expression ++x is equivalent to x+=1
7455 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7456 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007457 }
7458
7459 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7460 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7461 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7462 Object O = getObject(UO->getSubExpr(), true);
7463 if (!O)
7464 return VisitExpr(UO);
7465
7466 notePreMod(O, UO);
7467 Visit(UO->getSubExpr());
7468 notePostMod(O, UO, UK_ModAsSideEffect);
7469 }
7470
7471 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7472 void VisitBinLOr(BinaryOperator *BO) {
7473 // The side-effects of the LHS of an '&&' are sequenced before the
7474 // value computation of the RHS, and hence before the value computation
7475 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7476 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007477 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007478 {
7479 SequencedSubexpression Sequenced(*this);
7480 Visit(BO->getLHS());
7481 }
7482
7483 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007484 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007485 if (!Result)
7486 Visit(BO->getRHS());
7487 } else {
7488 // Check for unsequenced operations in the RHS, treating it as an
7489 // entirely separate evaluation.
7490 //
7491 // FIXME: If there are operations in the RHS which are unsequenced
7492 // with respect to operations outside the RHS, and those operations
7493 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007494 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007495 }
Richard Smithc406cb72013-01-17 01:17:56 +00007496 }
7497 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007498 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007499 {
7500 SequencedSubexpression Sequenced(*this);
7501 Visit(BO->getLHS());
7502 }
7503
7504 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007505 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007506 if (Result)
7507 Visit(BO->getRHS());
7508 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007509 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007510 }
Richard Smithc406cb72013-01-17 01:17:56 +00007511 }
7512
7513 // Only visit the condition, unless we can be sure which subexpression will
7514 // be chosen.
7515 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007516 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007517 {
7518 SequencedSubexpression Sequenced(*this);
7519 Visit(CO->getCond());
7520 }
Richard Smithc406cb72013-01-17 01:17:56 +00007521
7522 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007523 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007524 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007525 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007526 WorkList.push_back(CO->getTrueExpr());
7527 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007528 }
Richard Smithc406cb72013-01-17 01:17:56 +00007529 }
7530
Richard Smithe3dbfe02013-06-30 10:40:20 +00007531 void VisitCallExpr(CallExpr *CE) {
7532 // C++11 [intro.execution]p15:
7533 // When calling a function [...], every value computation and side effect
7534 // associated with any argument expression, or with the postfix expression
7535 // designating the called function, is sequenced before execution of every
7536 // expression or statement in the body of the function [and thus before
7537 // the value computation of its result].
7538 SequencedSubexpression Sequenced(*this);
7539 Base::VisitCallExpr(CE);
7540
7541 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7542 }
7543
Richard Smithc406cb72013-01-17 01:17:56 +00007544 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007545 // This is a call, so all subexpressions are sequenced before the result.
7546 SequencedSubexpression Sequenced(*this);
7547
Richard Smithc406cb72013-01-17 01:17:56 +00007548 if (!CCE->isListInitialization())
7549 return VisitExpr(CCE);
7550
7551 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007552 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007553 SequenceTree::Seq Parent = Region;
7554 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7555 E = CCE->arg_end();
7556 I != E; ++I) {
7557 Region = Tree.allocate(Parent);
7558 Elts.push_back(Region);
7559 Visit(*I);
7560 }
7561
7562 // Forget that the initializers are sequenced.
7563 Region = Parent;
7564 for (unsigned I = 0; I < Elts.size(); ++I)
7565 Tree.merge(Elts[I]);
7566 }
7567
7568 void VisitInitListExpr(InitListExpr *ILE) {
7569 if (!SemaRef.getLangOpts().CPlusPlus11)
7570 return VisitExpr(ILE);
7571
7572 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007573 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007574 SequenceTree::Seq Parent = Region;
7575 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7576 Expr *E = ILE->getInit(I);
7577 if (!E) continue;
7578 Region = Tree.allocate(Parent);
7579 Elts.push_back(Region);
7580 Visit(E);
7581 }
7582
7583 // Forget that the initializers are sequenced.
7584 Region = Parent;
7585 for (unsigned I = 0; I < Elts.size(); ++I)
7586 Tree.merge(Elts[I]);
7587 }
7588};
7589}
7590
7591void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007592 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007593 WorkList.push_back(E);
7594 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007595 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007596 SequenceChecker(*this, Item, WorkList);
7597 }
Richard Smithc406cb72013-01-17 01:17:56 +00007598}
7599
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007600void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7601 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007602 CheckImplicitConversions(E, CheckLoc);
7603 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007604 if (!IsConstexpr && !E->isValueDependent())
7605 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007606}
7607
John McCall1f425642010-11-11 03:21:53 +00007608void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7609 FieldDecl *BitField,
7610 Expr *Init) {
7611 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7612}
7613
Mike Stump0c2ec772010-01-21 03:59:47 +00007614/// CheckParmsForFunctionDef - Check that the parameters of the given
7615/// function are appropriate for the definition of a function. This
7616/// takes care of any checks that cannot be performed on the
7617/// declaration itself, e.g., that the types of each of the function
7618/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007619bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7620 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007621 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007622 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007623 for (; P != PEnd; ++P) {
7624 ParmVarDecl *Param = *P;
7625
Mike Stump0c2ec772010-01-21 03:59:47 +00007626 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7627 // function declarator that is part of a function definition of
7628 // that function shall not have incomplete type.
7629 //
7630 // This is also C++ [dcl.fct]p6.
7631 if (!Param->isInvalidDecl() &&
7632 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007633 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007634 Param->setInvalidDecl();
7635 HasInvalidParm = true;
7636 }
7637
7638 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7639 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007640 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007641 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007642 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007643 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007644 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007645
7646 // C99 6.7.5.3p12:
7647 // If the function declarator is not part of a definition of that
7648 // function, parameters may have incomplete type and may use the [*]
7649 // notation in their sequences of declarator specifiers to specify
7650 // variable length array types.
7651 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007652 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007653 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007654 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007655 // information is added for it.
7656 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007657 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007658 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007659 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007660 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007661
7662 // MSVC destroys objects passed by value in the callee. Therefore a
7663 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007664 // object's destructor. However, we don't perform any direct access check
7665 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007666 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7667 .getCXXABI()
7668 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007669 if (!Param->isInvalidDecl()) {
7670 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7671 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7672 if (!ClassDecl->isInvalidDecl() &&
7673 !ClassDecl->hasIrrelevantDestructor() &&
7674 !ClassDecl->isDependentContext()) {
7675 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7676 MarkFunctionReferenced(Param->getLocation(), Destructor);
7677 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7678 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007679 }
7680 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007681 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007682 }
7683
7684 return HasInvalidParm;
7685}
John McCall2b5c1b22010-08-12 21:44:57 +00007686
7687/// CheckCastAlign - Implements -Wcast-align, which warns when a
7688/// pointer cast increases the alignment requirements.
7689void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7690 // This is actually a lot of work to potentially be doing on every
7691 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007692 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007693 return;
7694
7695 // Ignore dependent types.
7696 if (T->isDependentType() || Op->getType()->isDependentType())
7697 return;
7698
7699 // Require that the destination be a pointer type.
7700 const PointerType *DestPtr = T->getAs<PointerType>();
7701 if (!DestPtr) return;
7702
7703 // If the destination has alignment 1, we're done.
7704 QualType DestPointee = DestPtr->getPointeeType();
7705 if (DestPointee->isIncompleteType()) return;
7706 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7707 if (DestAlign.isOne()) return;
7708
7709 // Require that the source be a pointer type.
7710 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7711 if (!SrcPtr) return;
7712 QualType SrcPointee = SrcPtr->getPointeeType();
7713
7714 // Whitelist casts from cv void*. We already implicitly
7715 // whitelisted casts to cv void*, since they have alignment 1.
7716 // Also whitelist casts involving incomplete types, which implicitly
7717 // includes 'void'.
7718 if (SrcPointee->isIncompleteType()) return;
7719
7720 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7721 if (SrcAlign >= DestAlign) return;
7722
7723 Diag(TRange.getBegin(), diag::warn_cast_align)
7724 << Op->getType() << T
7725 << static_cast<unsigned>(SrcAlign.getQuantity())
7726 << static_cast<unsigned>(DestAlign.getQuantity())
7727 << TRange << Op->getSourceRange();
7728}
7729
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007730static const Type* getElementType(const Expr *BaseExpr) {
7731 const Type* EltType = BaseExpr->getType().getTypePtr();
7732 if (EltType->isAnyPointerType())
7733 return EltType->getPointeeType().getTypePtr();
7734 else if (EltType->isArrayType())
7735 return EltType->getBaseElementTypeUnsafe();
7736 return EltType;
7737}
7738
Chandler Carruth28389f02011-08-05 09:10:50 +00007739/// \brief Check whether this array fits the idiom of a size-one tail padded
7740/// array member of a struct.
7741///
7742/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7743/// commonly used to emulate flexible arrays in C89 code.
7744static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7745 const NamedDecl *ND) {
7746 if (Size != 1 || !ND) return false;
7747
7748 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7749 if (!FD) return false;
7750
7751 // Don't consider sizes resulting from macro expansions or template argument
7752 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007753
7754 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007755 while (TInfo) {
7756 TypeLoc TL = TInfo->getTypeLoc();
7757 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007758 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7759 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007760 TInfo = TDL->getTypeSourceInfo();
7761 continue;
7762 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007763 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7764 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007765 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7766 return false;
7767 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007768 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007769 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007770
7771 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007772 if (!RD) return false;
7773 if (RD->isUnion()) return false;
7774 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7775 if (!CRD->isStandardLayout()) return false;
7776 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007777
Benjamin Kramer8c543672011-08-06 03:04:42 +00007778 // See if this is the last field decl in the record.
7779 const Decl *D = FD;
7780 while ((D = D->getNextDeclInContext()))
7781 if (isa<FieldDecl>(D))
7782 return false;
7783 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007784}
7785
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007786void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007787 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007788 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007789 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007790 if (IndexExpr->isValueDependent())
7791 return;
7792
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007793 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007794 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007795 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007796 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007797 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007798 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007799
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007800 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007801 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007802 return;
Richard Smith13f67182011-12-16 19:31:14 +00007803 if (IndexNegated)
7804 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007805
Craig Topperc3ec1492014-05-26 06:22:03 +00007806 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007807 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7808 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007809 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007810 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007811
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007812 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007813 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007814 if (!size.isStrictlyPositive())
7815 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007816
7817 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007818 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007819 // Make sure we're comparing apples to apples when comparing index to size
7820 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7821 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007822 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007823 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007824 if (ptrarith_typesize != array_typesize) {
7825 // There's a cast to a different size type involved
7826 uint64_t ratio = array_typesize / ptrarith_typesize;
7827 // TODO: Be smarter about handling cases where array_typesize is not a
7828 // multiple of ptrarith_typesize
7829 if (ptrarith_typesize * ratio == array_typesize)
7830 size *= llvm::APInt(size.getBitWidth(), ratio);
7831 }
7832 }
7833
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007834 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007835 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007836 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007837 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007838
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007839 // For array subscripting the index must be less than size, but for pointer
7840 // arithmetic also allow the index (offset) to be equal to size since
7841 // computing the next address after the end of the array is legal and
7842 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007843 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007844 return;
7845
7846 // Also don't warn for arrays of size 1 which are members of some
7847 // structure. These are often used to approximate flexible arrays in C89
7848 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007849 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007850 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007851
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007852 // Suppress the warning if the subscript expression (as identified by the
7853 // ']' location) and the index expression are both from macro expansions
7854 // within a system header.
7855 if (ASE) {
7856 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7857 ASE->getRBracketLoc());
7858 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7859 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7860 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007861 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007862 return;
7863 }
7864 }
7865
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007866 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007867 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007868 DiagID = diag::warn_array_index_exceeds_bounds;
7869
7870 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7871 PDiag(DiagID) << index.toString(10, true)
7872 << size.toString(10, true)
7873 << (unsigned)size.getLimitedValue(~0U)
7874 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007875 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007876 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007877 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007878 DiagID = diag::warn_ptr_arith_precedes_bounds;
7879 if (index.isNegative()) index = -index;
7880 }
7881
7882 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7883 PDiag(DiagID) << index.toString(10, true)
7884 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007885 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007886
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007887 if (!ND) {
7888 // Try harder to find a NamedDecl to point at in the note.
7889 while (const ArraySubscriptExpr *ASE =
7890 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7891 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7892 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7893 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7894 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7895 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7896 }
7897
Chandler Carruth1af88f12011-02-17 21:10:52 +00007898 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007899 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7900 PDiag(diag::note_array_index_out_of_bounds)
7901 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007902}
7903
Ted Kremenekdf26df72011-03-01 18:41:00 +00007904void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007905 int AllowOnePastEnd = 0;
7906 while (expr) {
7907 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007908 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007909 case Stmt::ArraySubscriptExprClass: {
7910 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007911 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007912 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007913 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007914 }
7915 case Stmt::UnaryOperatorClass: {
7916 // Only unwrap the * and & unary operators
7917 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7918 expr = UO->getSubExpr();
7919 switch (UO->getOpcode()) {
7920 case UO_AddrOf:
7921 AllowOnePastEnd++;
7922 break;
7923 case UO_Deref:
7924 AllowOnePastEnd--;
7925 break;
7926 default:
7927 return;
7928 }
7929 break;
7930 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007931 case Stmt::ConditionalOperatorClass: {
7932 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7933 if (const Expr *lhs = cond->getLHS())
7934 CheckArrayAccess(lhs);
7935 if (const Expr *rhs = cond->getRHS())
7936 CheckArrayAccess(rhs);
7937 return;
7938 }
7939 default:
7940 return;
7941 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007942 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007943}
John McCall31168b02011-06-15 23:02:42 +00007944
7945//===--- CHECK: Objective-C retain cycles ----------------------------------//
7946
7947namespace {
7948 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007949 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007950 VarDecl *Variable;
7951 SourceRange Range;
7952 SourceLocation Loc;
7953 bool Indirect;
7954
7955 void setLocsFrom(Expr *e) {
7956 Loc = e->getExprLoc();
7957 Range = e->getSourceRange();
7958 }
7959 };
7960}
7961
7962/// Consider whether capturing the given variable can possibly lead to
7963/// a retain cycle.
7964static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007965 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007966 // lifetime. In MRR, it's captured strongly if the variable is
7967 // __block and has an appropriate type.
7968 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7969 return false;
7970
7971 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007972 if (ref)
7973 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007974 return true;
7975}
7976
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007977static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007978 while (true) {
7979 e = e->IgnoreParens();
7980 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7981 switch (cast->getCastKind()) {
7982 case CK_BitCast:
7983 case CK_LValueBitCast:
7984 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007985 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007986 e = cast->getSubExpr();
7987 continue;
7988
John McCall31168b02011-06-15 23:02:42 +00007989 default:
7990 return false;
7991 }
7992 }
7993
7994 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7995 ObjCIvarDecl *ivar = ref->getDecl();
7996 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7997 return false;
7998
7999 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008000 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008001 return false;
8002
8003 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8004 owner.Indirect = true;
8005 return true;
8006 }
8007
8008 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8009 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8010 if (!var) return false;
8011 return considerVariable(var, ref, owner);
8012 }
8013
John McCall31168b02011-06-15 23:02:42 +00008014 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8015 if (member->isArrow()) return false;
8016
8017 // Don't count this as an indirect ownership.
8018 e = member->getBase();
8019 continue;
8020 }
8021
John McCallfe96e0b2011-11-06 09:01:30 +00008022 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8023 // Only pay attention to pseudo-objects on property references.
8024 ObjCPropertyRefExpr *pre
8025 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8026 ->IgnoreParens());
8027 if (!pre) return false;
8028 if (pre->isImplicitProperty()) return false;
8029 ObjCPropertyDecl *property = pre->getExplicitProperty();
8030 if (!property->isRetaining() &&
8031 !(property->getPropertyIvarDecl() &&
8032 property->getPropertyIvarDecl()->getType()
8033 .getObjCLifetime() == Qualifiers::OCL_Strong))
8034 return false;
8035
8036 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008037 if (pre->isSuperReceiver()) {
8038 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8039 if (!owner.Variable)
8040 return false;
8041 owner.Loc = pre->getLocation();
8042 owner.Range = pre->getSourceRange();
8043 return true;
8044 }
John McCallfe96e0b2011-11-06 09:01:30 +00008045 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8046 ->getSourceExpr());
8047 continue;
8048 }
8049
John McCall31168b02011-06-15 23:02:42 +00008050 // Array ivars?
8051
8052 return false;
8053 }
8054}
8055
8056namespace {
8057 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8058 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8059 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008060 Context(Context), Variable(variable), Capturer(nullptr),
8061 VarWillBeReased(false) {}
8062 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008063 VarDecl *Variable;
8064 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008065 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008066
8067 void VisitDeclRefExpr(DeclRefExpr *ref) {
8068 if (ref->getDecl() == Variable && !Capturer)
8069 Capturer = ref;
8070 }
8071
John McCall31168b02011-06-15 23:02:42 +00008072 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8073 if (Capturer) return;
8074 Visit(ref->getBase());
8075 if (Capturer && ref->isFreeIvar())
8076 Capturer = ref;
8077 }
8078
8079 void VisitBlockExpr(BlockExpr *block) {
8080 // Look inside nested blocks
8081 if (block->getBlockDecl()->capturesVariable(Variable))
8082 Visit(block->getBlockDecl()->getBody());
8083 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008084
8085 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8086 if (Capturer) return;
8087 if (OVE->getSourceExpr())
8088 Visit(OVE->getSourceExpr());
8089 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008090 void VisitBinaryOperator(BinaryOperator *BinOp) {
8091 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8092 return;
8093 Expr *LHS = BinOp->getLHS();
8094 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8095 if (DRE->getDecl() != Variable)
8096 return;
8097 if (Expr *RHS = BinOp->getRHS()) {
8098 RHS = RHS->IgnoreParenCasts();
8099 llvm::APSInt Value;
8100 VarWillBeReased =
8101 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8102 }
8103 }
8104 }
John McCall31168b02011-06-15 23:02:42 +00008105 };
8106}
8107
8108/// Check whether the given argument is a block which captures a
8109/// variable.
8110static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8111 assert(owner.Variable && owner.Loc.isValid());
8112
8113 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008114
8115 // Look through [^{...} copy] and Block_copy(^{...}).
8116 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8117 Selector Cmd = ME->getSelector();
8118 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8119 e = ME->getInstanceReceiver();
8120 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008121 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008122 e = e->IgnoreParenCasts();
8123 }
8124 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8125 if (CE->getNumArgs() == 1) {
8126 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008127 if (Fn) {
8128 const IdentifierInfo *FnI = Fn->getIdentifier();
8129 if (FnI && FnI->isStr("_Block_copy")) {
8130 e = CE->getArg(0)->IgnoreParenCasts();
8131 }
8132 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008133 }
8134 }
8135
John McCall31168b02011-06-15 23:02:42 +00008136 BlockExpr *block = dyn_cast<BlockExpr>(e);
8137 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008138 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008139
8140 FindCaptureVisitor visitor(S.Context, owner.Variable);
8141 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008142 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008143}
8144
8145static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8146 RetainCycleOwner &owner) {
8147 assert(capturer);
8148 assert(owner.Variable && owner.Loc.isValid());
8149
8150 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8151 << owner.Variable << capturer->getSourceRange();
8152 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8153 << owner.Indirect << owner.Range;
8154}
8155
8156/// Check for a keyword selector that starts with the word 'add' or
8157/// 'set'.
8158static bool isSetterLikeSelector(Selector sel) {
8159 if (sel.isUnarySelector()) return false;
8160
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008161 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008162 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008163 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008164 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008165 else if (str.startswith("add")) {
8166 // Specially whitelist 'addOperationWithBlock:'.
8167 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8168 return false;
8169 str = str.substr(3);
8170 }
John McCall31168b02011-06-15 23:02:42 +00008171 else
8172 return false;
8173
8174 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008175 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008176}
8177
8178/// Check a message send to see if it's likely to cause a retain cycle.
8179void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8180 // Only check instance methods whose selector looks like a setter.
8181 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8182 return;
8183
8184 // Try to find a variable that the receiver is strongly owned by.
8185 RetainCycleOwner owner;
8186 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008187 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008188 return;
8189 } else {
8190 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8191 owner.Variable = getCurMethodDecl()->getSelfDecl();
8192 owner.Loc = msg->getSuperLoc();
8193 owner.Range = msg->getSuperLoc();
8194 }
8195
8196 // Check whether the receiver is captured by any of the arguments.
8197 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8198 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8199 return diagnoseRetainCycle(*this, capturer, owner);
8200}
8201
8202/// Check a property assign to see if it's likely to cause a retain cycle.
8203void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8204 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008205 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008206 return;
8207
8208 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8209 diagnoseRetainCycle(*this, capturer, owner);
8210}
8211
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008212void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8213 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008214 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008215 return;
8216
8217 // Because we don't have an expression for the variable, we have to set the
8218 // location explicitly here.
8219 Owner.Loc = Var->getLocation();
8220 Owner.Range = Var->getSourceRange();
8221
8222 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8223 diagnoseRetainCycle(*this, Capturer, Owner);
8224}
8225
Ted Kremenek9304da92012-12-21 08:04:28 +00008226static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8227 Expr *RHS, bool isProperty) {
8228 // Check if RHS is an Objective-C object literal, which also can get
8229 // immediately zapped in a weak reference. Note that we explicitly
8230 // allow ObjCStringLiterals, since those are designed to never really die.
8231 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008232
Ted Kremenek64873352012-12-21 22:46:35 +00008233 // This enum needs to match with the 'select' in
8234 // warn_objc_arc_literal_assign (off-by-1).
8235 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8236 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8237 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008238
8239 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008240 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008241 << (isProperty ? 0 : 1)
8242 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008243
8244 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008245}
8246
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008247static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8248 Qualifiers::ObjCLifetime LT,
8249 Expr *RHS, bool isProperty) {
8250 // Strip off any implicit cast added to get to the one ARC-specific.
8251 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8252 if (cast->getCastKind() == CK_ARCConsumeObject) {
8253 S.Diag(Loc, diag::warn_arc_retained_assign)
8254 << (LT == Qualifiers::OCL_ExplicitNone)
8255 << (isProperty ? 0 : 1)
8256 << RHS->getSourceRange();
8257 return true;
8258 }
8259 RHS = cast->getSubExpr();
8260 }
8261
8262 if (LT == Qualifiers::OCL_Weak &&
8263 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8264 return true;
8265
8266 return false;
8267}
8268
Ted Kremenekb36234d2012-12-21 08:04:20 +00008269bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8270 QualType LHS, Expr *RHS) {
8271 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8272
8273 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8274 return false;
8275
8276 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8277 return true;
8278
8279 return false;
8280}
8281
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008282void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8283 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008284 QualType LHSType;
8285 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008286 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008287 ObjCPropertyRefExpr *PRE
8288 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8289 if (PRE && !PRE->isImplicitProperty()) {
8290 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8291 if (PD)
8292 LHSType = PD->getType();
8293 }
8294
8295 if (LHSType.isNull())
8296 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008297
8298 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8299
8300 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008301 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008302 getCurFunction()->markSafeWeakUse(LHS);
8303 }
8304
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008305 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8306 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008307
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008308 // FIXME. Check for other life times.
8309 if (LT != Qualifiers::OCL_None)
8310 return;
8311
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008312 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008313 if (PRE->isImplicitProperty())
8314 return;
8315 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8316 if (!PD)
8317 return;
8318
Bill Wendling44426052012-12-20 19:22:21 +00008319 unsigned Attributes = PD->getPropertyAttributes();
8320 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008321 // when 'assign' attribute was not explicitly specified
8322 // by user, ignore it and rely on property type itself
8323 // for lifetime info.
8324 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8325 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8326 LHSType->isObjCRetainableType())
8327 return;
8328
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008329 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008330 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008331 Diag(Loc, diag::warn_arc_retained_property_assign)
8332 << RHS->getSourceRange();
8333 return;
8334 }
8335 RHS = cast->getSubExpr();
8336 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008337 }
Bill Wendling44426052012-12-20 19:22:21 +00008338 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008339 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8340 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008341 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008342 }
8343}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008344
8345//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8346
8347namespace {
8348bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8349 SourceLocation StmtLoc,
8350 const NullStmt *Body) {
8351 // Do not warn if the body is a macro that expands to nothing, e.g:
8352 //
8353 // #define CALL(x)
8354 // if (condition)
8355 // CALL(0);
8356 //
8357 if (Body->hasLeadingEmptyMacro())
8358 return false;
8359
8360 // Get line numbers of statement and body.
8361 bool StmtLineInvalid;
8362 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8363 &StmtLineInvalid);
8364 if (StmtLineInvalid)
8365 return false;
8366
8367 bool BodyLineInvalid;
8368 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8369 &BodyLineInvalid);
8370 if (BodyLineInvalid)
8371 return false;
8372
8373 // Warn if null statement and body are on the same line.
8374 if (StmtLine != BodyLine)
8375 return false;
8376
8377 return true;
8378}
8379} // Unnamed namespace
8380
8381void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8382 const Stmt *Body,
8383 unsigned DiagID) {
8384 // Since this is a syntactic check, don't emit diagnostic for template
8385 // instantiations, this just adds noise.
8386 if (CurrentInstantiationScope)
8387 return;
8388
8389 // The body should be a null statement.
8390 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8391 if (!NBody)
8392 return;
8393
8394 // Do the usual checks.
8395 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8396 return;
8397
8398 Diag(NBody->getSemiLoc(), DiagID);
8399 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8400}
8401
8402void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8403 const Stmt *PossibleBody) {
8404 assert(!CurrentInstantiationScope); // Ensured by caller
8405
8406 SourceLocation StmtLoc;
8407 const Stmt *Body;
8408 unsigned DiagID;
8409 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8410 StmtLoc = FS->getRParenLoc();
8411 Body = FS->getBody();
8412 DiagID = diag::warn_empty_for_body;
8413 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8414 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8415 Body = WS->getBody();
8416 DiagID = diag::warn_empty_while_body;
8417 } else
8418 return; // Neither `for' nor `while'.
8419
8420 // The body should be a null statement.
8421 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8422 if (!NBody)
8423 return;
8424
8425 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008426 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008427 return;
8428
8429 // Do the usual checks.
8430 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8431 return;
8432
8433 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8434 // noise level low, emit diagnostics only if for/while is followed by a
8435 // CompoundStmt, e.g.:
8436 // for (int i = 0; i < n; i++);
8437 // {
8438 // a(i);
8439 // }
8440 // or if for/while is followed by a statement with more indentation
8441 // than for/while itself:
8442 // for (int i = 0; i < n; i++);
8443 // a(i);
8444 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8445 if (!ProbableTypo) {
8446 bool BodyColInvalid;
8447 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8448 PossibleBody->getLocStart(),
8449 &BodyColInvalid);
8450 if (BodyColInvalid)
8451 return;
8452
8453 bool StmtColInvalid;
8454 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8455 S->getLocStart(),
8456 &StmtColInvalid);
8457 if (StmtColInvalid)
8458 return;
8459
8460 if (BodyCol > StmtCol)
8461 ProbableTypo = true;
8462 }
8463
8464 if (ProbableTypo) {
8465 Diag(NBody->getSemiLoc(), DiagID);
8466 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8467 }
8468}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008469
Richard Trieu36d0b2b2015-01-13 02:32:02 +00008470//===--- CHECK: Warn on self move with std::move. -------------------------===//
8471
8472/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8473void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8474 SourceLocation OpLoc) {
8475
8476 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8477 return;
8478
8479 if (!ActiveTemplateInstantiations.empty())
8480 return;
8481
8482 // Strip parens and casts away.
8483 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8484 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8485
8486 // Check for a call expression
8487 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8488 if (!CE || CE->getNumArgs() != 1)
8489 return;
8490
8491 // Check for a call to std::move
8492 const FunctionDecl *FD = CE->getDirectCallee();
8493 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8494 !FD->getIdentifier()->isStr("move"))
8495 return;
8496
8497 // Get argument from std::move
8498 RHSExpr = CE->getArg(0);
8499
8500 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8501 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8502
8503 // Two DeclRefExpr's, check that the decls are the same.
8504 if (LHSDeclRef && RHSDeclRef) {
8505 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8506 return;
8507 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8508 RHSDeclRef->getDecl()->getCanonicalDecl())
8509 return;
8510
8511 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8512 << LHSExpr->getSourceRange()
8513 << RHSExpr->getSourceRange();
8514 return;
8515 }
8516
8517 // Member variables require a different approach to check for self moves.
8518 // MemberExpr's are the same if every nested MemberExpr refers to the same
8519 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8520 // the base Expr's are CXXThisExpr's.
8521 const Expr *LHSBase = LHSExpr;
8522 const Expr *RHSBase = RHSExpr;
8523 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8524 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8525 if (!LHSME || !RHSME)
8526 return;
8527
8528 while (LHSME && RHSME) {
8529 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8530 RHSME->getMemberDecl()->getCanonicalDecl())
8531 return;
8532
8533 LHSBase = LHSME->getBase();
8534 RHSBase = RHSME->getBase();
8535 LHSME = dyn_cast<MemberExpr>(LHSBase);
8536 RHSME = dyn_cast<MemberExpr>(RHSBase);
8537 }
8538
8539 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8540 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8541 if (LHSDeclRef && RHSDeclRef) {
8542 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8543 return;
8544 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8545 RHSDeclRef->getDecl()->getCanonicalDecl())
8546 return;
8547
8548 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8549 << LHSExpr->getSourceRange()
8550 << RHSExpr->getSourceRange();
8551 return;
8552 }
8553
8554 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8555 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8556 << LHSExpr->getSourceRange()
8557 << RHSExpr->getSourceRange();
8558}
8559
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008560//===--- Layout compatibility ----------------------------------------------//
8561
8562namespace {
8563
8564bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8565
8566/// \brief Check if two enumeration types are layout-compatible.
8567bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8568 // C++11 [dcl.enum] p8:
8569 // Two enumeration types are layout-compatible if they have the same
8570 // underlying type.
8571 return ED1->isComplete() && ED2->isComplete() &&
8572 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8573}
8574
8575/// \brief Check if two fields are layout-compatible.
8576bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8577 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8578 return false;
8579
8580 if (Field1->isBitField() != Field2->isBitField())
8581 return false;
8582
8583 if (Field1->isBitField()) {
8584 // Make sure that the bit-fields are the same length.
8585 unsigned Bits1 = Field1->getBitWidthValue(C);
8586 unsigned Bits2 = Field2->getBitWidthValue(C);
8587
8588 if (Bits1 != Bits2)
8589 return false;
8590 }
8591
8592 return true;
8593}
8594
8595/// \brief Check if two standard-layout structs are layout-compatible.
8596/// (C++11 [class.mem] p17)
8597bool isLayoutCompatibleStruct(ASTContext &C,
8598 RecordDecl *RD1,
8599 RecordDecl *RD2) {
8600 // If both records are C++ classes, check that base classes match.
8601 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8602 // If one of records is a CXXRecordDecl we are in C++ mode,
8603 // thus the other one is a CXXRecordDecl, too.
8604 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8605 // Check number of base classes.
8606 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8607 return false;
8608
8609 // Check the base classes.
8610 for (CXXRecordDecl::base_class_const_iterator
8611 Base1 = D1CXX->bases_begin(),
8612 BaseEnd1 = D1CXX->bases_end(),
8613 Base2 = D2CXX->bases_begin();
8614 Base1 != BaseEnd1;
8615 ++Base1, ++Base2) {
8616 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8617 return false;
8618 }
8619 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8620 // If only RD2 is a C++ class, it should have zero base classes.
8621 if (D2CXX->getNumBases() > 0)
8622 return false;
8623 }
8624
8625 // Check the fields.
8626 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8627 Field2End = RD2->field_end(),
8628 Field1 = RD1->field_begin(),
8629 Field1End = RD1->field_end();
8630 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8631 if (!isLayoutCompatible(C, *Field1, *Field2))
8632 return false;
8633 }
8634 if (Field1 != Field1End || Field2 != Field2End)
8635 return false;
8636
8637 return true;
8638}
8639
8640/// \brief Check if two standard-layout unions are layout-compatible.
8641/// (C++11 [class.mem] p18)
8642bool isLayoutCompatibleUnion(ASTContext &C,
8643 RecordDecl *RD1,
8644 RecordDecl *RD2) {
8645 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008646 for (auto *Field2 : RD2->fields())
8647 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008648
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008649 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008650 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8651 I = UnmatchedFields.begin(),
8652 E = UnmatchedFields.end();
8653
8654 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008655 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008656 bool Result = UnmatchedFields.erase(*I);
8657 (void) Result;
8658 assert(Result);
8659 break;
8660 }
8661 }
8662 if (I == E)
8663 return false;
8664 }
8665
8666 return UnmatchedFields.empty();
8667}
8668
8669bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8670 if (RD1->isUnion() != RD2->isUnion())
8671 return false;
8672
8673 if (RD1->isUnion())
8674 return isLayoutCompatibleUnion(C, RD1, RD2);
8675 else
8676 return isLayoutCompatibleStruct(C, RD1, RD2);
8677}
8678
8679/// \brief Check if two types are layout-compatible in C++11 sense.
8680bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8681 if (T1.isNull() || T2.isNull())
8682 return false;
8683
8684 // C++11 [basic.types] p11:
8685 // If two types T1 and T2 are the same type, then T1 and T2 are
8686 // layout-compatible types.
8687 if (C.hasSameType(T1, T2))
8688 return true;
8689
8690 T1 = T1.getCanonicalType().getUnqualifiedType();
8691 T2 = T2.getCanonicalType().getUnqualifiedType();
8692
8693 const Type::TypeClass TC1 = T1->getTypeClass();
8694 const Type::TypeClass TC2 = T2->getTypeClass();
8695
8696 if (TC1 != TC2)
8697 return false;
8698
8699 if (TC1 == Type::Enum) {
8700 return isLayoutCompatible(C,
8701 cast<EnumType>(T1)->getDecl(),
8702 cast<EnumType>(T2)->getDecl());
8703 } else if (TC1 == Type::Record) {
8704 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8705 return false;
8706
8707 return isLayoutCompatible(C,
8708 cast<RecordType>(T1)->getDecl(),
8709 cast<RecordType>(T2)->getDecl());
8710 }
8711
8712 return false;
8713}
8714}
8715
8716//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8717
8718namespace {
8719/// \brief Given a type tag expression find the type tag itself.
8720///
8721/// \param TypeExpr Type tag expression, as it appears in user's code.
8722///
8723/// \param VD Declaration of an identifier that appears in a type tag.
8724///
8725/// \param MagicValue Type tag magic value.
8726bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8727 const ValueDecl **VD, uint64_t *MagicValue) {
8728 while(true) {
8729 if (!TypeExpr)
8730 return false;
8731
8732 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8733
8734 switch (TypeExpr->getStmtClass()) {
8735 case Stmt::UnaryOperatorClass: {
8736 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8737 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8738 TypeExpr = UO->getSubExpr();
8739 continue;
8740 }
8741 return false;
8742 }
8743
8744 case Stmt::DeclRefExprClass: {
8745 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8746 *VD = DRE->getDecl();
8747 return true;
8748 }
8749
8750 case Stmt::IntegerLiteralClass: {
8751 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8752 llvm::APInt MagicValueAPInt = IL->getValue();
8753 if (MagicValueAPInt.getActiveBits() <= 64) {
8754 *MagicValue = MagicValueAPInt.getZExtValue();
8755 return true;
8756 } else
8757 return false;
8758 }
8759
8760 case Stmt::BinaryConditionalOperatorClass:
8761 case Stmt::ConditionalOperatorClass: {
8762 const AbstractConditionalOperator *ACO =
8763 cast<AbstractConditionalOperator>(TypeExpr);
8764 bool Result;
8765 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8766 if (Result)
8767 TypeExpr = ACO->getTrueExpr();
8768 else
8769 TypeExpr = ACO->getFalseExpr();
8770 continue;
8771 }
8772 return false;
8773 }
8774
8775 case Stmt::BinaryOperatorClass: {
8776 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8777 if (BO->getOpcode() == BO_Comma) {
8778 TypeExpr = BO->getRHS();
8779 continue;
8780 }
8781 return false;
8782 }
8783
8784 default:
8785 return false;
8786 }
8787 }
8788}
8789
8790/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8791///
8792/// \param TypeExpr Expression that specifies a type tag.
8793///
8794/// \param MagicValues Registered magic values.
8795///
8796/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8797/// kind.
8798///
8799/// \param TypeInfo Information about the corresponding C type.
8800///
8801/// \returns true if the corresponding C type was found.
8802bool GetMatchingCType(
8803 const IdentifierInfo *ArgumentKind,
8804 const Expr *TypeExpr, const ASTContext &Ctx,
8805 const llvm::DenseMap<Sema::TypeTagMagicValue,
8806 Sema::TypeTagData> *MagicValues,
8807 bool &FoundWrongKind,
8808 Sema::TypeTagData &TypeInfo) {
8809 FoundWrongKind = false;
8810
8811 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008812 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008813
8814 uint64_t MagicValue;
8815
8816 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8817 return false;
8818
8819 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008820 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008821 if (I->getArgumentKind() != ArgumentKind) {
8822 FoundWrongKind = true;
8823 return false;
8824 }
8825 TypeInfo.Type = I->getMatchingCType();
8826 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8827 TypeInfo.MustBeNull = I->getMustBeNull();
8828 return true;
8829 }
8830 return false;
8831 }
8832
8833 if (!MagicValues)
8834 return false;
8835
8836 llvm::DenseMap<Sema::TypeTagMagicValue,
8837 Sema::TypeTagData>::const_iterator I =
8838 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8839 if (I == MagicValues->end())
8840 return false;
8841
8842 TypeInfo = I->second;
8843 return true;
8844}
8845} // unnamed namespace
8846
8847void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8848 uint64_t MagicValue, QualType Type,
8849 bool LayoutCompatible,
8850 bool MustBeNull) {
8851 if (!TypeTagForDatatypeMagicValues)
8852 TypeTagForDatatypeMagicValues.reset(
8853 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8854
8855 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8856 (*TypeTagForDatatypeMagicValues)[Magic] =
8857 TypeTagData(Type, LayoutCompatible, MustBeNull);
8858}
8859
8860namespace {
8861bool IsSameCharType(QualType T1, QualType T2) {
8862 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8863 if (!BT1)
8864 return false;
8865
8866 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8867 if (!BT2)
8868 return false;
8869
8870 BuiltinType::Kind T1Kind = BT1->getKind();
8871 BuiltinType::Kind T2Kind = BT2->getKind();
8872
8873 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8874 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8875 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8876 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8877}
8878} // unnamed namespace
8879
8880void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8881 const Expr * const *ExprArgs) {
8882 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8883 bool IsPointerAttr = Attr->getIsPointer();
8884
8885 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8886 bool FoundWrongKind;
8887 TypeTagData TypeInfo;
8888 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8889 TypeTagForDatatypeMagicValues.get(),
8890 FoundWrongKind, TypeInfo)) {
8891 if (FoundWrongKind)
8892 Diag(TypeTagExpr->getExprLoc(),
8893 diag::warn_type_tag_for_datatype_wrong_kind)
8894 << TypeTagExpr->getSourceRange();
8895 return;
8896 }
8897
8898 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8899 if (IsPointerAttr) {
8900 // Skip implicit cast of pointer to `void *' (as a function argument).
8901 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008902 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008903 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008904 ArgumentExpr = ICE->getSubExpr();
8905 }
8906 QualType ArgumentType = ArgumentExpr->getType();
8907
8908 // Passing a `void*' pointer shouldn't trigger a warning.
8909 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8910 return;
8911
8912 if (TypeInfo.MustBeNull) {
8913 // Type tag with matching void type requires a null pointer.
8914 if (!ArgumentExpr->isNullPointerConstant(Context,
8915 Expr::NPC_ValueDependentIsNotNull)) {
8916 Diag(ArgumentExpr->getExprLoc(),
8917 diag::warn_type_safety_null_pointer_required)
8918 << ArgumentKind->getName()
8919 << ArgumentExpr->getSourceRange()
8920 << TypeTagExpr->getSourceRange();
8921 }
8922 return;
8923 }
8924
8925 QualType RequiredType = TypeInfo.Type;
8926 if (IsPointerAttr)
8927 RequiredType = Context.getPointerType(RequiredType);
8928
8929 bool mismatch = false;
8930 if (!TypeInfo.LayoutCompatible) {
8931 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8932
8933 // C++11 [basic.fundamental] p1:
8934 // Plain char, signed char, and unsigned char are three distinct types.
8935 //
8936 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8937 // char' depending on the current char signedness mode.
8938 if (mismatch)
8939 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8940 RequiredType->getPointeeType())) ||
8941 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8942 mismatch = false;
8943 } else
8944 if (IsPointerAttr)
8945 mismatch = !isLayoutCompatible(Context,
8946 ArgumentType->getPointeeType(),
8947 RequiredType->getPointeeType());
8948 else
8949 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8950
8951 if (mismatch)
8952 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008953 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008954 << TypeInfo.LayoutCompatible << RequiredType
8955 << ArgumentExpr->getSourceRange()
8956 << TypeTagExpr->getSourceRange();
8957}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008958