blob: eb5b5890495711128113800916f39d7b60211253 [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"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000024#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000025#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000028#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000031#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000039#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000041#include <limits>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000042
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000044using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000045
Chris Lattnera26fb342009-02-18 17:49:48 +000046SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
47 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000048 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
49 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000050}
51
John McCallbebede42011-02-26 05:39:39 +000052/// Checks that a call expression's argument count is the desired number.
53/// This is useful when doing custom type-checking. Returns true on error.
54static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
55 unsigned argCount = call->getNumArgs();
56 if (argCount == desiredArgCount) return false;
57
58 if (argCount < desiredArgCount)
59 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
60 << 0 /*function call*/ << desiredArgCount << argCount
61 << call->getSourceRange();
62
63 // Highlight all the excess arguments.
64 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
65 call->getArg(argCount - 1)->getLocEnd());
66
67 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
68 << 0 /*function call*/ << desiredArgCount << argCount
69 << call->getArg(1)->getSourceRange();
70}
71
Julien Lerouge4a5b4442012-04-28 17:39:16 +000072/// Check that the first argument to __builtin_annotation is an integer
73/// and the second argument is a non-wide string literal.
74static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
75 if (checkArgCount(S, TheCall, 2))
76 return true;
77
78 // First argument should be an integer.
79 Expr *ValArg = TheCall->getArg(0);
80 QualType Ty = ValArg->getType();
81 if (!Ty->isIntegerType()) {
82 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
83 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000084 return true;
85 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000086
87 // Second argument should be a constant string.
88 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
89 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
90 if (!Literal || !Literal->isAscii()) {
91 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
92 << StrArg->getSourceRange();
93 return true;
94 }
95
96 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000097 return false;
98}
99
Richard Smith6cbd65d2013-07-11 02:27:57 +0000100/// Check that the argument to __builtin_addressof is a glvalue, and set the
101/// result type to the corresponding pointer type.
102static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
103 if (checkArgCount(S, TheCall, 1))
104 return true;
105
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000106 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000107 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
108 if (ResultType.isNull())
109 return true;
110
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000111 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000112 TheCall->setType(ResultType);
113 return false;
114}
115
John McCall03107a42015-10-29 20:48:01 +0000116static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
117 if (checkArgCount(S, TheCall, 3))
118 return true;
119
120 // First two arguments should be integers.
121 for (unsigned I = 0; I < 2; ++I) {
122 Expr *Arg = TheCall->getArg(I);
123 QualType Ty = Arg->getType();
124 if (!Ty->isIntegerType()) {
125 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
126 << Ty << Arg->getSourceRange();
127 return true;
128 }
129 }
130
131 // Third argument should be a pointer to a non-const integer.
132 // IRGen correctly handles volatile, restrict, and address spaces, and
133 // the other qualifiers aren't possible.
134 {
135 Expr *Arg = TheCall->getArg(2);
136 QualType Ty = Arg->getType();
137 const auto *PtrTy = Ty->getAs<PointerType>();
138 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
139 !PtrTy->getPointeeType().isConstQualified())) {
140 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
141 << Ty << Arg->getSourceRange();
142 return true;
143 }
144 }
145
146 return false;
147}
148
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000149static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
150 CallExpr *TheCall, unsigned SizeIdx,
151 unsigned DstSizeIdx) {
152 if (TheCall->getNumArgs() <= SizeIdx ||
153 TheCall->getNumArgs() <= DstSizeIdx)
154 return;
155
156 const Expr *SizeArg = TheCall->getArg(SizeIdx);
157 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
158
159 llvm::APSInt Size, DstSize;
160
161 // find out if both sizes are known at compile time
162 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
163 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
164 return;
165
166 if (Size.ule(DstSize))
167 return;
168
169 // confirmed overflow so generate the diagnostic.
170 IdentifierInfo *FnName = FDecl->getIdentifier();
171 SourceLocation SL = TheCall->getLocStart();
172 SourceRange SR = TheCall->getSourceRange();
173
174 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
175}
176
Peter Collingbournef7706832014-12-12 23:41:25 +0000177static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
178 if (checkArgCount(S, BuiltinCall, 2))
179 return true;
180
181 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
182 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
183 Expr *Call = BuiltinCall->getArg(0);
184 Expr *Chain = BuiltinCall->getArg(1);
185
186 if (Call->getStmtClass() != Stmt::CallExprClass) {
187 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
188 << Call->getSourceRange();
189 return true;
190 }
191
192 auto CE = cast<CallExpr>(Call);
193 if (CE->getCallee()->getType()->isBlockPointerType()) {
194 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
195 << Call->getSourceRange();
196 return true;
197 }
198
199 const Decl *TargetDecl = CE->getCalleeDecl();
200 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
201 if (FD->getBuiltinID()) {
202 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
203 << Call->getSourceRange();
204 return true;
205 }
206
207 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
208 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
209 << Call->getSourceRange();
210 return true;
211 }
212
213 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
214 if (ChainResult.isInvalid())
215 return true;
216 if (!ChainResult.get()->getType()->isPointerType()) {
217 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
218 << Chain->getSourceRange();
219 return true;
220 }
221
David Majnemerced8bdf2015-02-25 17:36:15 +0000222 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000223 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
224 QualType BuiltinTy = S.Context.getFunctionType(
225 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
226 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
227
228 Builtin =
229 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
230
231 BuiltinCall->setType(CE->getType());
232 BuiltinCall->setValueKind(CE->getValueKind());
233 BuiltinCall->setObjectKind(CE->getObjectKind());
234 BuiltinCall->setCallee(Builtin);
235 BuiltinCall->setArg(1, ChainResult.get());
236
237 return false;
238}
239
Reid Kleckner1d59f992015-01-22 01:36:17 +0000240static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
241 Scope::ScopeFlags NeededScopeFlags,
242 unsigned DiagID) {
243 // Scopes aren't available during instantiation. Fortunately, builtin
244 // functions cannot be template args so they cannot be formed through template
245 // instantiation. Therefore checking once during the parse is sufficient.
246 if (!SemaRef.ActiveTemplateInstantiations.empty())
247 return false;
248
249 Scope *S = SemaRef.getCurScope();
250 while (S && !S->isSEHExceptScope())
251 S = S->getParent();
252 if (!S || !(S->getFlags() & NeededScopeFlags)) {
253 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
254 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
255 << DRE->getDecl()->getIdentifier();
256 return true;
257 }
258
259 return false;
260}
261
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000262/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000263static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000264 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000265}
266
267/// Returns true if pipe element type is different from the pointer.
268static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
269 const Expr *Arg0 = Call->getArg(0);
270 // First argument type should always be pipe.
271 if (!Arg0->getType()->isPipeType()) {
272 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000273 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000274 return true;
275 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000276 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000277 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
278 // Validates the access qualifier is compatible with the call.
279 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
280 // read_only and write_only, and assumed to be read_only if no qualifier is
281 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000282 switch (Call->getDirectCallee()->getBuiltinID()) {
283 case Builtin::BIread_pipe:
284 case Builtin::BIreserve_read_pipe:
285 case Builtin::BIcommit_read_pipe:
286 case Builtin::BIwork_group_reserve_read_pipe:
287 case Builtin::BIsub_group_reserve_read_pipe:
288 case Builtin::BIwork_group_commit_read_pipe:
289 case Builtin::BIsub_group_commit_read_pipe:
290 if (!(!AccessQual || AccessQual->isReadOnly())) {
291 S.Diag(Arg0->getLocStart(),
292 diag::err_opencl_builtin_pipe_invalid_access_modifier)
293 << "read_only" << Arg0->getSourceRange();
294 return true;
295 }
296 break;
297 case Builtin::BIwrite_pipe:
298 case Builtin::BIreserve_write_pipe:
299 case Builtin::BIcommit_write_pipe:
300 case Builtin::BIwork_group_reserve_write_pipe:
301 case Builtin::BIsub_group_reserve_write_pipe:
302 case Builtin::BIwork_group_commit_write_pipe:
303 case Builtin::BIsub_group_commit_write_pipe:
304 if (!(AccessQual && AccessQual->isWriteOnly())) {
305 S.Diag(Arg0->getLocStart(),
306 diag::err_opencl_builtin_pipe_invalid_access_modifier)
307 << "write_only" << Arg0->getSourceRange();
308 return true;
309 }
310 break;
311 default:
312 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000313 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000314 return false;
315}
316
317/// Returns true if pipe element type is different from the pointer.
318static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
319 const Expr *Arg0 = Call->getArg(0);
320 const Expr *ArgIdx = Call->getArg(Idx);
321 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000322 const QualType EltTy = PipeTy->getElementType();
323 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000324 // The Idx argument should be a pointer and the type of the pointer and
325 // the type of pipe element should also be the same.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000326 if (!ArgTy || S.Context.hasSameType(EltTy, ArgTy->getPointeeType())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000327 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000328 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000329 << ArgIdx->getSourceRange();
330 return true;
331 }
332 return false;
333}
334
335// \brief Performs semantic analysis for the read/write_pipe call.
336// \param S Reference to the semantic analyzer.
337// \param Call A pointer to the builtin call.
338// \return True if a semantic error has been found, false otherwise.
339static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000340 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
341 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000342 switch (Call->getNumArgs()) {
343 case 2: {
344 if (checkOpenCLPipeArg(S, Call))
345 return true;
346 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000347 // read/write_pipe(pipe T, T*).
348 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000349 if (checkOpenCLPipePacketType(S, Call, 1))
350 return true;
351 } break;
352
353 case 4: {
354 if (checkOpenCLPipeArg(S, Call))
355 return true;
356 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000357 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
358 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000359 if (!Call->getArg(1)->getType()->isReserveIDT()) {
360 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000361 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000362 << Call->getArg(1)->getSourceRange();
363 return true;
364 }
365
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000366 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000367 const Expr *Arg2 = Call->getArg(2);
368 if (!Arg2->getType()->isIntegerType() &&
369 !Arg2->getType()->isUnsignedIntegerType()) {
370 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000371 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000372 << Arg2->getSourceRange();
373 return true;
374 }
375
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000376 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000377 if (checkOpenCLPipePacketType(S, Call, 3))
378 return true;
379 } break;
380 default:
381 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000382 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000383 return true;
384 }
385
386 return false;
387}
388
389// \brief Performs a semantic analysis on the {work_group_/sub_group_
390// /_}reserve_{read/write}_pipe
391// \param S Reference to the semantic analyzer.
392// \param Call The call to the builtin function to be analyzed.
393// \return True if a semantic error was found, false otherwise.
394static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
395 if (checkArgCount(S, Call, 2))
396 return true;
397
398 if (checkOpenCLPipeArg(S, Call))
399 return true;
400
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000401 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000402 if (!Call->getArg(1)->getType()->isIntegerType() &&
403 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
404 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000405 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000406 << Call->getArg(1)->getSourceRange();
407 return true;
408 }
409
410 return false;
411}
412
413// \brief Performs a semantic analysis on {work_group_/sub_group_
414// /_}commit_{read/write}_pipe
415// \param S Reference to the semantic analyzer.
416// \param Call The call to the builtin function to be analyzed.
417// \return True if a semantic error was found, false otherwise.
418static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
419 if (checkArgCount(S, Call, 2))
420 return true;
421
422 if (checkOpenCLPipeArg(S, Call))
423 return true;
424
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000425 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000426 if (!Call->getArg(1)->getType()->isReserveIDT()) {
427 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000428 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000429 << Call->getArg(1)->getSourceRange();
430 return true;
431 }
432
433 return false;
434}
435
436// \brief Performs a semantic analysis on the call to built-in Pipe
437// Query Functions.
438// \param S Reference to the semantic analyzer.
439// \param Call The call to the builtin function to be analyzed.
440// \return True if a semantic error was found, false otherwise.
441static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
442 if (checkArgCount(S, Call, 1))
443 return true;
444
445 if (!Call->getArg(0)->getType()->isPipeType()) {
446 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000447 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000448 return true;
449 }
450
451 return false;
452}
453
John McCalldadc5752010-08-24 06:29:42 +0000454ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000455Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
456 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000457 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000458
Chris Lattner3be167f2010-10-01 23:23:24 +0000459 // Find out if any arguments are required to be integer constant expressions.
460 unsigned ICEArguments = 0;
461 ASTContext::GetBuiltinTypeError Error;
462 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
463 if (Error != ASTContext::GE_None)
464 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
465
466 // If any arguments are required to be ICE's, check and diagnose.
467 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
468 // Skip arguments not required to be ICE's.
469 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
470
471 llvm::APSInt Result;
472 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
473 return true;
474 ICEArguments &= ~(1 << ArgNo);
475 }
476
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000477 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000478 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000479 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000480 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000481 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000482 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000483 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000484 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000485 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000486 if (SemaBuiltinVAStart(TheCall))
487 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000488 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000489 case Builtin::BI__va_start: {
490 switch (Context.getTargetInfo().getTriple().getArch()) {
491 case llvm::Triple::arm:
492 case llvm::Triple::thumb:
493 if (SemaBuiltinVAStartARM(TheCall))
494 return ExprError();
495 break;
496 default:
497 if (SemaBuiltinVAStart(TheCall))
498 return ExprError();
499 break;
500 }
501 break;
502 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000503 case Builtin::BI__builtin_isgreater:
504 case Builtin::BI__builtin_isgreaterequal:
505 case Builtin::BI__builtin_isless:
506 case Builtin::BI__builtin_islessequal:
507 case Builtin::BI__builtin_islessgreater:
508 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000509 if (SemaBuiltinUnorderedCompare(TheCall))
510 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000511 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000512 case Builtin::BI__builtin_fpclassify:
513 if (SemaBuiltinFPClassification(TheCall, 6))
514 return ExprError();
515 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000516 case Builtin::BI__builtin_isfinite:
517 case Builtin::BI__builtin_isinf:
518 case Builtin::BI__builtin_isinf_sign:
519 case Builtin::BI__builtin_isnan:
520 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000521 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000522 return ExprError();
523 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000524 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000525 return SemaBuiltinShuffleVector(TheCall);
526 // TheCall will be freed by the smart pointer here, but that's fine, since
527 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000528 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000529 if (SemaBuiltinPrefetch(TheCall))
530 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000531 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000532 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000533 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000534 if (SemaBuiltinAssume(TheCall))
535 return ExprError();
536 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000537 case Builtin::BI__builtin_assume_aligned:
538 if (SemaBuiltinAssumeAligned(TheCall))
539 return ExprError();
540 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000541 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000542 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000543 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000544 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000545 case Builtin::BI__builtin_longjmp:
546 if (SemaBuiltinLongjmp(TheCall))
547 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000548 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000549 case Builtin::BI__builtin_setjmp:
550 if (SemaBuiltinSetjmp(TheCall))
551 return ExprError();
552 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000553 case Builtin::BI_setjmp:
554 case Builtin::BI_setjmpex:
555 if (checkArgCount(*this, TheCall, 1))
556 return true;
557 break;
John McCallbebede42011-02-26 05:39:39 +0000558
559 case Builtin::BI__builtin_classify_type:
560 if (checkArgCount(*this, TheCall, 1)) return true;
561 TheCall->setType(Context.IntTy);
562 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000563 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000564 if (checkArgCount(*this, TheCall, 1)) return true;
565 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000566 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000567 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000568 case Builtin::BI__sync_fetch_and_add_1:
569 case Builtin::BI__sync_fetch_and_add_2:
570 case Builtin::BI__sync_fetch_and_add_4:
571 case Builtin::BI__sync_fetch_and_add_8:
572 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000573 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000574 case Builtin::BI__sync_fetch_and_sub_1:
575 case Builtin::BI__sync_fetch_and_sub_2:
576 case Builtin::BI__sync_fetch_and_sub_4:
577 case Builtin::BI__sync_fetch_and_sub_8:
578 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000579 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000580 case Builtin::BI__sync_fetch_and_or_1:
581 case Builtin::BI__sync_fetch_and_or_2:
582 case Builtin::BI__sync_fetch_and_or_4:
583 case Builtin::BI__sync_fetch_and_or_8:
584 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000585 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000586 case Builtin::BI__sync_fetch_and_and_1:
587 case Builtin::BI__sync_fetch_and_and_2:
588 case Builtin::BI__sync_fetch_and_and_4:
589 case Builtin::BI__sync_fetch_and_and_8:
590 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000591 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000592 case Builtin::BI__sync_fetch_and_xor_1:
593 case Builtin::BI__sync_fetch_and_xor_2:
594 case Builtin::BI__sync_fetch_and_xor_4:
595 case Builtin::BI__sync_fetch_and_xor_8:
596 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000597 case Builtin::BI__sync_fetch_and_nand:
598 case Builtin::BI__sync_fetch_and_nand_1:
599 case Builtin::BI__sync_fetch_and_nand_2:
600 case Builtin::BI__sync_fetch_and_nand_4:
601 case Builtin::BI__sync_fetch_and_nand_8:
602 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000603 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000604 case Builtin::BI__sync_add_and_fetch_1:
605 case Builtin::BI__sync_add_and_fetch_2:
606 case Builtin::BI__sync_add_and_fetch_4:
607 case Builtin::BI__sync_add_and_fetch_8:
608 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000609 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000610 case Builtin::BI__sync_sub_and_fetch_1:
611 case Builtin::BI__sync_sub_and_fetch_2:
612 case Builtin::BI__sync_sub_and_fetch_4:
613 case Builtin::BI__sync_sub_and_fetch_8:
614 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000615 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000616 case Builtin::BI__sync_and_and_fetch_1:
617 case Builtin::BI__sync_and_and_fetch_2:
618 case Builtin::BI__sync_and_and_fetch_4:
619 case Builtin::BI__sync_and_and_fetch_8:
620 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000621 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000622 case Builtin::BI__sync_or_and_fetch_1:
623 case Builtin::BI__sync_or_and_fetch_2:
624 case Builtin::BI__sync_or_and_fetch_4:
625 case Builtin::BI__sync_or_and_fetch_8:
626 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000627 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000628 case Builtin::BI__sync_xor_and_fetch_1:
629 case Builtin::BI__sync_xor_and_fetch_2:
630 case Builtin::BI__sync_xor_and_fetch_4:
631 case Builtin::BI__sync_xor_and_fetch_8:
632 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000633 case Builtin::BI__sync_nand_and_fetch:
634 case Builtin::BI__sync_nand_and_fetch_1:
635 case Builtin::BI__sync_nand_and_fetch_2:
636 case Builtin::BI__sync_nand_and_fetch_4:
637 case Builtin::BI__sync_nand_and_fetch_8:
638 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000639 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000640 case Builtin::BI__sync_val_compare_and_swap_1:
641 case Builtin::BI__sync_val_compare_and_swap_2:
642 case Builtin::BI__sync_val_compare_and_swap_4:
643 case Builtin::BI__sync_val_compare_and_swap_8:
644 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000645 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000646 case Builtin::BI__sync_bool_compare_and_swap_1:
647 case Builtin::BI__sync_bool_compare_and_swap_2:
648 case Builtin::BI__sync_bool_compare_and_swap_4:
649 case Builtin::BI__sync_bool_compare_and_swap_8:
650 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000651 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000652 case Builtin::BI__sync_lock_test_and_set_1:
653 case Builtin::BI__sync_lock_test_and_set_2:
654 case Builtin::BI__sync_lock_test_and_set_4:
655 case Builtin::BI__sync_lock_test_and_set_8:
656 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000657 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000658 case Builtin::BI__sync_lock_release_1:
659 case Builtin::BI__sync_lock_release_2:
660 case Builtin::BI__sync_lock_release_4:
661 case Builtin::BI__sync_lock_release_8:
662 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000663 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000664 case Builtin::BI__sync_swap_1:
665 case Builtin::BI__sync_swap_2:
666 case Builtin::BI__sync_swap_4:
667 case Builtin::BI__sync_swap_8:
668 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000669 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000670 case Builtin::BI__builtin_nontemporal_load:
671 case Builtin::BI__builtin_nontemporal_store:
672 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000673#define BUILTIN(ID, TYPE, ATTRS)
674#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
675 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000676 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000677#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000678 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000679 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000680 return ExprError();
681 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000682 case Builtin::BI__builtin_addressof:
683 if (SemaBuiltinAddressof(*this, TheCall))
684 return ExprError();
685 break;
John McCall03107a42015-10-29 20:48:01 +0000686 case Builtin::BI__builtin_add_overflow:
687 case Builtin::BI__builtin_sub_overflow:
688 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000689 if (SemaBuiltinOverflow(*this, TheCall))
690 return ExprError();
691 break;
Richard Smith760520b2014-06-03 23:27:44 +0000692 case Builtin::BI__builtin_operator_new:
693 case Builtin::BI__builtin_operator_delete:
694 if (!getLangOpts().CPlusPlus) {
695 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
696 << (BuiltinID == Builtin::BI__builtin_operator_new
697 ? "__builtin_operator_new"
698 : "__builtin_operator_delete")
699 << "C++";
700 return ExprError();
701 }
702 // CodeGen assumes it can find the global new and delete to call,
703 // so ensure that they are declared.
704 DeclareGlobalNewDelete();
705 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000706
707 // check secure string manipulation functions where overflows
708 // are detectable at compile time
709 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000710 case Builtin::BI__builtin___memmove_chk:
711 case Builtin::BI__builtin___memset_chk:
712 case Builtin::BI__builtin___strlcat_chk:
713 case Builtin::BI__builtin___strlcpy_chk:
714 case Builtin::BI__builtin___strncat_chk:
715 case Builtin::BI__builtin___strncpy_chk:
716 case Builtin::BI__builtin___stpncpy_chk:
717 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
718 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000719 case Builtin::BI__builtin___memccpy_chk:
720 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
721 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000722 case Builtin::BI__builtin___snprintf_chk:
723 case Builtin::BI__builtin___vsnprintf_chk:
724 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
725 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000726 case Builtin::BI__builtin_call_with_static_chain:
727 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
728 return ExprError();
729 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000730 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000731 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000732 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
733 diag::err_seh___except_block))
734 return ExprError();
735 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000736 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000737 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000738 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
739 diag::err_seh___except_filter))
740 return ExprError();
741 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +0000742 case Builtin::BI__GetExceptionInfo:
743 if (checkArgCount(*this, TheCall, 1))
744 return ExprError();
745
746 if (CheckCXXThrowOperand(
747 TheCall->getLocStart(),
748 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
749 TheCall))
750 return ExprError();
751
752 TheCall->setType(Context.VoidPtrTy);
753 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000754 case Builtin::BIread_pipe:
755 case Builtin::BIwrite_pipe:
756 // Since those two functions are declared with var args, we need a semantic
757 // check for the argument.
758 if (SemaBuiltinRWPipe(*this, TheCall))
759 return ExprError();
760 break;
761 case Builtin::BIreserve_read_pipe:
762 case Builtin::BIreserve_write_pipe:
763 case Builtin::BIwork_group_reserve_read_pipe:
764 case Builtin::BIwork_group_reserve_write_pipe:
765 case Builtin::BIsub_group_reserve_read_pipe:
766 case Builtin::BIsub_group_reserve_write_pipe:
767 if (SemaBuiltinReserveRWPipe(*this, TheCall))
768 return ExprError();
769 // Since return type of reserve_read/write_pipe built-in function is
770 // reserve_id_t, which is not defined in the builtin def file , we used int
771 // as return type and need to override the return type of these functions.
772 TheCall->setType(Context.OCLReserveIDTy);
773 break;
774 case Builtin::BIcommit_read_pipe:
775 case Builtin::BIcommit_write_pipe:
776 case Builtin::BIwork_group_commit_read_pipe:
777 case Builtin::BIwork_group_commit_write_pipe:
778 case Builtin::BIsub_group_commit_read_pipe:
779 case Builtin::BIsub_group_commit_write_pipe:
780 if (SemaBuiltinCommitRWPipe(*this, TheCall))
781 return ExprError();
782 break;
783 case Builtin::BIget_pipe_num_packets:
784 case Builtin::BIget_pipe_max_packets:
785 if (SemaBuiltinPipePackets(*this, TheCall))
786 return ExprError();
787 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000788 }
Richard Smith760520b2014-06-03 23:27:44 +0000789
Nate Begeman4904e322010-06-08 02:47:44 +0000790 // Since the target specific builtins for each arch overlap, only check those
791 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +0000792 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000793 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000794 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000795 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000796 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000797 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000798 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
799 return ExprError();
800 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000801 case llvm::Triple::aarch64:
802 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000803 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000804 return ExprError();
805 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000806 case llvm::Triple::mips:
807 case llvm::Triple::mipsel:
808 case llvm::Triple::mips64:
809 case llvm::Triple::mips64el:
810 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
811 return ExprError();
812 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000813 case llvm::Triple::systemz:
814 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
815 return ExprError();
816 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000817 case llvm::Triple::x86:
818 case llvm::Triple::x86_64:
819 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
820 return ExprError();
821 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000822 case llvm::Triple::ppc:
823 case llvm::Triple::ppc64:
824 case llvm::Triple::ppc64le:
825 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
826 return ExprError();
827 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000828 default:
829 break;
830 }
831 }
832
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000833 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000834}
835
Nate Begeman91e1fea2010-06-14 05:21:25 +0000836// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000837static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000838 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000839 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000840 switch (Type.getEltType()) {
841 case NeonTypeFlags::Int8:
842 case NeonTypeFlags::Poly8:
843 return shift ? 7 : (8 << IsQuad) - 1;
844 case NeonTypeFlags::Int16:
845 case NeonTypeFlags::Poly16:
846 return shift ? 15 : (4 << IsQuad) - 1;
847 case NeonTypeFlags::Int32:
848 return shift ? 31 : (2 << IsQuad) - 1;
849 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000850 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000851 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000852 case NeonTypeFlags::Poly128:
853 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000854 case NeonTypeFlags::Float16:
855 assert(!shift && "cannot shift float types!");
856 return (4 << IsQuad) - 1;
857 case NeonTypeFlags::Float32:
858 assert(!shift && "cannot shift float types!");
859 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000860 case NeonTypeFlags::Float64:
861 assert(!shift && "cannot shift float types!");
862 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000863 }
David Blaikie8a40f702012-01-17 06:56:22 +0000864 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000865}
866
Bob Wilsone4d77232011-11-08 05:04:11 +0000867/// getNeonEltType - Return the QualType corresponding to the elements of
868/// the vector type specified by the NeonTypeFlags. This is used to check
869/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000870static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000871 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000872 switch (Flags.getEltType()) {
873 case NeonTypeFlags::Int8:
874 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
875 case NeonTypeFlags::Int16:
876 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
877 case NeonTypeFlags::Int32:
878 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
879 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000880 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000881 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
882 else
883 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
884 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000885 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000886 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000887 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000888 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000889 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000890 if (IsInt64Long)
891 return Context.UnsignedLongTy;
892 else
893 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000894 case NeonTypeFlags::Poly128:
895 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000896 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000897 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000898 case NeonTypeFlags::Float32:
899 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000900 case NeonTypeFlags::Float64:
901 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000902 }
David Blaikie8a40f702012-01-17 06:56:22 +0000903 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000904}
905
Tim Northover12670412014-02-19 10:37:05 +0000906bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000907 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000908 uint64_t mask = 0;
909 unsigned TV = 0;
910 int PtrArgNum = -1;
911 bool HasConstPtr = false;
912 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000913#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000914#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000915#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000916 }
917
918 // For NEON intrinsics which are overloaded on vector element type, validate
919 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000920 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000921 if (mask) {
922 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
923 return true;
924
925 TV = Result.getLimitedValue(64);
926 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
927 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000928 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000929 }
930
931 if (PtrArgNum >= 0) {
932 // Check that pointer arguments have the specified type.
933 Expr *Arg = TheCall->getArg(PtrArgNum);
934 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
935 Arg = ICE->getSubExpr();
936 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
937 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000938
Tim Northovera2ee4332014-03-29 15:09:45 +0000939 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000940 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000941 bool IsInt64Long =
942 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
943 QualType EltTy =
944 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000945 if (HasConstPtr)
946 EltTy = EltTy.withConst();
947 QualType LHSTy = Context.getPointerType(EltTy);
948 AssignConvertType ConvTy;
949 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
950 if (RHS.isInvalid())
951 return true;
952 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
953 RHS.get(), AA_Assigning))
954 return true;
955 }
956
957 // For NEON intrinsics which take an immediate value as part of the
958 // instruction, range check them here.
959 unsigned i = 0, l = 0, u = 0;
960 switch (BuiltinID) {
961 default:
962 return false;
Tim Northover12670412014-02-19 10:37:05 +0000963#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000964#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000965#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000966 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000967
Richard Sandiford28940af2014-04-16 08:47:51 +0000968 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000969}
970
Tim Northovera2ee4332014-03-29 15:09:45 +0000971bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
972 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000973 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000974 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000975 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000976 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000977 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000978 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
979 BuiltinID == AArch64::BI__builtin_arm_strex ||
980 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000981 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000982 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000983 BuiltinID == ARM::BI__builtin_arm_ldaex ||
984 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
985 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000986
987 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
988
989 // Ensure that we have the proper number of arguments.
990 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
991 return true;
992
993 // Inspect the pointer argument of the atomic builtin. This should always be
994 // a pointer type, whose element is an integral scalar or pointer type.
995 // Because it is a pointer type, we don't have to worry about any implicit
996 // casts here.
997 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
998 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
999 if (PointerArgRes.isInvalid())
1000 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001001 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001002
1003 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1004 if (!pointerType) {
1005 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1006 << PointerArg->getType() << PointerArg->getSourceRange();
1007 return true;
1008 }
1009
1010 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1011 // task is to insert the appropriate casts into the AST. First work out just
1012 // what the appropriate type is.
1013 QualType ValType = pointerType->getPointeeType();
1014 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1015 if (IsLdrex)
1016 AddrType.addConst();
1017
1018 // Issue a warning if the cast is dodgy.
1019 CastKind CastNeeded = CK_NoOp;
1020 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1021 CastNeeded = CK_BitCast;
1022 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1023 << PointerArg->getType()
1024 << Context.getPointerType(AddrType)
1025 << AA_Passing << PointerArg->getSourceRange();
1026 }
1027
1028 // Finally, do the cast and replace the argument with the corrected version.
1029 AddrType = Context.getPointerType(AddrType);
1030 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1031 if (PointerArgRes.isInvalid())
1032 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001033 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001034
1035 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1036
1037 // In general, we allow ints, floats and pointers to be loaded and stored.
1038 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1039 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1040 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1041 << PointerArg->getType() << PointerArg->getSourceRange();
1042 return true;
1043 }
1044
1045 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001046 if (Context.getTypeSize(ValType) > MaxWidth) {
1047 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001048 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1049 << PointerArg->getType() << PointerArg->getSourceRange();
1050 return true;
1051 }
1052
1053 switch (ValType.getObjCLifetime()) {
1054 case Qualifiers::OCL_None:
1055 case Qualifiers::OCL_ExplicitNone:
1056 // okay
1057 break;
1058
1059 case Qualifiers::OCL_Weak:
1060 case Qualifiers::OCL_Strong:
1061 case Qualifiers::OCL_Autoreleasing:
1062 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1063 << ValType << PointerArg->getSourceRange();
1064 return true;
1065 }
1066
Tim Northover6aacd492013-07-16 09:47:53 +00001067 if (IsLdrex) {
1068 TheCall->setType(ValType);
1069 return false;
1070 }
1071
1072 // Initialize the argument to be stored.
1073 ExprResult ValArg = TheCall->getArg(0);
1074 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1075 Context, ValType, /*consume*/ false);
1076 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1077 if (ValArg.isInvalid())
1078 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001079 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001080
1081 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1082 // but the custom checker bypasses all default analysis.
1083 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001084 return false;
1085}
1086
Nate Begeman4904e322010-06-08 02:47:44 +00001087bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001088 llvm::APSInt Result;
1089
Tim Northover6aacd492013-07-16 09:47:53 +00001090 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001091 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1092 BuiltinID == ARM::BI__builtin_arm_strex ||
1093 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001094 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001095 }
1096
Yi Kong26d104a2014-08-13 19:18:14 +00001097 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1098 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1099 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1100 }
1101
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001102 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1103 BuiltinID == ARM::BI__builtin_arm_wsr64)
1104 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1105
1106 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1107 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1108 BuiltinID == ARM::BI__builtin_arm_wsr ||
1109 BuiltinID == ARM::BI__builtin_arm_wsrp)
1110 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1111
Tim Northover12670412014-02-19 10:37:05 +00001112 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1113 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001114
Yi Kong4efadfb2014-07-03 16:01:25 +00001115 // For intrinsics which take an immediate value as part of the instruction,
1116 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001117 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001118 switch (BuiltinID) {
1119 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001120 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1121 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001122 case ARM::BI__builtin_arm_vcvtr_f:
1123 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001124 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001125 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001126 case ARM::BI__builtin_arm_isb:
1127 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001128 }
Nate Begemand773fe62010-06-13 04:47:52 +00001129
Nate Begemanf568b072010-08-03 21:32:34 +00001130 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001131 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001132}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001133
Tim Northover573cbee2014-05-24 12:52:07 +00001134bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001135 CallExpr *TheCall) {
1136 llvm::APSInt Result;
1137
Tim Northover573cbee2014-05-24 12:52:07 +00001138 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001139 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1140 BuiltinID == AArch64::BI__builtin_arm_strex ||
1141 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001142 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1143 }
1144
Yi Konga5548432014-08-13 19:18:20 +00001145 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1146 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1147 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1148 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1149 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1150 }
1151
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001152 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1153 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1154 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
1155
1156 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1157 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1158 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1159 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1160 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1161
Tim Northovera2ee4332014-03-29 15:09:45 +00001162 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1163 return true;
1164
Yi Kong19a29ac2014-07-17 10:52:06 +00001165 // For intrinsics which take an immediate value as part of the instruction,
1166 // range check them here.
1167 unsigned i = 0, l = 0, u = 0;
1168 switch (BuiltinID) {
1169 default: return false;
1170 case AArch64::BI__builtin_arm_dmb:
1171 case AArch64::BI__builtin_arm_dsb:
1172 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1173 }
1174
Yi Kong19a29ac2014-07-17 10:52:06 +00001175 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001176}
1177
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001178bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1179 unsigned i = 0, l = 0, u = 0;
1180 switch (BuiltinID) {
1181 default: return false;
1182 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1183 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001184 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1185 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1186 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1187 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1188 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001189 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001190
Richard Sandiford28940af2014-04-16 08:47:51 +00001191 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001192}
1193
Kit Bartone50adcb2015-03-30 19:40:59 +00001194bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1195 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001196 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1197 BuiltinID == PPC::BI__builtin_divdeu ||
1198 BuiltinID == PPC::BI__builtin_bpermd;
1199 bool IsTarget64Bit = Context.getTargetInfo()
1200 .getTypeWidth(Context
1201 .getTargetInfo()
1202 .getIntPtrType()) == 64;
1203 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1204 BuiltinID == PPC::BI__builtin_divweu ||
1205 BuiltinID == PPC::BI__builtin_divde ||
1206 BuiltinID == PPC::BI__builtin_divdeu;
1207
1208 if (Is64BitBltin && !IsTarget64Bit)
1209 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1210 << TheCall->getSourceRange();
1211
1212 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1213 (BuiltinID == PPC::BI__builtin_bpermd &&
1214 !Context.getTargetInfo().hasFeature("bpermd")))
1215 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1216 << TheCall->getSourceRange();
1217
Kit Bartone50adcb2015-03-30 19:40:59 +00001218 switch (BuiltinID) {
1219 default: return false;
1220 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1221 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1222 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1223 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1224 case PPC::BI__builtin_tbegin:
1225 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1226 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1227 case PPC::BI__builtin_tabortwc:
1228 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1229 case PPC::BI__builtin_tabortwci:
1230 case PPC::BI__builtin_tabortdci:
1231 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1232 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1233 }
1234 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1235}
1236
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001237bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1238 CallExpr *TheCall) {
1239 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1240 Expr *Arg = TheCall->getArg(0);
1241 llvm::APSInt AbortCode(32);
1242 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1243 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1244 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1245 << Arg->getSourceRange();
1246 }
1247
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001248 // For intrinsics which take an immediate value as part of the instruction,
1249 // range check them here.
1250 unsigned i = 0, l = 0, u = 0;
1251 switch (BuiltinID) {
1252 default: return false;
1253 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1254 case SystemZ::BI__builtin_s390_verimb:
1255 case SystemZ::BI__builtin_s390_verimh:
1256 case SystemZ::BI__builtin_s390_verimf:
1257 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1258 case SystemZ::BI__builtin_s390_vfaeb:
1259 case SystemZ::BI__builtin_s390_vfaeh:
1260 case SystemZ::BI__builtin_s390_vfaef:
1261 case SystemZ::BI__builtin_s390_vfaebs:
1262 case SystemZ::BI__builtin_s390_vfaehs:
1263 case SystemZ::BI__builtin_s390_vfaefs:
1264 case SystemZ::BI__builtin_s390_vfaezb:
1265 case SystemZ::BI__builtin_s390_vfaezh:
1266 case SystemZ::BI__builtin_s390_vfaezf:
1267 case SystemZ::BI__builtin_s390_vfaezbs:
1268 case SystemZ::BI__builtin_s390_vfaezhs:
1269 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1270 case SystemZ::BI__builtin_s390_vfidb:
1271 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1272 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1273 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1274 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1275 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1276 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1277 case SystemZ::BI__builtin_s390_vstrcb:
1278 case SystemZ::BI__builtin_s390_vstrch:
1279 case SystemZ::BI__builtin_s390_vstrcf:
1280 case SystemZ::BI__builtin_s390_vstrczb:
1281 case SystemZ::BI__builtin_s390_vstrczh:
1282 case SystemZ::BI__builtin_s390_vstrczf:
1283 case SystemZ::BI__builtin_s390_vstrcbs:
1284 case SystemZ::BI__builtin_s390_vstrchs:
1285 case SystemZ::BI__builtin_s390_vstrcfs:
1286 case SystemZ::BI__builtin_s390_vstrczbs:
1287 case SystemZ::BI__builtin_s390_vstrczhs:
1288 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1289 }
1290 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001291}
1292
Craig Topper5ba2c502015-11-07 08:08:31 +00001293/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1294/// This checks that the target supports __builtin_cpu_supports and
1295/// that the string argument is constant and valid.
1296static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1297 Expr *Arg = TheCall->getArg(0);
1298
1299 // Check if the argument is a string literal.
1300 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1301 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1302 << Arg->getSourceRange();
1303
1304 // Check the contents of the string.
1305 StringRef Feature =
1306 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1307 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1308 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1309 << Arg->getSourceRange();
1310 return false;
1311}
1312
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001313bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001314 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001315 switch (BuiltinID) {
Richard Trieucc3949d2016-02-18 22:34:54 +00001316 default:
1317 return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001318 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001319 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001320 case X86::BI__builtin_ms_va_start:
1321 return SemaBuiltinMSVAStart(TheCall);
Richard Trieucc3949d2016-02-18 22:34:54 +00001322 case X86::BI_mm_prefetch:
1323 i = 1;
1324 l = 0;
1325 u = 3;
1326 break;
1327 case X86::BI__builtin_ia32_sha1rnds4:
1328 i = 2;
1329 l = 0;
1330 u = 3;
1331 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001332 case X86::BI__builtin_ia32_vpermil2pd:
1333 case X86::BI__builtin_ia32_vpermil2pd256:
1334 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001335 case X86::BI__builtin_ia32_vpermil2ps256:
1336 i = 3;
1337 l = 0;
1338 u = 3;
1339 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001340 case X86::BI__builtin_ia32_cmpb128_mask:
1341 case X86::BI__builtin_ia32_cmpw128_mask:
1342 case X86::BI__builtin_ia32_cmpd128_mask:
1343 case X86::BI__builtin_ia32_cmpq128_mask:
1344 case X86::BI__builtin_ia32_cmpb256_mask:
1345 case X86::BI__builtin_ia32_cmpw256_mask:
1346 case X86::BI__builtin_ia32_cmpd256_mask:
1347 case X86::BI__builtin_ia32_cmpq256_mask:
1348 case X86::BI__builtin_ia32_cmpb512_mask:
1349 case X86::BI__builtin_ia32_cmpw512_mask:
1350 case X86::BI__builtin_ia32_cmpd512_mask:
1351 case X86::BI__builtin_ia32_cmpq512_mask:
1352 case X86::BI__builtin_ia32_ucmpb128_mask:
1353 case X86::BI__builtin_ia32_ucmpw128_mask:
1354 case X86::BI__builtin_ia32_ucmpd128_mask:
1355 case X86::BI__builtin_ia32_ucmpq128_mask:
1356 case X86::BI__builtin_ia32_ucmpb256_mask:
1357 case X86::BI__builtin_ia32_ucmpw256_mask:
1358 case X86::BI__builtin_ia32_ucmpd256_mask:
1359 case X86::BI__builtin_ia32_ucmpq256_mask:
1360 case X86::BI__builtin_ia32_ucmpb512_mask:
1361 case X86::BI__builtin_ia32_ucmpw512_mask:
1362 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001363 case X86::BI__builtin_ia32_ucmpq512_mask:
1364 i = 2;
1365 l = 0;
1366 u = 7;
1367 break;
Craig Topper16015252015-01-31 06:31:23 +00001368 case X86::BI__builtin_ia32_roundps:
1369 case X86::BI__builtin_ia32_roundpd:
1370 case X86::BI__builtin_ia32_roundps256:
Richard Trieucc3949d2016-02-18 22:34:54 +00001371 case X86::BI__builtin_ia32_roundpd256:
1372 i = 1;
1373 l = 0;
1374 u = 15;
1375 break;
Craig Topper16015252015-01-31 06:31:23 +00001376 case X86::BI__builtin_ia32_roundss:
Richard Trieucc3949d2016-02-18 22:34:54 +00001377 case X86::BI__builtin_ia32_roundsd:
1378 i = 2;
1379 l = 0;
1380 u = 15;
1381 break;
Craig Topper16015252015-01-31 06:31:23 +00001382 case X86::BI__builtin_ia32_cmpps:
1383 case X86::BI__builtin_ia32_cmpss:
1384 case X86::BI__builtin_ia32_cmppd:
1385 case X86::BI__builtin_ia32_cmpsd:
1386 case X86::BI__builtin_ia32_cmpps256:
1387 case X86::BI__builtin_ia32_cmppd256:
1388 case X86::BI__builtin_ia32_cmpps512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001389 case X86::BI__builtin_ia32_cmppd512_mask:
1390 i = 2;
1391 l = 0;
1392 u = 31;
1393 break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001394 case X86::BI__builtin_ia32_vpcomub:
1395 case X86::BI__builtin_ia32_vpcomuw:
1396 case X86::BI__builtin_ia32_vpcomud:
1397 case X86::BI__builtin_ia32_vpcomuq:
1398 case X86::BI__builtin_ia32_vpcomb:
1399 case X86::BI__builtin_ia32_vpcomw:
1400 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001401 case X86::BI__builtin_ia32_vpcomq:
1402 i = 2;
1403 l = 0;
1404 u = 7;
1405 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001406 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001407 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001408}
1409
Richard Smith55ce3522012-06-25 20:30:08 +00001410/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1411/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1412/// Returns true when the format fits the function and the FormatStringInfo has
1413/// been populated.
1414bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1415 FormatStringInfo *FSI) {
1416 FSI->HasVAListArg = Format->getFirstArg() == 0;
1417 FSI->FormatIdx = Format->getFormatIdx() - 1;
1418 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001419
Richard Smith55ce3522012-06-25 20:30:08 +00001420 // The way the format attribute works in GCC, the implicit this argument
1421 // of member functions is counted. However, it doesn't appear in our own
1422 // lists, so decrement format_idx in that case.
1423 if (IsCXXMember) {
1424 if(FSI->FormatIdx == 0)
1425 return false;
1426 --FSI->FormatIdx;
1427 if (FSI->FirstDataArg != 0)
1428 --FSI->FirstDataArg;
1429 }
1430 return true;
1431}
Mike Stump11289f42009-09-09 15:08:12 +00001432
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001433/// Checks if a the given expression evaluates to null.
1434///
1435/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001436static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001437 // If the expression has non-null type, it doesn't evaluate to null.
1438 if (auto nullability
1439 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1440 if (*nullability == NullabilityKind::NonNull)
1441 return false;
1442 }
1443
Ted Kremeneka146db32014-01-17 06:24:47 +00001444 // As a special case, transparent unions initialized with zero are
1445 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001446 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001447 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1448 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001449 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001450 if (const InitListExpr *ILE =
1451 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001452 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001453 }
1454
1455 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001456 return (!Expr->isValueDependent() &&
1457 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1458 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001459}
1460
1461static void CheckNonNullArgument(Sema &S,
1462 const Expr *ArgExpr,
1463 SourceLocation CallSiteLoc) {
1464 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001465 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1466 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001467}
1468
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001469bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1470 FormatStringInfo FSI;
1471 if ((GetFormatStringType(Format) == FST_NSString) &&
1472 getFormatStringInfo(Format, false, &FSI)) {
1473 Idx = FSI.FormatIdx;
1474 return true;
1475 }
1476 return false;
1477}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001478/// \brief Diagnose use of %s directive in an NSString which is being passed
1479/// as formatting string to formatting method.
1480static void
1481DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1482 const NamedDecl *FDecl,
1483 Expr **Args,
1484 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001485 unsigned Idx = 0;
1486 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001487 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1488 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001489 Idx = 2;
1490 Format = true;
1491 }
1492 else
1493 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1494 if (S.GetFormatNSStringIdx(I, Idx)) {
1495 Format = true;
1496 break;
1497 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001498 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001499 if (!Format || NumArgs <= Idx)
1500 return;
1501 const Expr *FormatExpr = Args[Idx];
1502 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1503 FormatExpr = CSCE->getSubExpr();
1504 const StringLiteral *FormatString;
1505 if (const ObjCStringLiteral *OSL =
1506 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1507 FormatString = OSL->getString();
1508 else
1509 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1510 if (!FormatString)
1511 return;
1512 if (S.FormatStringHasSArg(FormatString)) {
1513 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1514 << "%s" << 1 << 1;
1515 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1516 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001517 }
1518}
1519
Douglas Gregorb4866e82015-06-19 18:13:19 +00001520/// Determine whether the given type has a non-null nullability annotation.
1521static bool isNonNullType(ASTContext &ctx, QualType type) {
1522 if (auto nullability = type->getNullability(ctx))
1523 return *nullability == NullabilityKind::NonNull;
1524
1525 return false;
1526}
1527
Ted Kremenek2bc73332014-01-17 06:24:43 +00001528static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001529 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001530 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001531 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001532 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001533 assert((FDecl || Proto) && "Need a function declaration or prototype");
1534
Ted Kremenek9aedc152014-01-17 06:24:56 +00001535 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001536 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001537 if (FDecl) {
1538 // Handle the nonnull attribute on the function/method declaration itself.
1539 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1540 if (!NonNull->args_size()) {
1541 // Easy case: all pointer arguments are nonnull.
1542 for (const auto *Arg : Args)
1543 if (S.isValidPointerAttrType(Arg->getType()))
1544 CheckNonNullArgument(S, Arg, CallSiteLoc);
1545 return;
1546 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001547
Douglas Gregorb4866e82015-06-19 18:13:19 +00001548 for (unsigned Val : NonNull->args()) {
1549 if (Val >= Args.size())
1550 continue;
1551 if (NonNullArgs.empty())
1552 NonNullArgs.resize(Args.size());
1553 NonNullArgs.set(Val);
1554 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001555 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001556 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001557
Douglas Gregorb4866e82015-06-19 18:13:19 +00001558 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1559 // Handle the nonnull attribute on the parameters of the
1560 // function/method.
1561 ArrayRef<ParmVarDecl*> parms;
1562 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1563 parms = FD->parameters();
1564 else
1565 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1566
1567 unsigned ParamIndex = 0;
1568 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1569 I != E; ++I, ++ParamIndex) {
1570 const ParmVarDecl *PVD = *I;
1571 if (PVD->hasAttr<NonNullAttr>() ||
1572 isNonNullType(S.Context, PVD->getType())) {
1573 if (NonNullArgs.empty())
1574 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001575
Douglas Gregorb4866e82015-06-19 18:13:19 +00001576 NonNullArgs.set(ParamIndex);
1577 }
1578 }
1579 } else {
1580 // If we have a non-function, non-method declaration but no
1581 // function prototype, try to dig out the function prototype.
1582 if (!Proto) {
1583 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1584 QualType type = VD->getType().getNonReferenceType();
1585 if (auto pointerType = type->getAs<PointerType>())
1586 type = pointerType->getPointeeType();
1587 else if (auto blockType = type->getAs<BlockPointerType>())
1588 type = blockType->getPointeeType();
1589 // FIXME: data member pointers?
1590
1591 // Dig out the function prototype, if there is one.
1592 Proto = type->getAs<FunctionProtoType>();
1593 }
1594 }
1595
1596 // Fill in non-null argument information from the nullability
1597 // information on the parameter types (if we have them).
1598 if (Proto) {
1599 unsigned Index = 0;
1600 for (auto paramType : Proto->getParamTypes()) {
1601 if (isNonNullType(S.Context, paramType)) {
1602 if (NonNullArgs.empty())
1603 NonNullArgs.resize(Args.size());
1604
1605 NonNullArgs.set(Index);
1606 }
1607
1608 ++Index;
1609 }
1610 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001611 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001612
Douglas Gregorb4866e82015-06-19 18:13:19 +00001613 // Check for non-null arguments.
1614 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1615 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001616 if (NonNullArgs[ArgIndex])
1617 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001618 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001619}
1620
Richard Smith55ce3522012-06-25 20:30:08 +00001621/// Handles the checks for format strings, non-POD arguments to vararg
1622/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001623void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1624 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001625 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001626 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001627 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001628 if (CurContext->isDependentContext())
1629 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001630
Ted Kremenekb8176da2010-09-09 04:33:05 +00001631 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001632 llvm::SmallBitVector CheckedVarArgs;
1633 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001634 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001635 // Only create vector if there are format attributes.
1636 CheckedVarArgs.resize(Args.size());
1637
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001638 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001639 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001640 }
Richard Smithd7293d72013-08-05 18:49:43 +00001641 }
Richard Smith55ce3522012-06-25 20:30:08 +00001642
1643 // Refuse POD arguments that weren't caught by the format string
1644 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001645 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001646 unsigned NumParams = Proto ? Proto->getNumParams()
1647 : FDecl && isa<FunctionDecl>(FDecl)
1648 ? cast<FunctionDecl>(FDecl)->getNumParams()
1649 : FDecl && isa<ObjCMethodDecl>(FDecl)
1650 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1651 : 0;
1652
Alp Toker9cacbab2014-01-20 20:26:09 +00001653 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001654 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001655 if (const Expr *Arg = Args[ArgIdx]) {
1656 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1657 checkVariadicArgument(Arg, CallType);
1658 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001659 }
Richard Smithd7293d72013-08-05 18:49:43 +00001660 }
Mike Stump11289f42009-09-09 15:08:12 +00001661
Douglas Gregorb4866e82015-06-19 18:13:19 +00001662 if (FDecl || Proto) {
1663 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001664
Richard Trieu41bc0992013-06-22 00:20:41 +00001665 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001666 if (FDecl) {
1667 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1668 CheckArgumentWithTypeTag(I, Args.data());
1669 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001670 }
Richard Smith55ce3522012-06-25 20:30:08 +00001671}
1672
1673/// CheckConstructorCall - Check a constructor call for correctness and safety
1674/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001675void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1676 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001677 const FunctionProtoType *Proto,
1678 SourceLocation Loc) {
1679 VariadicCallType CallType =
1680 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001681 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1682 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001683}
1684
1685/// CheckFunctionCall - Check a direct function call for various correctness
1686/// and safety properties not strictly enforced by the C type system.
1687bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1688 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001689 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1690 isa<CXXMethodDecl>(FDecl);
1691 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1692 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001693 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1694 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001695 Expr** Args = TheCall->getArgs();
1696 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001697 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001698 // If this is a call to a member operator, hide the first argument
1699 // from checkCall.
1700 // FIXME: Our choice of AST representation here is less than ideal.
1701 ++Args;
1702 --NumArgs;
1703 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001704 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001705 IsMemberFunction, TheCall->getRParenLoc(),
1706 TheCall->getCallee()->getSourceRange(), CallType);
1707
1708 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1709 // None of the checks below are needed for functions that don't have
1710 // simple names (e.g., C++ conversion functions).
1711 if (!FnInfo)
1712 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001713
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001714 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001715 if (getLangOpts().ObjC1)
1716 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001717
Anna Zaks22122702012-01-17 00:37:07 +00001718 unsigned CMId = FDecl->getMemoryFunctionKind();
1719 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001720 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001721
Anna Zaks201d4892012-01-13 21:52:01 +00001722 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001723 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001724 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001725 else if (CMId == Builtin::BIstrncat)
1726 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001727 else
Anna Zaks22122702012-01-17 00:37:07 +00001728 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001729
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001730 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001731}
1732
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001733bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001734 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001735 VariadicCallType CallType =
1736 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001737
Douglas Gregorb4866e82015-06-19 18:13:19 +00001738 checkCall(Method, nullptr, Args,
1739 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1740 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001741
1742 return false;
1743}
1744
Richard Trieu664c4c62013-06-20 21:03:13 +00001745bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1746 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001747 QualType Ty;
1748 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001749 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001750 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001751 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001752 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001753 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001754
Douglas Gregorb4866e82015-06-19 18:13:19 +00001755 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1756 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001757 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001758
Richard Trieu664c4c62013-06-20 21:03:13 +00001759 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001760 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001761 CallType = VariadicDoesNotApply;
1762 } else if (Ty->isBlockPointerType()) {
1763 CallType = VariadicBlock;
1764 } else { // Ty->isFunctionPointerType()
1765 CallType = VariadicFunction;
1766 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001767
Douglas Gregorb4866e82015-06-19 18:13:19 +00001768 checkCall(NDecl, Proto,
1769 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1770 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001771 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001772
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001773 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001774}
1775
Richard Trieu41bc0992013-06-22 00:20:41 +00001776/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1777/// such as function pointers returned from functions.
1778bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001779 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001780 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001781 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001782 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001783 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001784 TheCall->getCallee()->getSourceRange(), CallType);
1785
1786 return false;
1787}
1788
Tim Northovere94a34c2014-03-11 10:49:14 +00001789static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1790 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1791 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1792 return false;
1793
1794 switch (Op) {
1795 case AtomicExpr::AO__c11_atomic_init:
1796 llvm_unreachable("There is no ordering argument for an init");
1797
1798 case AtomicExpr::AO__c11_atomic_load:
1799 case AtomicExpr::AO__atomic_load_n:
1800 case AtomicExpr::AO__atomic_load:
1801 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1802 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1803
1804 case AtomicExpr::AO__c11_atomic_store:
1805 case AtomicExpr::AO__atomic_store:
1806 case AtomicExpr::AO__atomic_store_n:
1807 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1808 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1809 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1810
1811 default:
1812 return true;
1813 }
1814}
1815
Richard Smithfeea8832012-04-12 05:08:17 +00001816ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1817 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001818 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1819 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001820
Richard Smithfeea8832012-04-12 05:08:17 +00001821 // All these operations take one of the following forms:
1822 enum {
1823 // C __c11_atomic_init(A *, C)
1824 Init,
1825 // C __c11_atomic_load(A *, int)
1826 Load,
1827 // void __atomic_load(A *, CP, int)
1828 Copy,
1829 // C __c11_atomic_add(A *, M, int)
1830 Arithmetic,
1831 // C __atomic_exchange_n(A *, CP, int)
1832 Xchg,
1833 // void __atomic_exchange(A *, C *, CP, int)
1834 GNUXchg,
1835 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1836 C11CmpXchg,
1837 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1838 GNUCmpXchg
1839 } Form = Init;
1840 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1841 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1842 // where:
1843 // C is an appropriate type,
1844 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1845 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1846 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1847 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001848
Gabor Horvath98bd0982015-03-16 09:59:54 +00001849 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1850 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1851 AtomicExpr::AO__atomic_load,
1852 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001853 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1854 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1855 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1856 Op == AtomicExpr::AO__atomic_store_n ||
1857 Op == AtomicExpr::AO__atomic_exchange_n ||
1858 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1859 bool IsAddSub = false;
1860
1861 switch (Op) {
1862 case AtomicExpr::AO__c11_atomic_init:
1863 Form = Init;
1864 break;
1865
1866 case AtomicExpr::AO__c11_atomic_load:
1867 case AtomicExpr::AO__atomic_load_n:
1868 Form = Load;
1869 break;
1870
1871 case AtomicExpr::AO__c11_atomic_store:
1872 case AtomicExpr::AO__atomic_load:
1873 case AtomicExpr::AO__atomic_store:
1874 case AtomicExpr::AO__atomic_store_n:
1875 Form = Copy;
1876 break;
1877
1878 case AtomicExpr::AO__c11_atomic_fetch_add:
1879 case AtomicExpr::AO__c11_atomic_fetch_sub:
1880 case AtomicExpr::AO__atomic_fetch_add:
1881 case AtomicExpr::AO__atomic_fetch_sub:
1882 case AtomicExpr::AO__atomic_add_fetch:
1883 case AtomicExpr::AO__atomic_sub_fetch:
1884 IsAddSub = true;
1885 // Fall through.
1886 case AtomicExpr::AO__c11_atomic_fetch_and:
1887 case AtomicExpr::AO__c11_atomic_fetch_or:
1888 case AtomicExpr::AO__c11_atomic_fetch_xor:
1889 case AtomicExpr::AO__atomic_fetch_and:
1890 case AtomicExpr::AO__atomic_fetch_or:
1891 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001892 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001893 case AtomicExpr::AO__atomic_and_fetch:
1894 case AtomicExpr::AO__atomic_or_fetch:
1895 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001896 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001897 Form = Arithmetic;
1898 break;
1899
1900 case AtomicExpr::AO__c11_atomic_exchange:
1901 case AtomicExpr::AO__atomic_exchange_n:
1902 Form = Xchg;
1903 break;
1904
1905 case AtomicExpr::AO__atomic_exchange:
1906 Form = GNUXchg;
1907 break;
1908
1909 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1910 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1911 Form = C11CmpXchg;
1912 break;
1913
1914 case AtomicExpr::AO__atomic_compare_exchange:
1915 case AtomicExpr::AO__atomic_compare_exchange_n:
1916 Form = GNUCmpXchg;
1917 break;
1918 }
1919
1920 // Check we have the right number of arguments.
1921 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001922 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001923 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001924 << TheCall->getCallee()->getSourceRange();
1925 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001926 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1927 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001928 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001929 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001930 << TheCall->getCallee()->getSourceRange();
1931 return ExprError();
1932 }
1933
Richard Smithfeea8832012-04-12 05:08:17 +00001934 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001935 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001936 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1937 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1938 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001939 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001940 << Ptr->getType() << Ptr->getSourceRange();
1941 return ExprError();
1942 }
1943
Richard Smithfeea8832012-04-12 05:08:17 +00001944 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1945 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1946 QualType ValType = AtomTy; // 'C'
1947 if (IsC11) {
1948 if (!AtomTy->isAtomicType()) {
1949 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1950 << Ptr->getType() << Ptr->getSourceRange();
1951 return ExprError();
1952 }
Richard Smithe00921a2012-09-15 06:09:58 +00001953 if (AtomTy.isConstQualified()) {
1954 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1955 << Ptr->getType() << Ptr->getSourceRange();
1956 return ExprError();
1957 }
Richard Smithfeea8832012-04-12 05:08:17 +00001958 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001959 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1960 if (ValType.isConstQualified()) {
1961 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1962 << Ptr->getType() << Ptr->getSourceRange();
1963 return ExprError();
1964 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001965 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001966
Richard Smithfeea8832012-04-12 05:08:17 +00001967 // For an arithmetic operation, the implied arithmetic must be well-formed.
1968 if (Form == Arithmetic) {
1969 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1970 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1971 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1972 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1973 return ExprError();
1974 }
1975 if (!IsAddSub && !ValType->isIntegerType()) {
1976 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1977 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1978 return ExprError();
1979 }
David Majnemere85cff82015-01-28 05:48:06 +00001980 if (IsC11 && ValType->isPointerType() &&
1981 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1982 diag::err_incomplete_type)) {
1983 return ExprError();
1984 }
Richard Smithfeea8832012-04-12 05:08:17 +00001985 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1986 // For __atomic_*_n operations, the value type must be a scalar integral or
1987 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001988 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001989 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1990 return ExprError();
1991 }
1992
Eli Friedmanaa769812013-09-11 03:49:34 +00001993 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1994 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001995 // For GNU atomics, require a trivially-copyable type. This is not part of
1996 // the GNU atomics specification, but we enforce it for sanity.
1997 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001998 << Ptr->getType() << Ptr->getSourceRange();
1999 return ExprError();
2000 }
2001
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002002 switch (ValType.getObjCLifetime()) {
2003 case Qualifiers::OCL_None:
2004 case Qualifiers::OCL_ExplicitNone:
2005 // okay
2006 break;
2007
2008 case Qualifiers::OCL_Weak:
2009 case Qualifiers::OCL_Strong:
2010 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002011 // FIXME: Can this happen? By this point, ValType should be known
2012 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002013 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2014 << ValType << Ptr->getSourceRange();
2015 return ExprError();
2016 }
2017
David Majnemerc6eb6502015-06-03 00:26:35 +00002018 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2019 // volatile-ness of the pointee-type inject itself into the result or the
2020 // other operands.
2021 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002022 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00002023 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002024 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002025 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002026 ResultType = Context.BoolTy;
2027
Richard Smithfeea8832012-04-12 05:08:17 +00002028 // The type of a parameter passed 'by value'. In the GNU atomics, such
2029 // arguments are actually passed as pointers.
2030 QualType ByValType = ValType; // 'CP'
2031 if (!IsC11 && !IsN)
2032 ByValType = Ptr->getType();
2033
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002034 // FIXME: __atomic_load allows the first argument to be a a pointer to const
2035 // but not the second argument. We need to manually remove possible const
2036 // qualifiers.
2037
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002038 // The first argument --- the pointer --- has a fixed type; we
2039 // deduce the types of the rest of the arguments accordingly. Walk
2040 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002041 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002042 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002043 if (i < NumVals[Form] + 1) {
2044 switch (i) {
2045 case 1:
2046 // The second argument is the non-atomic operand. For arithmetic, this
2047 // is always passed by value, and for a compare_exchange it is always
2048 // passed by address. For the rest, GNU uses by-address and C11 uses
2049 // by-value.
2050 assert(Form != Load);
2051 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2052 Ty = ValType;
2053 else if (Form == Copy || Form == Xchg)
2054 Ty = ByValType;
2055 else if (Form == Arithmetic)
2056 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002057 else {
2058 Expr *ValArg = TheCall->getArg(i);
2059 unsigned AS = 0;
2060 // Keep address space of non-atomic pointer type.
2061 if (const PointerType *PtrTy =
2062 ValArg->getType()->getAs<PointerType>()) {
2063 AS = PtrTy->getPointeeType().getAddressSpace();
2064 }
2065 Ty = Context.getPointerType(
2066 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2067 }
Richard Smithfeea8832012-04-12 05:08:17 +00002068 break;
2069 case 2:
2070 // The third argument to compare_exchange / GNU exchange is a
2071 // (pointer to a) desired value.
2072 Ty = ByValType;
2073 break;
2074 case 3:
2075 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2076 Ty = Context.BoolTy;
2077 break;
2078 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002079 } else {
2080 // The order(s) are always converted to int.
2081 Ty = Context.IntTy;
2082 }
Richard Smithfeea8832012-04-12 05:08:17 +00002083
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002084 InitializedEntity Entity =
2085 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002086 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002087 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2088 if (Arg.isInvalid())
2089 return true;
2090 TheCall->setArg(i, Arg.get());
2091 }
2092
Richard Smithfeea8832012-04-12 05:08:17 +00002093 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002094 SmallVector<Expr*, 5> SubExprs;
2095 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002096 switch (Form) {
2097 case Init:
2098 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002099 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002100 break;
2101 case Load:
2102 SubExprs.push_back(TheCall->getArg(1)); // Order
2103 break;
2104 case Copy:
2105 case Arithmetic:
2106 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002107 SubExprs.push_back(TheCall->getArg(2)); // Order
2108 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002109 break;
2110 case GNUXchg:
2111 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2112 SubExprs.push_back(TheCall->getArg(3)); // Order
2113 SubExprs.push_back(TheCall->getArg(1)); // Val1
2114 SubExprs.push_back(TheCall->getArg(2)); // Val2
2115 break;
2116 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002117 SubExprs.push_back(TheCall->getArg(3)); // Order
2118 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002119 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002120 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002121 break;
2122 case GNUCmpXchg:
2123 SubExprs.push_back(TheCall->getArg(4)); // Order
2124 SubExprs.push_back(TheCall->getArg(1)); // Val1
2125 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2126 SubExprs.push_back(TheCall->getArg(2)); // Val2
2127 SubExprs.push_back(TheCall->getArg(3)); // Weak
2128 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002129 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002130
2131 if (SubExprs.size() >= 2 && Form != Init) {
2132 llvm::APSInt Result(32);
2133 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2134 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002135 Diag(SubExprs[1]->getLocStart(),
2136 diag::warn_atomic_op_has_invalid_memory_order)
2137 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002138 }
2139
Fariborz Jahanian615de762013-05-28 17:37:39 +00002140 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2141 SubExprs, ResultType, Op,
2142 TheCall->getRParenLoc());
2143
2144 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2145 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2146 Context.AtomicUsesUnsupportedLibcall(AE))
2147 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2148 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002149
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002150 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002151}
2152
John McCall29ad95b2011-08-27 01:09:30 +00002153/// checkBuiltinArgument - Given a call to a builtin function, perform
2154/// normal type-checking on the given argument, updating the call in
2155/// place. This is useful when a builtin function requires custom
2156/// type-checking for some of its arguments but not necessarily all of
2157/// them.
2158///
2159/// Returns true on error.
2160static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2161 FunctionDecl *Fn = E->getDirectCallee();
2162 assert(Fn && "builtin call without direct callee!");
2163
2164 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2165 InitializedEntity Entity =
2166 InitializedEntity::InitializeParameter(S.Context, Param);
2167
2168 ExprResult Arg = E->getArg(0);
2169 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2170 if (Arg.isInvalid())
2171 return true;
2172
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002173 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002174 return false;
2175}
2176
Chris Lattnerdc046542009-05-08 06:58:22 +00002177/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2178/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2179/// type of its first argument. The main ActOnCallExpr routines have already
2180/// promoted the types of arguments because all of these calls are prototyped as
2181/// void(...).
2182///
2183/// This function goes through and does final semantic checking for these
2184/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002185ExprResult
2186Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002187 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002188 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2189 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2190
2191 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002192 if (TheCall->getNumArgs() < 1) {
2193 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2194 << 0 << 1 << TheCall->getNumArgs()
2195 << TheCall->getCallee()->getSourceRange();
2196 return ExprError();
2197 }
Mike Stump11289f42009-09-09 15:08:12 +00002198
Chris Lattnerdc046542009-05-08 06:58:22 +00002199 // Inspect the first argument of the atomic builtin. This should always be
2200 // a pointer type, whose element is an integral scalar or pointer type.
2201 // Because it is a pointer type, we don't have to worry about any implicit
2202 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002203 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002204 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002205 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2206 if (FirstArgResult.isInvalid())
2207 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002208 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002209 TheCall->setArg(0, FirstArg);
2210
John McCall31168b02011-06-15 23:02:42 +00002211 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2212 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002213 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2214 << FirstArg->getType() << FirstArg->getSourceRange();
2215 return ExprError();
2216 }
Mike Stump11289f42009-09-09 15:08:12 +00002217
John McCall31168b02011-06-15 23:02:42 +00002218 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002219 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002220 !ValType->isBlockPointerType()) {
2221 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2222 << FirstArg->getType() << FirstArg->getSourceRange();
2223 return ExprError();
2224 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002225
John McCall31168b02011-06-15 23:02:42 +00002226 switch (ValType.getObjCLifetime()) {
2227 case Qualifiers::OCL_None:
2228 case Qualifiers::OCL_ExplicitNone:
2229 // okay
2230 break;
2231
2232 case Qualifiers::OCL_Weak:
2233 case Qualifiers::OCL_Strong:
2234 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002235 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002236 << ValType << FirstArg->getSourceRange();
2237 return ExprError();
2238 }
2239
John McCallb50451a2011-10-05 07:41:44 +00002240 // Strip any qualifiers off ValType.
2241 ValType = ValType.getUnqualifiedType();
2242
Chandler Carruth3973af72010-07-18 20:54:12 +00002243 // The majority of builtins return a value, but a few have special return
2244 // types, so allow them to override appropriately below.
2245 QualType ResultType = ValType;
2246
Chris Lattnerdc046542009-05-08 06:58:22 +00002247 // We need to figure out which concrete builtin this maps onto. For example,
2248 // __sync_fetch_and_add with a 2 byte object turns into
2249 // __sync_fetch_and_add_2.
2250#define BUILTIN_ROW(x) \
2251 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2252 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002253
Chris Lattnerdc046542009-05-08 06:58:22 +00002254 static const unsigned BuiltinIndices[][5] = {
2255 BUILTIN_ROW(__sync_fetch_and_add),
2256 BUILTIN_ROW(__sync_fetch_and_sub),
2257 BUILTIN_ROW(__sync_fetch_and_or),
2258 BUILTIN_ROW(__sync_fetch_and_and),
2259 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002260 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002261
Chris Lattnerdc046542009-05-08 06:58:22 +00002262 BUILTIN_ROW(__sync_add_and_fetch),
2263 BUILTIN_ROW(__sync_sub_and_fetch),
2264 BUILTIN_ROW(__sync_and_and_fetch),
2265 BUILTIN_ROW(__sync_or_and_fetch),
2266 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002267 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002268
Chris Lattnerdc046542009-05-08 06:58:22 +00002269 BUILTIN_ROW(__sync_val_compare_and_swap),
2270 BUILTIN_ROW(__sync_bool_compare_and_swap),
2271 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002272 BUILTIN_ROW(__sync_lock_release),
2273 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002274 };
Mike Stump11289f42009-09-09 15:08:12 +00002275#undef BUILTIN_ROW
2276
Chris Lattnerdc046542009-05-08 06:58:22 +00002277 // Determine the index of the size.
2278 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002279 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002280 case 1: SizeIndex = 0; break;
2281 case 2: SizeIndex = 1; break;
2282 case 4: SizeIndex = 2; break;
2283 case 8: SizeIndex = 3; break;
2284 case 16: SizeIndex = 4; break;
2285 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002286 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2287 << FirstArg->getType() << FirstArg->getSourceRange();
2288 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002289 }
Mike Stump11289f42009-09-09 15:08:12 +00002290
Chris Lattnerdc046542009-05-08 06:58:22 +00002291 // Each of these builtins has one pointer argument, followed by some number of
2292 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2293 // that we ignore. Find out which row of BuiltinIndices to read from as well
2294 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002295 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002296 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002297 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002298 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002299 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002300 case Builtin::BI__sync_fetch_and_add:
2301 case Builtin::BI__sync_fetch_and_add_1:
2302 case Builtin::BI__sync_fetch_and_add_2:
2303 case Builtin::BI__sync_fetch_and_add_4:
2304 case Builtin::BI__sync_fetch_and_add_8:
2305 case Builtin::BI__sync_fetch_and_add_16:
2306 BuiltinIndex = 0;
2307 break;
2308
2309 case Builtin::BI__sync_fetch_and_sub:
2310 case Builtin::BI__sync_fetch_and_sub_1:
2311 case Builtin::BI__sync_fetch_and_sub_2:
2312 case Builtin::BI__sync_fetch_and_sub_4:
2313 case Builtin::BI__sync_fetch_and_sub_8:
2314 case Builtin::BI__sync_fetch_and_sub_16:
2315 BuiltinIndex = 1;
2316 break;
2317
2318 case Builtin::BI__sync_fetch_and_or:
2319 case Builtin::BI__sync_fetch_and_or_1:
2320 case Builtin::BI__sync_fetch_and_or_2:
2321 case Builtin::BI__sync_fetch_and_or_4:
2322 case Builtin::BI__sync_fetch_and_or_8:
2323 case Builtin::BI__sync_fetch_and_or_16:
2324 BuiltinIndex = 2;
2325 break;
2326
2327 case Builtin::BI__sync_fetch_and_and:
2328 case Builtin::BI__sync_fetch_and_and_1:
2329 case Builtin::BI__sync_fetch_and_and_2:
2330 case Builtin::BI__sync_fetch_and_and_4:
2331 case Builtin::BI__sync_fetch_and_and_8:
2332 case Builtin::BI__sync_fetch_and_and_16:
2333 BuiltinIndex = 3;
2334 break;
Mike Stump11289f42009-09-09 15:08:12 +00002335
Douglas Gregor73722482011-11-28 16:30:08 +00002336 case Builtin::BI__sync_fetch_and_xor:
2337 case Builtin::BI__sync_fetch_and_xor_1:
2338 case Builtin::BI__sync_fetch_and_xor_2:
2339 case Builtin::BI__sync_fetch_and_xor_4:
2340 case Builtin::BI__sync_fetch_and_xor_8:
2341 case Builtin::BI__sync_fetch_and_xor_16:
2342 BuiltinIndex = 4;
2343 break;
2344
Hal Finkeld2208b52014-10-02 20:53:50 +00002345 case Builtin::BI__sync_fetch_and_nand:
2346 case Builtin::BI__sync_fetch_and_nand_1:
2347 case Builtin::BI__sync_fetch_and_nand_2:
2348 case Builtin::BI__sync_fetch_and_nand_4:
2349 case Builtin::BI__sync_fetch_and_nand_8:
2350 case Builtin::BI__sync_fetch_and_nand_16:
2351 BuiltinIndex = 5;
2352 WarnAboutSemanticsChange = true;
2353 break;
2354
Douglas Gregor73722482011-11-28 16:30:08 +00002355 case Builtin::BI__sync_add_and_fetch:
2356 case Builtin::BI__sync_add_and_fetch_1:
2357 case Builtin::BI__sync_add_and_fetch_2:
2358 case Builtin::BI__sync_add_and_fetch_4:
2359 case Builtin::BI__sync_add_and_fetch_8:
2360 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002361 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002362 break;
2363
2364 case Builtin::BI__sync_sub_and_fetch:
2365 case Builtin::BI__sync_sub_and_fetch_1:
2366 case Builtin::BI__sync_sub_and_fetch_2:
2367 case Builtin::BI__sync_sub_and_fetch_4:
2368 case Builtin::BI__sync_sub_and_fetch_8:
2369 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002370 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002371 break;
2372
2373 case Builtin::BI__sync_and_and_fetch:
2374 case Builtin::BI__sync_and_and_fetch_1:
2375 case Builtin::BI__sync_and_and_fetch_2:
2376 case Builtin::BI__sync_and_and_fetch_4:
2377 case Builtin::BI__sync_and_and_fetch_8:
2378 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002379 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002380 break;
2381
2382 case Builtin::BI__sync_or_and_fetch:
2383 case Builtin::BI__sync_or_and_fetch_1:
2384 case Builtin::BI__sync_or_and_fetch_2:
2385 case Builtin::BI__sync_or_and_fetch_4:
2386 case Builtin::BI__sync_or_and_fetch_8:
2387 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002388 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002389 break;
2390
2391 case Builtin::BI__sync_xor_and_fetch:
2392 case Builtin::BI__sync_xor_and_fetch_1:
2393 case Builtin::BI__sync_xor_and_fetch_2:
2394 case Builtin::BI__sync_xor_and_fetch_4:
2395 case Builtin::BI__sync_xor_and_fetch_8:
2396 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002397 BuiltinIndex = 10;
2398 break;
2399
2400 case Builtin::BI__sync_nand_and_fetch:
2401 case Builtin::BI__sync_nand_and_fetch_1:
2402 case Builtin::BI__sync_nand_and_fetch_2:
2403 case Builtin::BI__sync_nand_and_fetch_4:
2404 case Builtin::BI__sync_nand_and_fetch_8:
2405 case Builtin::BI__sync_nand_and_fetch_16:
2406 BuiltinIndex = 11;
2407 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002408 break;
Mike Stump11289f42009-09-09 15:08:12 +00002409
Chris Lattnerdc046542009-05-08 06:58:22 +00002410 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002411 case Builtin::BI__sync_val_compare_and_swap_1:
2412 case Builtin::BI__sync_val_compare_and_swap_2:
2413 case Builtin::BI__sync_val_compare_and_swap_4:
2414 case Builtin::BI__sync_val_compare_and_swap_8:
2415 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002416 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002417 NumFixed = 2;
2418 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002419
Chris Lattnerdc046542009-05-08 06:58:22 +00002420 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002421 case Builtin::BI__sync_bool_compare_and_swap_1:
2422 case Builtin::BI__sync_bool_compare_and_swap_2:
2423 case Builtin::BI__sync_bool_compare_and_swap_4:
2424 case Builtin::BI__sync_bool_compare_and_swap_8:
2425 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002426 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002427 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002428 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002429 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002430
2431 case Builtin::BI__sync_lock_test_and_set:
2432 case Builtin::BI__sync_lock_test_and_set_1:
2433 case Builtin::BI__sync_lock_test_and_set_2:
2434 case Builtin::BI__sync_lock_test_and_set_4:
2435 case Builtin::BI__sync_lock_test_and_set_8:
2436 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002437 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002438 break;
2439
Chris Lattnerdc046542009-05-08 06:58:22 +00002440 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002441 case Builtin::BI__sync_lock_release_1:
2442 case Builtin::BI__sync_lock_release_2:
2443 case Builtin::BI__sync_lock_release_4:
2444 case Builtin::BI__sync_lock_release_8:
2445 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002446 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002447 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002448 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002449 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002450
2451 case Builtin::BI__sync_swap:
2452 case Builtin::BI__sync_swap_1:
2453 case Builtin::BI__sync_swap_2:
2454 case Builtin::BI__sync_swap_4:
2455 case Builtin::BI__sync_swap_8:
2456 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002457 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002458 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002459 }
Mike Stump11289f42009-09-09 15:08:12 +00002460
Chris Lattnerdc046542009-05-08 06:58:22 +00002461 // Now that we know how many fixed arguments we expect, first check that we
2462 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002463 if (TheCall->getNumArgs() < 1+NumFixed) {
2464 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2465 << 0 << 1+NumFixed << TheCall->getNumArgs()
2466 << TheCall->getCallee()->getSourceRange();
2467 return ExprError();
2468 }
Mike Stump11289f42009-09-09 15:08:12 +00002469
Hal Finkeld2208b52014-10-02 20:53:50 +00002470 if (WarnAboutSemanticsChange) {
2471 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2472 << TheCall->getCallee()->getSourceRange();
2473 }
2474
Chris Lattner5b9241b2009-05-08 15:36:58 +00002475 // Get the decl for the concrete builtin from this, we can tell what the
2476 // concrete integer type we should convert to is.
2477 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002478 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002479 FunctionDecl *NewBuiltinDecl;
2480 if (NewBuiltinID == BuiltinID)
2481 NewBuiltinDecl = FDecl;
2482 else {
2483 // Perform builtin lookup to avoid redeclaring it.
2484 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2485 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2486 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2487 assert(Res.getFoundDecl());
2488 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002489 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002490 return ExprError();
2491 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002492
John McCallcf142162010-08-07 06:22:56 +00002493 // The first argument --- the pointer --- has a fixed type; we
2494 // deduce the types of the rest of the arguments accordingly. Walk
2495 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002496 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002497 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002498
Chris Lattnerdc046542009-05-08 06:58:22 +00002499 // GCC does an implicit conversion to the pointer or integer ValType. This
2500 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002501 // Initialize the argument.
2502 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2503 ValType, /*consume*/ false);
2504 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002505 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002506 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002507
Chris Lattnerdc046542009-05-08 06:58:22 +00002508 // Okay, we have something that *can* be converted to the right type. Check
2509 // to see if there is a potentially weird extension going on here. This can
2510 // happen when you do an atomic operation on something like an char* and
2511 // pass in 42. The 42 gets converted to char. This is even more strange
2512 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002513 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002514 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002515 }
Mike Stump11289f42009-09-09 15:08:12 +00002516
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002517 ASTContext& Context = this->getASTContext();
2518
2519 // Create a new DeclRefExpr to refer to the new decl.
2520 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2521 Context,
2522 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002523 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002524 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002525 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002526 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002527 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002528 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002529
Chris Lattnerdc046542009-05-08 06:58:22 +00002530 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002531 // FIXME: This loses syntactic information.
2532 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2533 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2534 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002535 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002536
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002537 // Change the result type of the call to match the original value type. This
2538 // is arbitrary, but the codegen for these builtins ins design to handle it
2539 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002540 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002541
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002542 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002543}
2544
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002545/// SemaBuiltinNontemporalOverloaded - We have a call to
2546/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2547/// overloaded function based on the pointer type of its last argument.
2548///
2549/// This function goes through and does final semantic checking for these
2550/// builtins.
2551ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2552 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2553 DeclRefExpr *DRE =
2554 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2555 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2556 unsigned BuiltinID = FDecl->getBuiltinID();
2557 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2558 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2559 "Unexpected nontemporal load/store builtin!");
2560 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2561 unsigned numArgs = isStore ? 2 : 1;
2562
2563 // Ensure that we have the proper number of arguments.
2564 if (checkArgCount(*this, TheCall, numArgs))
2565 return ExprError();
2566
2567 // Inspect the last argument of the nontemporal builtin. This should always
2568 // be a pointer type, from which we imply the type of the memory access.
2569 // Because it is a pointer type, we don't have to worry about any implicit
2570 // casts here.
2571 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2572 ExprResult PointerArgResult =
2573 DefaultFunctionArrayLvalueConversion(PointerArg);
2574
2575 if (PointerArgResult.isInvalid())
2576 return ExprError();
2577 PointerArg = PointerArgResult.get();
2578 TheCall->setArg(numArgs - 1, PointerArg);
2579
2580 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2581 if (!pointerType) {
2582 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2583 << PointerArg->getType() << PointerArg->getSourceRange();
2584 return ExprError();
2585 }
2586
2587 QualType ValType = pointerType->getPointeeType();
2588
2589 // Strip any qualifiers off ValType.
2590 ValType = ValType.getUnqualifiedType();
2591 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2592 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2593 !ValType->isVectorType()) {
2594 Diag(DRE->getLocStart(),
2595 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2596 << PointerArg->getType() << PointerArg->getSourceRange();
2597 return ExprError();
2598 }
2599
2600 if (!isStore) {
2601 TheCall->setType(ValType);
2602 return TheCallResult;
2603 }
2604
2605 ExprResult ValArg = TheCall->getArg(0);
2606 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2607 Context, ValType, /*consume*/ false);
2608 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2609 if (ValArg.isInvalid())
2610 return ExprError();
2611
2612 TheCall->setArg(0, ValArg.get());
2613 TheCall->setType(Context.VoidTy);
2614 return TheCallResult;
2615}
2616
Chris Lattner6436fb62009-02-18 06:01:06 +00002617/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002618/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002619/// Note: It might also make sense to do the UTF-16 conversion here (would
2620/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002621bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002622 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002623 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2624
Douglas Gregorfb65e592011-07-27 05:40:30 +00002625 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002626 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2627 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002628 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002629 }
Mike Stump11289f42009-09-09 15:08:12 +00002630
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002631 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002632 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002633 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002634 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002635 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002636 UTF16 *ToPtr = &ToBuf[0];
2637
2638 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2639 &ToPtr, ToPtr + NumBytes,
2640 strictConversion);
2641 // Check for conversion failure.
2642 if (Result != conversionOK)
2643 Diag(Arg->getLocStart(),
2644 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2645 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002646 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002647}
2648
Charles Davisc7d5c942015-09-17 20:55:33 +00002649/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2650/// for validity. Emit an error and return true on failure; return false
2651/// on success.
2652bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002653 Expr *Fn = TheCall->getCallee();
2654 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002655 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002656 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002657 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2658 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002659 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002660 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002661 return true;
2662 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002663
2664 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002665 return Diag(TheCall->getLocEnd(),
2666 diag::err_typecheck_call_too_few_args_at_least)
2667 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002668 }
2669
John McCall29ad95b2011-08-27 01:09:30 +00002670 // Type-check the first argument normally.
2671 if (checkBuiltinArgument(*this, TheCall, 0))
2672 return true;
2673
Chris Lattnere202e6a2007-12-20 00:05:45 +00002674 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002675 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002676 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002677 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002678 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002679 else if (FunctionDecl *FD = getCurFunctionDecl())
2680 isVariadic = FD->isVariadic();
2681 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002682 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002683
Chris Lattnere202e6a2007-12-20 00:05:45 +00002684 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002685 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2686 return true;
2687 }
Mike Stump11289f42009-09-09 15:08:12 +00002688
Chris Lattner43be2e62007-12-19 23:59:04 +00002689 // Verify that the second argument to the builtin is the last argument of the
2690 // current function or method.
2691 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002692 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002693
Nico Weber9eea7642013-05-24 23:31:57 +00002694 // These are valid if SecondArgIsLastNamedArgument is false after the next
2695 // block.
2696 QualType Type;
2697 SourceLocation ParamLoc;
2698
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002699 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2700 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002701 // FIXME: This isn't correct for methods (results in bogus warning).
2702 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002703 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002704 if (CurBlock)
2705 LastArg = *(CurBlock->TheDecl->param_end()-1);
2706 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002707 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002708 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002709 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002710 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002711
2712 Type = PV->getType();
2713 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002714 }
2715 }
Mike Stump11289f42009-09-09 15:08:12 +00002716
Chris Lattner43be2e62007-12-19 23:59:04 +00002717 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002718 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002719 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002720 else if (Type->isReferenceType()) {
2721 Diag(Arg->getLocStart(),
2722 diag::warn_va_start_of_reference_type_is_undefined);
2723 Diag(ParamLoc, diag::note_parameter_type) << Type;
2724 }
2725
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002726 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002727 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002728}
Chris Lattner43be2e62007-12-19 23:59:04 +00002729
Charles Davisc7d5c942015-09-17 20:55:33 +00002730/// Check the arguments to '__builtin_va_start' for validity, and that
2731/// it was called from a function of the native ABI.
2732/// Emit an error and return true on failure; return false on success.
2733bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2734 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2735 // On x64 Windows, don't allow this in System V ABI functions.
2736 // (Yes, that means there's no corresponding way to support variadic
2737 // System V ABI functions on Windows.)
2738 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2739 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2740 clang::CallingConv CC = CC_C;
2741 if (const FunctionDecl *FD = getCurFunctionDecl())
2742 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2743 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2744 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2745 return Diag(TheCall->getCallee()->getLocStart(),
2746 diag::err_va_start_used_in_wrong_abi_function)
2747 << (OS != llvm::Triple::Win32);
2748 }
2749 return SemaBuiltinVAStartImpl(TheCall);
2750}
2751
2752/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2753/// it was called from a Win64 ABI function.
2754/// Emit an error and return true on failure; return false on success.
2755bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2756 // This only makes sense for x86-64.
2757 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2758 Expr *Callee = TheCall->getCallee();
2759 if (TT.getArch() != llvm::Triple::x86_64)
2760 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2761 // Don't allow this in System V ABI functions.
2762 clang::CallingConv CC = CC_C;
2763 if (const FunctionDecl *FD = getCurFunctionDecl())
2764 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2765 if (CC == CC_X86_64SysV ||
2766 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2767 return Diag(Callee->getLocStart(),
2768 diag::err_ms_va_start_used_in_sysv_function);
2769 return SemaBuiltinVAStartImpl(TheCall);
2770}
2771
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002772bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2773 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2774 // const char *named_addr);
2775
2776 Expr *Func = Call->getCallee();
2777
2778 if (Call->getNumArgs() < 3)
2779 return Diag(Call->getLocEnd(),
2780 diag::err_typecheck_call_too_few_args_at_least)
2781 << 0 /*function call*/ << 3 << Call->getNumArgs();
2782
2783 // Determine whether the current function is variadic or not.
2784 bool IsVariadic;
2785 if (BlockScopeInfo *CurBlock = getCurBlock())
2786 IsVariadic = CurBlock->TheDecl->isVariadic();
2787 else if (FunctionDecl *FD = getCurFunctionDecl())
2788 IsVariadic = FD->isVariadic();
2789 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2790 IsVariadic = MD->isVariadic();
2791 else
2792 llvm_unreachable("unexpected statement type");
2793
2794 if (!IsVariadic) {
2795 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2796 return true;
2797 }
2798
2799 // Type-check the first argument normally.
2800 if (checkBuiltinArgument(*this, Call, 0))
2801 return true;
2802
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002803 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002804 unsigned ArgNo;
2805 QualType Type;
2806 } ArgumentTypes[] = {
2807 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2808 { 2, Context.getSizeType() },
2809 };
2810
2811 for (const auto &AT : ArgumentTypes) {
2812 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2813 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2814 continue;
2815 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2816 << Arg->getType() << AT.Type << 1 /* different class */
2817 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2818 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2819 }
2820
2821 return false;
2822}
2823
Chris Lattner2da14fb2007-12-20 00:26:33 +00002824/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2825/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002826bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2827 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002828 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002829 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002830 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002831 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002832 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002833 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002834 << SourceRange(TheCall->getArg(2)->getLocStart(),
2835 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002836
John Wiegley01296292011-04-08 18:41:53 +00002837 ExprResult OrigArg0 = TheCall->getArg(0);
2838 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002839
Chris Lattner2da14fb2007-12-20 00:26:33 +00002840 // Do standard promotions between the two arguments, returning their common
2841 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002842 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002843 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2844 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002845
2846 // Make sure any conversions are pushed back into the call; this is
2847 // type safe since unordered compare builtins are declared as "_Bool
2848 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002849 TheCall->setArg(0, OrigArg0.get());
2850 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002851
John Wiegley01296292011-04-08 18:41:53 +00002852 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002853 return false;
2854
Chris Lattner2da14fb2007-12-20 00:26:33 +00002855 // If the common type isn't a real floating type, then the arguments were
2856 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002857 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002858 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002859 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002860 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2861 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002862
Chris Lattner2da14fb2007-12-20 00:26:33 +00002863 return false;
2864}
2865
Benjamin Kramer634fc102010-02-15 22:42:31 +00002866/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2867/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002868/// to check everything. We expect the last argument to be a floating point
2869/// value.
2870bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2871 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002872 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002873 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002874 if (TheCall->getNumArgs() > NumArgs)
2875 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002876 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002877 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002878 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002879 (*(TheCall->arg_end()-1))->getLocEnd());
2880
Benjamin Kramer64aae502010-02-16 10:07:31 +00002881 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002882
Eli Friedman7e4faac2009-08-31 20:06:00 +00002883 if (OrigArg->isTypeDependent())
2884 return false;
2885
Chris Lattner68784ef2010-05-06 05:50:07 +00002886 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002887 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002888 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002889 diag::err_typecheck_call_invalid_unary_fp)
2890 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002891
Chris Lattner68784ef2010-05-06 05:50:07 +00002892 // If this is an implicit conversion from float -> double, remove it.
2893 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2894 Expr *CastArg = Cast->getSubExpr();
2895 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2896 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2897 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002898 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002899 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002900 }
2901 }
2902
Eli Friedman7e4faac2009-08-31 20:06:00 +00002903 return false;
2904}
2905
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002906/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2907// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002908ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002909 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002910 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002911 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002912 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2913 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002914
Nate Begemana0110022010-06-08 00:16:34 +00002915 // Determine which of the following types of shufflevector we're checking:
2916 // 1) unary, vector mask: (lhs, mask)
2917 // 2) binary, vector mask: (lhs, rhs, mask)
2918 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2919 QualType resType = TheCall->getArg(0)->getType();
2920 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002921
Douglas Gregorc25f7662009-05-19 22:10:17 +00002922 if (!TheCall->getArg(0)->isTypeDependent() &&
2923 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002924 QualType LHSType = TheCall->getArg(0)->getType();
2925 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002926
Craig Topperbaca3892013-07-29 06:47:04 +00002927 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2928 return ExprError(Diag(TheCall->getLocStart(),
2929 diag::err_shufflevector_non_vector)
2930 << SourceRange(TheCall->getArg(0)->getLocStart(),
2931 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002932
Nate Begemana0110022010-06-08 00:16:34 +00002933 numElements = LHSType->getAs<VectorType>()->getNumElements();
2934 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002935
Nate Begemana0110022010-06-08 00:16:34 +00002936 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2937 // with mask. If so, verify that RHS is an integer vector type with the
2938 // same number of elts as lhs.
2939 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002940 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002941 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002942 return ExprError(Diag(TheCall->getLocStart(),
2943 diag::err_shufflevector_incompatible_vector)
2944 << SourceRange(TheCall->getArg(1)->getLocStart(),
2945 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002946 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002947 return ExprError(Diag(TheCall->getLocStart(),
2948 diag::err_shufflevector_incompatible_vector)
2949 << SourceRange(TheCall->getArg(0)->getLocStart(),
2950 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002951 } else if (numElements != numResElements) {
2952 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002953 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002954 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002955 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002956 }
2957
2958 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002959 if (TheCall->getArg(i)->isTypeDependent() ||
2960 TheCall->getArg(i)->isValueDependent())
2961 continue;
2962
Nate Begemana0110022010-06-08 00:16:34 +00002963 llvm::APSInt Result(32);
2964 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2965 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002966 diag::err_shufflevector_nonconstant_argument)
2967 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002968
Craig Topper50ad5b72013-08-03 17:40:38 +00002969 // Allow -1 which will be translated to undef in the IR.
2970 if (Result.isSigned() && Result.isAllOnesValue())
2971 continue;
2972
Chris Lattner7ab824e2008-08-10 02:05:13 +00002973 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002974 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002975 diag::err_shufflevector_argument_too_large)
2976 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002977 }
2978
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002979 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002980
Chris Lattner7ab824e2008-08-10 02:05:13 +00002981 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002982 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002983 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002984 }
2985
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002986 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2987 TheCall->getCallee()->getLocStart(),
2988 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002989}
Chris Lattner43be2e62007-12-19 23:59:04 +00002990
Hal Finkelc4d7c822013-09-18 03:29:45 +00002991/// SemaConvertVectorExpr - Handle __builtin_convertvector
2992ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2993 SourceLocation BuiltinLoc,
2994 SourceLocation RParenLoc) {
2995 ExprValueKind VK = VK_RValue;
2996 ExprObjectKind OK = OK_Ordinary;
2997 QualType DstTy = TInfo->getType();
2998 QualType SrcTy = E->getType();
2999
3000 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3001 return ExprError(Diag(BuiltinLoc,
3002 diag::err_convertvector_non_vector)
3003 << E->getSourceRange());
3004 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3005 return ExprError(Diag(BuiltinLoc,
3006 diag::err_convertvector_non_vector_type));
3007
3008 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3009 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3010 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3011 if (SrcElts != DstElts)
3012 return ExprError(Diag(BuiltinLoc,
3013 diag::err_convertvector_incompatible_vector)
3014 << E->getSourceRange());
3015 }
3016
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003017 return new (Context)
3018 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003019}
3020
Daniel Dunbarb7257262008-07-21 22:59:13 +00003021/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3022// This is declared to take (const void*, ...) and can take two
3023// optional constant int args.
3024bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003025 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003026
Chris Lattner3b054132008-11-19 05:08:23 +00003027 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003028 return Diag(TheCall->getLocEnd(),
3029 diag::err_typecheck_call_too_many_args_at_most)
3030 << 0 /*function call*/ << 3 << NumArgs
3031 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003032
3033 // Argument 0 is checked for us and the remaining arguments must be
3034 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003035 for (unsigned i = 1; i != NumArgs; ++i)
3036 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003037 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003038
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003039 return false;
3040}
3041
Hal Finkelf0417332014-07-17 14:25:55 +00003042/// SemaBuiltinAssume - Handle __assume (MS Extension).
3043// __assume does not evaluate its arguments, and should warn if its argument
3044// has side effects.
3045bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3046 Expr *Arg = TheCall->getArg(0);
3047 if (Arg->isInstantiationDependent()) return false;
3048
3049 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003050 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003051 << Arg->getSourceRange()
3052 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3053
3054 return false;
3055}
3056
3057/// Handle __builtin_assume_aligned. This is declared
3058/// as (const void*, size_t, ...) and can take one optional constant int arg.
3059bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3060 unsigned NumArgs = TheCall->getNumArgs();
3061
3062 if (NumArgs > 3)
3063 return Diag(TheCall->getLocEnd(),
3064 diag::err_typecheck_call_too_many_args_at_most)
3065 << 0 /*function call*/ << 3 << NumArgs
3066 << TheCall->getSourceRange();
3067
3068 // The alignment must be a constant integer.
3069 Expr *Arg = TheCall->getArg(1);
3070
3071 // We can't check the value of a dependent argument.
3072 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3073 llvm::APSInt Result;
3074 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3075 return true;
3076
3077 if (!Result.isPowerOf2())
3078 return Diag(TheCall->getLocStart(),
3079 diag::err_alignment_not_power_of_two)
3080 << Arg->getSourceRange();
3081 }
3082
3083 if (NumArgs > 2) {
3084 ExprResult Arg(TheCall->getArg(2));
3085 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3086 Context.getSizeType(), false);
3087 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3088 if (Arg.isInvalid()) return true;
3089 TheCall->setArg(2, Arg.get());
3090 }
Hal Finkelf0417332014-07-17 14:25:55 +00003091
3092 return false;
3093}
3094
Eric Christopher8d0c6212010-04-17 02:26:23 +00003095/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3096/// TheCall is a constant expression.
3097bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3098 llvm::APSInt &Result) {
3099 Expr *Arg = TheCall->getArg(ArgNum);
3100 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3101 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3102
3103 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3104
3105 if (!Arg->isIntegerConstantExpr(Result, Context))
3106 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003107 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003108
Chris Lattnerd545ad12009-09-23 06:06:36 +00003109 return false;
3110}
3111
Richard Sandiford28940af2014-04-16 08:47:51 +00003112/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3113/// TheCall is a constant expression in the range [Low, High].
3114bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3115 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003116 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003117
3118 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003119 Expr *Arg = TheCall->getArg(ArgNum);
3120 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003121 return false;
3122
Eric Christopher8d0c6212010-04-17 02:26:23 +00003123 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003124 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003125 return true;
3126
Richard Sandiford28940af2014-04-16 08:47:51 +00003127 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003128 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003129 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003130
3131 return false;
3132}
3133
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003134/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3135/// TheCall is an ARM/AArch64 special register string literal.
3136bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3137 int ArgNum, unsigned ExpectedFieldNum,
3138 bool AllowName) {
3139 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3140 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3141 BuiltinID == ARM::BI__builtin_arm_rsr ||
3142 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3143 BuiltinID == ARM::BI__builtin_arm_wsr ||
3144 BuiltinID == ARM::BI__builtin_arm_wsrp;
3145 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3146 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3147 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3148 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3149 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3150 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3151 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3152
3153 // We can't check the value of a dependent argument.
3154 Expr *Arg = TheCall->getArg(ArgNum);
3155 if (Arg->isTypeDependent() || Arg->isValueDependent())
3156 return false;
3157
3158 // Check if the argument is a string literal.
3159 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3160 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3161 << Arg->getSourceRange();
3162
3163 // Check the type of special register given.
3164 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3165 SmallVector<StringRef, 6> Fields;
3166 Reg.split(Fields, ":");
3167
3168 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3169 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3170 << Arg->getSourceRange();
3171
3172 // If the string is the name of a register then we cannot check that it is
3173 // valid here but if the string is of one the forms described in ACLE then we
3174 // can check that the supplied fields are integers and within the valid
3175 // ranges.
3176 if (Fields.size() > 1) {
3177 bool FiveFields = Fields.size() == 5;
3178
3179 bool ValidString = true;
3180 if (IsARMBuiltin) {
3181 ValidString &= Fields[0].startswith_lower("cp") ||
3182 Fields[0].startswith_lower("p");
3183 if (ValidString)
3184 Fields[0] =
3185 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3186
3187 ValidString &= Fields[2].startswith_lower("c");
3188 if (ValidString)
3189 Fields[2] = Fields[2].drop_front(1);
3190
3191 if (FiveFields) {
3192 ValidString &= Fields[3].startswith_lower("c");
3193 if (ValidString)
3194 Fields[3] = Fields[3].drop_front(1);
3195 }
3196 }
3197
3198 SmallVector<int, 5> Ranges;
3199 if (FiveFields)
3200 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3201 else
3202 Ranges.append({15, 7, 15});
3203
3204 for (unsigned i=0; i<Fields.size(); ++i) {
3205 int IntField;
3206 ValidString &= !Fields[i].getAsInteger(10, IntField);
3207 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3208 }
3209
3210 if (!ValidString)
3211 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3212 << Arg->getSourceRange();
3213
3214 } else if (IsAArch64Builtin && Fields.size() == 1) {
3215 // If the register name is one of those that appear in the condition below
3216 // and the special register builtin being used is one of the write builtins,
3217 // then we require that the argument provided for writing to the register
3218 // is an integer constant expression. This is because it will be lowered to
3219 // an MSR (immediate) instruction, so we need to know the immediate at
3220 // compile time.
3221 if (TheCall->getNumArgs() != 2)
3222 return false;
3223
3224 std::string RegLower = Reg.lower();
3225 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3226 RegLower != "pan" && RegLower != "uao")
3227 return false;
3228
3229 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3230 }
3231
3232 return false;
3233}
3234
Eli Friedmanc97d0142009-05-03 06:04:26 +00003235/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003236/// This checks that the target supports __builtin_longjmp and
3237/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003238bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003239 if (!Context.getTargetInfo().hasSjLjLowering())
3240 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3241 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3242
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003243 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003244 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003245
Eric Christopher8d0c6212010-04-17 02:26:23 +00003246 // TODO: This is less than ideal. Overload this to take a value.
3247 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3248 return true;
3249
3250 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003251 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3252 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3253
3254 return false;
3255}
3256
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003257/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3258/// This checks that the target supports __builtin_setjmp.
3259bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3260 if (!Context.getTargetInfo().hasSjLjLowering())
3261 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3262 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3263 return false;
3264}
3265
Richard Smithd7293d72013-08-05 18:49:43 +00003266namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003267class UncoveredArgHandler {
3268 enum { Unknown = -1, AllCovered = -2 };
3269 signed FirstUncoveredArg;
3270 SmallVector<const Expr *, 4> DiagnosticExprs;
3271
3272public:
3273 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3274
3275 bool hasUncoveredArg() const {
3276 return (FirstUncoveredArg >= 0);
3277 }
3278
3279 unsigned getUncoveredArg() const {
3280 assert(hasUncoveredArg() && "no uncovered argument");
3281 return FirstUncoveredArg;
3282 }
3283
3284 void setAllCovered() {
3285 // A string has been found with all arguments covered, so clear out
3286 // the diagnostics.
3287 DiagnosticExprs.clear();
3288 FirstUncoveredArg = AllCovered;
3289 }
3290
3291 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3292 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3293
3294 // Don't update if a previous string covers all arguments.
3295 if (FirstUncoveredArg == AllCovered)
3296 return;
3297
3298 // UncoveredArgHandler tracks the highest uncovered argument index
3299 // and with it all the strings that match this index.
3300 if (NewFirstUncoveredArg == FirstUncoveredArg)
3301 DiagnosticExprs.push_back(StrExpr);
3302 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3303 DiagnosticExprs.clear();
3304 DiagnosticExprs.push_back(StrExpr);
3305 FirstUncoveredArg = NewFirstUncoveredArg;
3306 }
3307 }
3308
3309 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3310};
3311
Richard Smithd7293d72013-08-05 18:49:43 +00003312enum StringLiteralCheckType {
3313 SLCT_NotALiteral,
3314 SLCT_UncheckedLiteral,
3315 SLCT_CheckedLiteral
3316};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003317} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003318
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003319static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3320 const Expr *OrigFormatExpr,
3321 ArrayRef<const Expr *> Args,
3322 bool HasVAListArg, unsigned format_idx,
3323 unsigned firstDataArg,
3324 Sema::FormatStringType Type,
3325 bool inFunctionCall,
3326 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003327 llvm::SmallBitVector &CheckedVarArgs,
3328 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003329
Richard Smith55ce3522012-06-25 20:30:08 +00003330// Determine if an expression is a string literal or constant string.
3331// If this function returns false on the arguments to a function expecting a
3332// format string, we will usually need to emit a warning.
3333// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003334static StringLiteralCheckType
3335checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3336 bool HasVAListArg, unsigned format_idx,
3337 unsigned firstDataArg, Sema::FormatStringType Type,
3338 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003339 llvm::SmallBitVector &CheckedVarArgs,
3340 UncoveredArgHandler &UncoveredArg) {
Ted Kremenek808829352010-09-09 03:51:39 +00003341 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003342 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003343 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003344
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003345 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003346
Richard Smithd7293d72013-08-05 18:49:43 +00003347 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003348 // Technically -Wformat-nonliteral does not warn about this case.
3349 // The behavior of printf and friends in this case is implementation
3350 // dependent. Ideally if the format string cannot be null then
3351 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003352 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003353
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003354 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003355 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003356 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003357 // The expression is a literal if both sub-expressions were, and it was
3358 // completely checked only if both sub-expressions were checked.
3359 const AbstractConditionalOperator *C =
3360 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003361
3362 // Determine whether it is necessary to check both sub-expressions, for
3363 // example, because the condition expression is a constant that can be
3364 // evaluated at compile time.
3365 bool CheckLeft = true, CheckRight = true;
3366
3367 bool Cond;
3368 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3369 if (Cond)
3370 CheckRight = false;
3371 else
3372 CheckLeft = false;
3373 }
3374
3375 StringLiteralCheckType Left;
3376 if (!CheckLeft)
3377 Left = SLCT_UncheckedLiteral;
3378 else {
3379 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3380 HasVAListArg, format_idx, firstDataArg,
3381 Type, CallType, InFunctionCall,
3382 CheckedVarArgs, UncoveredArg);
3383 if (Left == SLCT_NotALiteral || !CheckRight)
3384 return Left;
3385 }
3386
Richard Smith55ce3522012-06-25 20:30:08 +00003387 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003388 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003389 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003390 Type, CallType, InFunctionCall, CheckedVarArgs,
3391 UncoveredArg);
3392
3393 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003394 }
3395
3396 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003397 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3398 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003399 }
3400
John McCallc07a0c72011-02-17 10:25:35 +00003401 case Stmt::OpaqueValueExprClass:
3402 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3403 E = src;
3404 goto tryAgain;
3405 }
Richard Smith55ce3522012-06-25 20:30:08 +00003406 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003407
Ted Kremeneka8890832011-02-24 23:03:04 +00003408 case Stmt::PredefinedExprClass:
3409 // While __func__, etc., are technically not string literals, they
3410 // cannot contain format specifiers and thus are not a security
3411 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003412 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003413
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003414 case Stmt::DeclRefExprClass: {
3415 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003416
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003417 // As an exception, do not flag errors for variables binding to
3418 // const string literals.
3419 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3420 bool isConstant = false;
3421 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003422
Richard Smithd7293d72013-08-05 18:49:43 +00003423 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3424 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003425 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003426 isConstant = T.isConstant(S.Context) &&
3427 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003428 } else if (T->isObjCObjectPointerType()) {
3429 // In ObjC, there is usually no "const ObjectPointer" type,
3430 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003431 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003432 }
Mike Stump11289f42009-09-09 15:08:12 +00003433
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003434 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003435 if (const Expr *Init = VD->getAnyInitializer()) {
3436 // Look through initializers like const char c[] = { "foo" }
3437 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3438 if (InitList->isStringLiteralInit())
3439 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3440 }
Richard Smithd7293d72013-08-05 18:49:43 +00003441 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003442 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003443 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003444 /*InFunctionCall*/false, CheckedVarArgs,
3445 UncoveredArg);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003446 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003447 }
Mike Stump11289f42009-09-09 15:08:12 +00003448
Anders Carlssonb012ca92009-06-28 19:55:58 +00003449 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3450 // special check to see if the format string is a function parameter
3451 // of the function calling the printf function. If the function
3452 // has an attribute indicating it is a printf-like function, then we
3453 // should suppress warnings concerning non-literals being used in a call
3454 // to a vprintf function. For example:
3455 //
3456 // void
3457 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3458 // va_list ap;
3459 // va_start(ap, fmt);
3460 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3461 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003462 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003463 if (HasVAListArg) {
3464 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3465 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3466 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003467 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003468 // adjust for implicit parameter
3469 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3470 if (MD->isInstance())
3471 ++PVIndex;
3472 // We also check if the formats are compatible.
3473 // We can't pass a 'scanf' string to a 'printf' function.
3474 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003475 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003476 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003477 }
3478 }
3479 }
3480 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003481 }
Mike Stump11289f42009-09-09 15:08:12 +00003482
Richard Smith55ce3522012-06-25 20:30:08 +00003483 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003484 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003485
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003486 case Stmt::CallExprClass:
3487 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003488 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003489 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3490 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3491 unsigned ArgIndex = FA->getFormatIdx();
3492 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3493 if (MD->isInstance())
3494 --ArgIndex;
3495 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003496
Richard Smithd7293d72013-08-05 18:49:43 +00003497 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003498 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003499 Type, CallType, InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003500 CheckedVarArgs, UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003501 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3502 unsigned BuiltinID = FD->getBuiltinID();
3503 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3504 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3505 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003506 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003507 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003508 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003509 InFunctionCall, CheckedVarArgs,
3510 UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003511 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003512 }
3513 }
Mike Stump11289f42009-09-09 15:08:12 +00003514
Richard Smith55ce3522012-06-25 20:30:08 +00003515 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003516 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003517 case Stmt::ObjCStringLiteralClass:
3518 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003519 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003520
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003521 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003522 StrE = ObjCFExpr->getString();
3523 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003524 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003525
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003526 if (StrE) {
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003527 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
3528 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003529 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00003530 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003531 }
Mike Stump11289f42009-09-09 15:08:12 +00003532
Richard Smith55ce3522012-06-25 20:30:08 +00003533 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003534 }
Mike Stump11289f42009-09-09 15:08:12 +00003535
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003536 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003537 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003538 }
3539}
3540
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003541Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003542 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003543 .Case("scanf", FST_Scanf)
3544 .Cases("printf", "printf0", FST_Printf)
3545 .Cases("NSString", "CFString", FST_NSString)
3546 .Case("strftime", FST_Strftime)
3547 .Case("strfmon", FST_Strfmon)
3548 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003549 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003550 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003551 .Default(FST_Unknown);
3552}
3553
Jordan Rose3e0ec582012-07-19 18:10:23 +00003554/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003555/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003556/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003557bool Sema::CheckFormatArguments(const FormatAttr *Format,
3558 ArrayRef<const Expr *> Args,
3559 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003560 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003561 SourceLocation Loc, SourceRange Range,
3562 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003563 FormatStringInfo FSI;
3564 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003565 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003566 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003567 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003568 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003569}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003570
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003571bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003572 bool HasVAListArg, unsigned format_idx,
3573 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003574 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003575 SourceLocation Loc, SourceRange Range,
3576 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003577 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003578 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003579 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003580 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003581 }
Mike Stump11289f42009-09-09 15:08:12 +00003582
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003583 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003584
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003585 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003586 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003587 // Dynamically generated format strings are difficult to
3588 // automatically vet at compile time. Requiring that format strings
3589 // are string literals: (1) permits the checking of format strings by
3590 // the compiler and thereby (2) can practically remove the source of
3591 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003592
Mike Stump11289f42009-09-09 15:08:12 +00003593 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003594 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003595 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003596 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003597 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00003598 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003599 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3600 format_idx, firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003601 /*IsFunctionCall*/true, CheckedVarArgs,
3602 UncoveredArg);
3603
3604 // Generate a diagnostic where an uncovered argument is detected.
3605 if (UncoveredArg.hasUncoveredArg()) {
3606 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
3607 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
3608 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
3609 }
3610
Richard Smith55ce3522012-06-25 20:30:08 +00003611 if (CT != SLCT_NotALiteral)
3612 // Literal format string found, check done!
3613 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003614
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003615 // Strftime is particular as it always uses a single 'time' argument,
3616 // so it is safe to pass a non-literal string.
3617 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003618 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003619
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003620 // Do not emit diag when the string param is a macro expansion and the
3621 // format is either NSString or CFString. This is a hack to prevent
3622 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3623 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003624 if (Type == FST_NSString &&
3625 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003626 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003627
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003628 // If there are no arguments specified, warn with -Wformat-security, otherwise
3629 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003630 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003631 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003632 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003633 << OrigFormatExpr->getSourceRange();
3634 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003635 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003636 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003637 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003638 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003639}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003640
Ted Kremenekab278de2010-01-28 23:39:18 +00003641namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003642class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3643protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003644 Sema &S;
3645 const StringLiteral *FExpr;
3646 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003647 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003648 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003649 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003650 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003651 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003652 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003653 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003654 bool usesPositionalArgs;
3655 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003656 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003657 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003658 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003659 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003660
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003661public:
Ted Kremenek02087932010-07-16 02:11:22 +00003662 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003663 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003664 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003665 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003666 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003667 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003668 llvm::SmallBitVector &CheckedVarArgs,
3669 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00003670 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003671 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3672 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003673 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003674 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003675 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003676 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00003677 CoveredArgs.resize(numDataArgs);
3678 CoveredArgs.reset();
3679 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003680
Ted Kremenek019d2242010-01-29 01:50:07 +00003681 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003682
Ted Kremenek02087932010-07-16 02:11:22 +00003683 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003684 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003685
Jordan Rose92303592012-09-08 04:00:03 +00003686 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003687 const analyze_format_string::FormatSpecifier &FS,
3688 const analyze_format_string::ConversionSpecifier &CS,
3689 const char *startSpecifier, unsigned specifierLen,
3690 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003691
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003692 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003693 const analyze_format_string::FormatSpecifier &FS,
3694 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003695
3696 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003697 const analyze_format_string::ConversionSpecifier &CS,
3698 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003699
Craig Toppere14c0f82014-03-12 04:55:44 +00003700 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003701
Craig Toppere14c0f82014-03-12 04:55:44 +00003702 void HandleInvalidPosition(const char *startSpecifier,
3703 unsigned specifierLen,
3704 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003705
Craig Toppere14c0f82014-03-12 04:55:44 +00003706 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003707
Craig Toppere14c0f82014-03-12 04:55:44 +00003708 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003709
Richard Trieu03cf7b72011-10-28 00:41:25 +00003710 template <typename Range>
3711 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3712 const Expr *ArgumentExpr,
3713 PartialDiagnostic PDiag,
3714 SourceLocation StringLoc,
3715 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003716 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003717
Ted Kremenek02087932010-07-16 02:11:22 +00003718protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003719 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3720 const char *startSpec,
3721 unsigned specifierLen,
3722 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003723
3724 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3725 const char *startSpec,
3726 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003727
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003728 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003729 CharSourceRange getSpecifierRange(const char *startSpecifier,
3730 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003731 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003732
Ted Kremenek5739de72010-01-29 01:06:55 +00003733 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003734
3735 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3736 const analyze_format_string::ConversionSpecifier &CS,
3737 const char *startSpecifier, unsigned specifierLen,
3738 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003739
3740 template <typename Range>
3741 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3742 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003743 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003744};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003745} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00003746
Ted Kremenek02087932010-07-16 02:11:22 +00003747SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003748 return OrigFormatExpr->getSourceRange();
3749}
3750
Ted Kremenek02087932010-07-16 02:11:22 +00003751CharSourceRange CheckFormatHandler::
3752getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003753 SourceLocation Start = getLocationOfByte(startSpecifier);
3754 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3755
3756 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003757 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003758
3759 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003760}
3761
Ted Kremenek02087932010-07-16 02:11:22 +00003762SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003763 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003764}
3765
Ted Kremenek02087932010-07-16 02:11:22 +00003766void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3767 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003768 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3769 getLocationOfByte(startSpecifier),
3770 /*IsStringLocation*/true,
3771 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003772}
3773
Jordan Rose92303592012-09-08 04:00:03 +00003774void CheckFormatHandler::HandleInvalidLengthModifier(
3775 const analyze_format_string::FormatSpecifier &FS,
3776 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003777 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003778 using namespace analyze_format_string;
3779
3780 const LengthModifier &LM = FS.getLengthModifier();
3781 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3782
3783 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003784 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003785 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003786 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003787 getLocationOfByte(LM.getStart()),
3788 /*IsStringLocation*/true,
3789 getSpecifierRange(startSpecifier, specifierLen));
3790
3791 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3792 << FixedLM->toString()
3793 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3794
3795 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003796 FixItHint Hint;
3797 if (DiagID == diag::warn_format_nonsensical_length)
3798 Hint = FixItHint::CreateRemoval(LMRange);
3799
3800 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003801 getLocationOfByte(LM.getStart()),
3802 /*IsStringLocation*/true,
3803 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003804 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003805 }
3806}
3807
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003808void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003809 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003810 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003811 using namespace analyze_format_string;
3812
3813 const LengthModifier &LM = FS.getLengthModifier();
3814 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3815
3816 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003817 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003818 if (FixedLM) {
3819 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3820 << LM.toString() << 0,
3821 getLocationOfByte(LM.getStart()),
3822 /*IsStringLocation*/true,
3823 getSpecifierRange(startSpecifier, specifierLen));
3824
3825 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3826 << FixedLM->toString()
3827 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3828
3829 } else {
3830 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3831 << LM.toString() << 0,
3832 getLocationOfByte(LM.getStart()),
3833 /*IsStringLocation*/true,
3834 getSpecifierRange(startSpecifier, specifierLen));
3835 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003836}
3837
3838void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3839 const analyze_format_string::ConversionSpecifier &CS,
3840 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003841 using namespace analyze_format_string;
3842
3843 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003844 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003845 if (FixedCS) {
3846 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3847 << CS.toString() << /*conversion specifier*/1,
3848 getLocationOfByte(CS.getStart()),
3849 /*IsStringLocation*/true,
3850 getSpecifierRange(startSpecifier, specifierLen));
3851
3852 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3853 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3854 << FixedCS->toString()
3855 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3856 } else {
3857 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3858 << CS.toString() << /*conversion specifier*/1,
3859 getLocationOfByte(CS.getStart()),
3860 /*IsStringLocation*/true,
3861 getSpecifierRange(startSpecifier, specifierLen));
3862 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003863}
3864
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003865void CheckFormatHandler::HandlePosition(const char *startPos,
3866 unsigned posLen) {
3867 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3868 getLocationOfByte(startPos),
3869 /*IsStringLocation*/true,
3870 getSpecifierRange(startPos, posLen));
3871}
3872
Ted Kremenekd1668192010-02-27 01:41:03 +00003873void
Ted Kremenek02087932010-07-16 02:11:22 +00003874CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3875 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003876 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3877 << (unsigned) p,
3878 getLocationOfByte(startPos), /*IsStringLocation*/true,
3879 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003880}
3881
Ted Kremenek02087932010-07-16 02:11:22 +00003882void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003883 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003884 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3885 getLocationOfByte(startPos),
3886 /*IsStringLocation*/true,
3887 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003888}
3889
Ted Kremenek02087932010-07-16 02:11:22 +00003890void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003891 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003892 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003893 EmitFormatDiagnostic(
3894 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3895 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3896 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003897 }
Ted Kremenek02087932010-07-16 02:11:22 +00003898}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003899
Jordan Rose58bbe422012-07-19 18:10:08 +00003900// Note that this may return NULL if there was an error parsing or building
3901// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003902const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003903 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003904}
3905
3906void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003907 // Does the number of data arguments exceed the number of
3908 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00003909 if (!HasVAListArg) {
3910 // Find any arguments that weren't covered.
3911 CoveredArgs.flip();
3912 signed notCoveredArg = CoveredArgs.find_first();
3913 if (notCoveredArg >= 0) {
3914 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003915 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
3916 } else {
3917 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00003918 }
3919 }
3920}
3921
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003922void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
3923 const Expr *ArgExpr) {
3924 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
3925 "Invalid state");
3926
3927 if (!ArgExpr)
3928 return;
3929
3930 SourceLocation Loc = ArgExpr->getLocStart();
3931
3932 if (S.getSourceManager().isInSystemMacro(Loc))
3933 return;
3934
3935 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
3936 for (auto E : DiagnosticExprs)
3937 PDiag << E->getSourceRange();
3938
3939 CheckFormatHandler::EmitFormatDiagnostic(
3940 S, IsFunctionCall, DiagnosticExprs[0],
3941 PDiag, Loc, /*IsStringLocation*/false,
3942 DiagnosticExprs[0]->getSourceRange());
3943}
3944
Ted Kremenekce815422010-07-19 21:25:57 +00003945bool
3946CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3947 SourceLocation Loc,
3948 const char *startSpec,
3949 unsigned specifierLen,
3950 const char *csStart,
3951 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00003952 bool keepGoing = true;
3953 if (argIndex < NumDataArgs) {
3954 // Consider the argument coverered, even though the specifier doesn't
3955 // make sense.
3956 CoveredArgs.set(argIndex);
3957 }
3958 else {
3959 // If argIndex exceeds the number of data arguments we
3960 // don't issue a warning because that is just a cascade of warnings (and
3961 // they may have intended '%%' anyway). We don't want to continue processing
3962 // the format string after this point, however, as we will like just get
3963 // gibberish when trying to match arguments.
3964 keepGoing = false;
3965 }
3966
Richard Trieu03cf7b72011-10-28 00:41:25 +00003967 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3968 << StringRef(csStart, csLen),
3969 Loc, /*IsStringLocation*/true,
3970 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003971
3972 return keepGoing;
3973}
3974
Richard Trieu03cf7b72011-10-28 00:41:25 +00003975void
3976CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3977 const char *startSpec,
3978 unsigned specifierLen) {
3979 EmitFormatDiagnostic(
3980 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3981 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3982}
3983
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003984bool
3985CheckFormatHandler::CheckNumArgs(
3986 const analyze_format_string::FormatSpecifier &FS,
3987 const analyze_format_string::ConversionSpecifier &CS,
3988 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3989
3990 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003991 PartialDiagnostic PDiag = FS.usesPositionalArg()
3992 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3993 << (argIndex+1) << NumDataArgs)
3994 : S.PDiag(diag::warn_printf_insufficient_data_args);
3995 EmitFormatDiagnostic(
3996 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3997 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003998
3999 // Since more arguments than conversion tokens are given, by extension
4000 // all arguments are covered, so mark this as so.
4001 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004002 return false;
4003 }
4004 return true;
4005}
4006
Richard Trieu03cf7b72011-10-28 00:41:25 +00004007template<typename Range>
4008void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4009 SourceLocation Loc,
4010 bool IsStringLocation,
4011 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004012 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004013 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004014 Loc, IsStringLocation, StringRange, FixIt);
4015}
4016
4017/// \brief If the format string is not within the funcion call, emit a note
4018/// so that the function call and string are in diagnostic messages.
4019///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004020/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004021/// call and only one diagnostic message will be produced. Otherwise, an
4022/// extra note will be emitted pointing to location of the format string.
4023///
4024/// \param ArgumentExpr the expression that is passed as the format string
4025/// argument in the function call. Used for getting locations when two
4026/// diagnostics are emitted.
4027///
4028/// \param PDiag the callee should already have provided any strings for the
4029/// diagnostic message. This function only adds locations and fixits
4030/// to diagnostics.
4031///
4032/// \param Loc primary location for diagnostic. If two diagnostics are
4033/// required, one will be at Loc and a new SourceLocation will be created for
4034/// the other one.
4035///
4036/// \param IsStringLocation if true, Loc points to the format string should be
4037/// used for the note. Otherwise, Loc points to the argument list and will
4038/// be used with PDiag.
4039///
4040/// \param StringRange some or all of the string to highlight. This is
4041/// templated so it can accept either a CharSourceRange or a SourceRange.
4042///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004043/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004044template<typename Range>
4045void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
4046 const Expr *ArgumentExpr,
4047 PartialDiagnostic PDiag,
4048 SourceLocation Loc,
4049 bool IsStringLocation,
4050 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004051 ArrayRef<FixItHint> FixIt) {
4052 if (InFunctionCall) {
4053 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4054 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004055 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004056 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004057 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4058 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004059
4060 const Sema::SemaDiagnosticBuilder &Note =
4061 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4062 diag::note_format_string_defined);
4063
4064 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004065 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004066 }
4067}
4068
Ted Kremenek02087932010-07-16 02:11:22 +00004069//===--- CHECK: Printf format string checking ------------------------------===//
4070
4071namespace {
4072class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004073 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004074
Ted Kremenek02087932010-07-16 02:11:22 +00004075public:
4076 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4077 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004078 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004079 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004080 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004081 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004082 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004083 llvm::SmallBitVector &CheckedVarArgs,
4084 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004085 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4086 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004087 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4088 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004089 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004090 {}
4091
Ted Kremenek02087932010-07-16 02:11:22 +00004092 bool HandleInvalidPrintfConversionSpecifier(
4093 const analyze_printf::PrintfSpecifier &FS,
4094 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004095 unsigned specifierLen) override;
4096
Ted Kremenek02087932010-07-16 02:11:22 +00004097 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4098 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004099 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004100 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4101 const char *StartSpecifier,
4102 unsigned SpecifierLen,
4103 const Expr *E);
4104
Ted Kremenek02087932010-07-16 02:11:22 +00004105 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4106 const char *startSpecifier, unsigned specifierLen);
4107 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4108 const analyze_printf::OptionalAmount &Amt,
4109 unsigned type,
4110 const char *startSpecifier, unsigned specifierLen);
4111 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4112 const analyze_printf::OptionalFlag &flag,
4113 const char *startSpecifier, unsigned specifierLen);
4114 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4115 const analyze_printf::OptionalFlag &ignoredFlag,
4116 const analyze_printf::OptionalFlag &flag,
4117 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004118 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004119 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004120
4121 void HandleEmptyObjCModifierFlag(const char *startFlag,
4122 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004123
Ted Kremenek2b417712015-07-02 05:39:16 +00004124 void HandleInvalidObjCModifierFlag(const char *startFlag,
4125 unsigned flagLen) override;
4126
4127 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4128 const char *flagsEnd,
4129 const char *conversionPosition)
4130 override;
4131};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004132} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004133
4134bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4135 const analyze_printf::PrintfSpecifier &FS,
4136 const char *startSpecifier,
4137 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004138 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004139 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004140
Ted Kremenekce815422010-07-19 21:25:57 +00004141 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4142 getLocationOfByte(CS.getStart()),
4143 startSpecifier, specifierLen,
4144 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004145}
4146
Ted Kremenek02087932010-07-16 02:11:22 +00004147bool CheckPrintfHandler::HandleAmount(
4148 const analyze_format_string::OptionalAmount &Amt,
4149 unsigned k, const char *startSpecifier,
4150 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004151 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004152 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004153 unsigned argIndex = Amt.getArgIndex();
4154 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004155 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4156 << k,
4157 getLocationOfByte(Amt.getStart()),
4158 /*IsStringLocation*/true,
4159 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004160 // Don't do any more checking. We will just emit
4161 // spurious errors.
4162 return false;
4163 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004164
Ted Kremenek5739de72010-01-29 01:06:55 +00004165 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004166 // Although not in conformance with C99, we also allow the argument to be
4167 // an 'unsigned int' as that is a reasonably safe case. GCC also
4168 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004169 CoveredArgs.set(argIndex);
4170 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004171 if (!Arg)
4172 return false;
4173
Ted Kremenek5739de72010-01-29 01:06:55 +00004174 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004175
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004176 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4177 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004178
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004179 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004180 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004181 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004182 << T << Arg->getSourceRange(),
4183 getLocationOfByte(Amt.getStart()),
4184 /*IsStringLocation*/true,
4185 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004186 // Don't do any more checking. We will just emit
4187 // spurious errors.
4188 return false;
4189 }
4190 }
4191 }
4192 return true;
4193}
Ted Kremenek5739de72010-01-29 01:06:55 +00004194
Tom Careb49ec692010-06-17 19:00:27 +00004195void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004196 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004197 const analyze_printf::OptionalAmount &Amt,
4198 unsigned type,
4199 const char *startSpecifier,
4200 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004201 const analyze_printf::PrintfConversionSpecifier &CS =
4202 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004203
Richard Trieu03cf7b72011-10-28 00:41:25 +00004204 FixItHint fixit =
4205 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4206 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4207 Amt.getConstantLength()))
4208 : FixItHint();
4209
4210 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4211 << type << CS.toString(),
4212 getLocationOfByte(Amt.getStart()),
4213 /*IsStringLocation*/true,
4214 getSpecifierRange(startSpecifier, specifierLen),
4215 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004216}
4217
Ted Kremenek02087932010-07-16 02:11:22 +00004218void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004219 const analyze_printf::OptionalFlag &flag,
4220 const char *startSpecifier,
4221 unsigned specifierLen) {
4222 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004223 const analyze_printf::PrintfConversionSpecifier &CS =
4224 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004225 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4226 << flag.toString() << CS.toString(),
4227 getLocationOfByte(flag.getPosition()),
4228 /*IsStringLocation*/true,
4229 getSpecifierRange(startSpecifier, specifierLen),
4230 FixItHint::CreateRemoval(
4231 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004232}
4233
4234void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004235 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004236 const analyze_printf::OptionalFlag &ignoredFlag,
4237 const analyze_printf::OptionalFlag &flag,
4238 const char *startSpecifier,
4239 unsigned specifierLen) {
4240 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004241 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4242 << ignoredFlag.toString() << flag.toString(),
4243 getLocationOfByte(ignoredFlag.getPosition()),
4244 /*IsStringLocation*/true,
4245 getSpecifierRange(startSpecifier, specifierLen),
4246 FixItHint::CreateRemoval(
4247 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004248}
4249
Ted Kremenek2b417712015-07-02 05:39:16 +00004250// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4251// bool IsStringLocation, Range StringRange,
4252// ArrayRef<FixItHint> Fixit = None);
4253
4254void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4255 unsigned flagLen) {
4256 // Warn about an empty flag.
4257 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4258 getLocationOfByte(startFlag),
4259 /*IsStringLocation*/true,
4260 getSpecifierRange(startFlag, flagLen));
4261}
4262
4263void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4264 unsigned flagLen) {
4265 // Warn about an invalid flag.
4266 auto Range = getSpecifierRange(startFlag, flagLen);
4267 StringRef flag(startFlag, flagLen);
4268 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4269 getLocationOfByte(startFlag),
4270 /*IsStringLocation*/true,
4271 Range, FixItHint::CreateRemoval(Range));
4272}
4273
4274void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4275 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4276 // Warn about using '[...]' without a '@' conversion.
4277 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4278 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4279 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4280 getLocationOfByte(conversionPosition),
4281 /*IsStringLocation*/true,
4282 Range, FixItHint::CreateRemoval(Range));
4283}
4284
Richard Smith55ce3522012-06-25 20:30:08 +00004285// Determines if the specified is a C++ class or struct containing
4286// a member with the specified name and kind (e.g. a CXXMethodDecl named
4287// "c_str()").
4288template<typename MemberKind>
4289static llvm::SmallPtrSet<MemberKind*, 1>
4290CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4291 const RecordType *RT = Ty->getAs<RecordType>();
4292 llvm::SmallPtrSet<MemberKind*, 1> Results;
4293
4294 if (!RT)
4295 return Results;
4296 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004297 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004298 return Results;
4299
Alp Tokerb6cc5922014-05-03 03:45:55 +00004300 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004301 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004302 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004303
4304 // We just need to include all members of the right kind turned up by the
4305 // filter, at this point.
4306 if (S.LookupQualifiedName(R, RT->getDecl()))
4307 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4308 NamedDecl *decl = (*I)->getUnderlyingDecl();
4309 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4310 Results.insert(FK);
4311 }
4312 return Results;
4313}
4314
Richard Smith2868a732014-02-28 01:36:39 +00004315/// Check if we could call '.c_str()' on an object.
4316///
4317/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4318/// allow the call, or if it would be ambiguous).
4319bool Sema::hasCStrMethod(const Expr *E) {
4320 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4321 MethodSet Results =
4322 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4323 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4324 MI != ME; ++MI)
4325 if ((*MI)->getMinRequiredArguments() == 0)
4326 return true;
4327 return false;
4328}
4329
Richard Smith55ce3522012-06-25 20:30:08 +00004330// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004331// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004332// Returns true when a c_str() conversion method is found.
4333bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004334 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004335 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4336
4337 MethodSet Results =
4338 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4339
4340 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4341 MI != ME; ++MI) {
4342 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004343 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004344 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004345 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004346 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004347 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4348 << "c_str()"
4349 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4350 return true;
4351 }
4352 }
4353
4354 return false;
4355}
4356
Ted Kremenekab278de2010-01-28 23:39:18 +00004357bool
Ted Kremenek02087932010-07-16 02:11:22 +00004358CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004359 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004360 const char *startSpecifier,
4361 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004362 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004363 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004364 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004365
Ted Kremenek6cd69422010-07-19 22:01:06 +00004366 if (FS.consumesDataArgument()) {
4367 if (atFirstArg) {
4368 atFirstArg = false;
4369 usesPositionalArgs = FS.usesPositionalArg();
4370 }
4371 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004372 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4373 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004374 return false;
4375 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004376 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004377
Ted Kremenekd1668192010-02-27 01:41:03 +00004378 // First check if the field width, precision, and conversion specifier
4379 // have matching data arguments.
4380 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4381 startSpecifier, specifierLen)) {
4382 return false;
4383 }
4384
4385 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4386 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004387 return false;
4388 }
4389
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004390 if (!CS.consumesDataArgument()) {
4391 // FIXME: Technically specifying a precision or field width here
4392 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004393 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004394 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004395
Ted Kremenek4a49d982010-02-26 19:18:41 +00004396 // Consume the argument.
4397 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004398 if (argIndex < NumDataArgs) {
4399 // The check to see if the argIndex is valid will come later.
4400 // We set the bit here because we may exit early from this
4401 // function if we encounter some other error.
4402 CoveredArgs.set(argIndex);
4403 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004404
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004405 // FreeBSD kernel extensions.
4406 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4407 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4408 // We need at least two arguments.
4409 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4410 return false;
4411
4412 // Claim the second argument.
4413 CoveredArgs.set(argIndex + 1);
4414
4415 // Type check the first argument (int for %b, pointer for %D)
4416 const Expr *Ex = getDataArg(argIndex);
4417 const analyze_printf::ArgType &AT =
4418 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4419 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4420 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4421 EmitFormatDiagnostic(
4422 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4423 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4424 << false << Ex->getSourceRange(),
4425 Ex->getLocStart(), /*IsStringLocation*/false,
4426 getSpecifierRange(startSpecifier, specifierLen));
4427
4428 // Type check the second argument (char * for both %b and %D)
4429 Ex = getDataArg(argIndex + 1);
4430 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4431 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4432 EmitFormatDiagnostic(
4433 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4434 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4435 << false << Ex->getSourceRange(),
4436 Ex->getLocStart(), /*IsStringLocation*/false,
4437 getSpecifierRange(startSpecifier, specifierLen));
4438
4439 return true;
4440 }
4441
Ted Kremenek4a49d982010-02-26 19:18:41 +00004442 // Check for using an Objective-C specific conversion specifier
4443 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004444 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004445 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4446 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004447 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004448
Tom Careb49ec692010-06-17 19:00:27 +00004449 // Check for invalid use of field width
4450 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004451 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004452 startSpecifier, specifierLen);
4453 }
4454
4455 // Check for invalid use of precision
4456 if (!FS.hasValidPrecision()) {
4457 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4458 startSpecifier, specifierLen);
4459 }
4460
4461 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004462 if (!FS.hasValidThousandsGroupingPrefix())
4463 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004464 if (!FS.hasValidLeadingZeros())
4465 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4466 if (!FS.hasValidPlusPrefix())
4467 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004468 if (!FS.hasValidSpacePrefix())
4469 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004470 if (!FS.hasValidAlternativeForm())
4471 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4472 if (!FS.hasValidLeftJustified())
4473 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4474
4475 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004476 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4477 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4478 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004479 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4480 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4481 startSpecifier, specifierLen);
4482
4483 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004484 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004485 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4486 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004487 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004488 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004489 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004490 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4491 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004492
Jordan Rose92303592012-09-08 04:00:03 +00004493 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4494 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4495
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004496 // The remaining checks depend on the data arguments.
4497 if (HasVAListArg)
4498 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004499
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004500 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004501 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004502
Jordan Rose58bbe422012-07-19 18:10:08 +00004503 const Expr *Arg = getDataArg(argIndex);
4504 if (!Arg)
4505 return true;
4506
4507 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004508}
4509
Jordan Roseaee34382012-09-05 22:56:26 +00004510static bool requiresParensToAddCast(const Expr *E) {
4511 // FIXME: We should have a general way to reason about operator
4512 // precedence and whether parens are actually needed here.
4513 // Take care of a few common cases where they aren't.
4514 const Expr *Inside = E->IgnoreImpCasts();
4515 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4516 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4517
4518 switch (Inside->getStmtClass()) {
4519 case Stmt::ArraySubscriptExprClass:
4520 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004521 case Stmt::CharacterLiteralClass:
4522 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004523 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004524 case Stmt::FloatingLiteralClass:
4525 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004526 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004527 case Stmt::ObjCArrayLiteralClass:
4528 case Stmt::ObjCBoolLiteralExprClass:
4529 case Stmt::ObjCBoxedExprClass:
4530 case Stmt::ObjCDictionaryLiteralClass:
4531 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004532 case Stmt::ObjCIvarRefExprClass:
4533 case Stmt::ObjCMessageExprClass:
4534 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004535 case Stmt::ObjCStringLiteralClass:
4536 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004537 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004538 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004539 case Stmt::UnaryOperatorClass:
4540 return false;
4541 default:
4542 return true;
4543 }
4544}
4545
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004546static std::pair<QualType, StringRef>
4547shouldNotPrintDirectly(const ASTContext &Context,
4548 QualType IntendedTy,
4549 const Expr *E) {
4550 // Use a 'while' to peel off layers of typedefs.
4551 QualType TyTy = IntendedTy;
4552 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4553 StringRef Name = UserTy->getDecl()->getName();
4554 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4555 .Case("NSInteger", Context.LongTy)
4556 .Case("NSUInteger", Context.UnsignedLongTy)
4557 .Case("SInt32", Context.IntTy)
4558 .Case("UInt32", Context.UnsignedIntTy)
4559 .Default(QualType());
4560
4561 if (!CastTy.isNull())
4562 return std::make_pair(CastTy, Name);
4563
4564 TyTy = UserTy->desugar();
4565 }
4566
4567 // Strip parens if necessary.
4568 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4569 return shouldNotPrintDirectly(Context,
4570 PE->getSubExpr()->getType(),
4571 PE->getSubExpr());
4572
4573 // If this is a conditional expression, then its result type is constructed
4574 // via usual arithmetic conversions and thus there might be no necessary
4575 // typedef sugar there. Recurse to operands to check for NSInteger &
4576 // Co. usage condition.
4577 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4578 QualType TrueTy, FalseTy;
4579 StringRef TrueName, FalseName;
4580
4581 std::tie(TrueTy, TrueName) =
4582 shouldNotPrintDirectly(Context,
4583 CO->getTrueExpr()->getType(),
4584 CO->getTrueExpr());
4585 std::tie(FalseTy, FalseName) =
4586 shouldNotPrintDirectly(Context,
4587 CO->getFalseExpr()->getType(),
4588 CO->getFalseExpr());
4589
4590 if (TrueTy == FalseTy)
4591 return std::make_pair(TrueTy, TrueName);
4592 else if (TrueTy.isNull())
4593 return std::make_pair(FalseTy, FalseName);
4594 else if (FalseTy.isNull())
4595 return std::make_pair(TrueTy, TrueName);
4596 }
4597
4598 return std::make_pair(QualType(), StringRef());
4599}
4600
Richard Smith55ce3522012-06-25 20:30:08 +00004601bool
4602CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4603 const char *StartSpecifier,
4604 unsigned SpecifierLen,
4605 const Expr *E) {
4606 using namespace analyze_format_string;
4607 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004608 // Now type check the data expression that matches the
4609 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004610 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4611 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004612 if (!AT.isValid())
4613 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004614
Jordan Rose598ec092012-12-05 18:44:40 +00004615 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004616 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4617 ExprTy = TET->getUnderlyingExpr()->getType();
4618 }
4619
Seth Cantrellb4802962015-03-04 03:12:10 +00004620 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4621
4622 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004623 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004624 }
Jordan Rose98709982012-06-04 22:48:57 +00004625
Jordan Rose22b74712012-09-05 22:56:19 +00004626 // Look through argument promotions for our error message's reported type.
4627 // This includes the integral and floating promotions, but excludes array
4628 // and function pointer decay; seeing that an argument intended to be a
4629 // string has type 'char [6]' is probably more confusing than 'char *'.
4630 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4631 if (ICE->getCastKind() == CK_IntegralCast ||
4632 ICE->getCastKind() == CK_FloatingCast) {
4633 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004634 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004635
4636 // Check if we didn't match because of an implicit cast from a 'char'
4637 // or 'short' to an 'int'. This is done because printf is a varargs
4638 // function.
4639 if (ICE->getType() == S.Context.IntTy ||
4640 ICE->getType() == S.Context.UnsignedIntTy) {
4641 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004642 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004643 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004644 }
Jordan Rose98709982012-06-04 22:48:57 +00004645 }
Jordan Rose598ec092012-12-05 18:44:40 +00004646 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4647 // Special case for 'a', which has type 'int' in C.
4648 // Note, however, that we do /not/ want to treat multibyte constants like
4649 // 'MooV' as characters! This form is deprecated but still exists.
4650 if (ExprTy == S.Context.IntTy)
4651 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4652 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004653 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004654
Jordan Rosebc53ed12014-05-31 04:12:14 +00004655 // Look through enums to their underlying type.
4656 bool IsEnum = false;
4657 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4658 ExprTy = EnumTy->getDecl()->getIntegerType();
4659 IsEnum = true;
4660 }
4661
Jordan Rose0e5badd2012-12-05 18:44:49 +00004662 // %C in an Objective-C context prints a unichar, not a wchar_t.
4663 // If the argument is an integer of some kind, believe the %C and suggest
4664 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004665 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004666 if (ObjCContext &&
4667 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4668 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4669 !ExprTy->isCharType()) {
4670 // 'unichar' is defined as a typedef of unsigned short, but we should
4671 // prefer using the typedef if it is visible.
4672 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004673
4674 // While we are here, check if the value is an IntegerLiteral that happens
4675 // to be within the valid range.
4676 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4677 const llvm::APInt &V = IL->getValue();
4678 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4679 return true;
4680 }
4681
Jordan Rose0e5badd2012-12-05 18:44:49 +00004682 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4683 Sema::LookupOrdinaryName);
4684 if (S.LookupName(Result, S.getCurScope())) {
4685 NamedDecl *ND = Result.getFoundDecl();
4686 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4687 if (TD->getUnderlyingType() == IntendedTy)
4688 IntendedTy = S.Context.getTypedefType(TD);
4689 }
4690 }
4691 }
4692
4693 // Special-case some of Darwin's platform-independence types by suggesting
4694 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004695 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004696 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004697 QualType CastTy;
4698 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4699 if (!CastTy.isNull()) {
4700 IntendedTy = CastTy;
4701 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004702 }
4703 }
4704
Jordan Rose22b74712012-09-05 22:56:19 +00004705 // We may be able to offer a FixItHint if it is a supported type.
4706 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004707 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004708 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004709
Jordan Rose22b74712012-09-05 22:56:19 +00004710 if (success) {
4711 // Get the fix string from the fixed format specifier
4712 SmallString<16> buf;
4713 llvm::raw_svector_ostream os(buf);
4714 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004715
Jordan Roseaee34382012-09-05 22:56:26 +00004716 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4717
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004718 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004719 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4720 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4721 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4722 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004723 // In this case, the specifier is wrong and should be changed to match
4724 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004725 EmitFormatDiagnostic(S.PDiag(diag)
4726 << AT.getRepresentativeTypeName(S.Context)
4727 << IntendedTy << IsEnum << E->getSourceRange(),
4728 E->getLocStart(),
4729 /*IsStringLocation*/ false, SpecRange,
4730 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004731 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004732 // The canonical type for formatting this value is different from the
4733 // actual type of the expression. (This occurs, for example, with Darwin's
4734 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4735 // should be printed as 'long' for 64-bit compatibility.)
4736 // Rather than emitting a normal format/argument mismatch, we want to
4737 // add a cast to the recommended type (and correct the format string
4738 // if necessary).
4739 SmallString<16> CastBuf;
4740 llvm::raw_svector_ostream CastFix(CastBuf);
4741 CastFix << "(";
4742 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4743 CastFix << ")";
4744
4745 SmallVector<FixItHint,4> Hints;
4746 if (!AT.matchesType(S.Context, IntendedTy))
4747 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4748
4749 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4750 // If there's already a cast present, just replace it.
4751 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4752 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4753
4754 } else if (!requiresParensToAddCast(E)) {
4755 // If the expression has high enough precedence,
4756 // just write the C-style cast.
4757 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4758 CastFix.str()));
4759 } else {
4760 // Otherwise, add parens around the expression as well as the cast.
4761 CastFix << "(";
4762 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4763 CastFix.str()));
4764
Alp Tokerb6cc5922014-05-03 03:45:55 +00004765 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004766 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4767 }
4768
Jordan Rose0e5badd2012-12-05 18:44:49 +00004769 if (ShouldNotPrintDirectly) {
4770 // The expression has a type that should not be printed directly.
4771 // We extract the name from the typedef because we don't want to show
4772 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004773 StringRef Name;
4774 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4775 Name = TypedefTy->getDecl()->getName();
4776 else
4777 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004778 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004779 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004780 << E->getSourceRange(),
4781 E->getLocStart(), /*IsStringLocation=*/false,
4782 SpecRange, Hints);
4783 } else {
4784 // In this case, the expression could be printed using a different
4785 // specifier, but we've decided that the specifier is probably correct
4786 // and we should cast instead. Just use the normal warning message.
4787 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004788 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4789 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004790 << E->getSourceRange(),
4791 E->getLocStart(), /*IsStringLocation*/false,
4792 SpecRange, Hints);
4793 }
Jordan Roseaee34382012-09-05 22:56:26 +00004794 }
Jordan Rose22b74712012-09-05 22:56:19 +00004795 } else {
4796 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4797 SpecifierLen);
4798 // Since the warning for passing non-POD types to variadic functions
4799 // was deferred until now, we emit a warning for non-POD
4800 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004801 switch (S.isValidVarArgType(ExprTy)) {
4802 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004803 case Sema::VAK_ValidInCXX11: {
4804 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4805 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4806 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4807 }
Richard Smithd7293d72013-08-05 18:49:43 +00004808
Seth Cantrellb4802962015-03-04 03:12:10 +00004809 EmitFormatDiagnostic(
4810 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4811 << IsEnum << CSR << E->getSourceRange(),
4812 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4813 break;
4814 }
Richard Smithd7293d72013-08-05 18:49:43 +00004815 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004816 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004817 EmitFormatDiagnostic(
4818 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004819 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004820 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004821 << CallType
4822 << AT.getRepresentativeTypeName(S.Context)
4823 << CSR
4824 << E->getSourceRange(),
4825 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004826 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004827 break;
4828
4829 case Sema::VAK_Invalid:
4830 if (ExprTy->isObjCObjectType())
4831 EmitFormatDiagnostic(
4832 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4833 << S.getLangOpts().CPlusPlus11
4834 << ExprTy
4835 << CallType
4836 << AT.getRepresentativeTypeName(S.Context)
4837 << CSR
4838 << E->getSourceRange(),
4839 E->getLocStart(), /*IsStringLocation*/false, CSR);
4840 else
4841 // FIXME: If this is an initializer list, suggest removing the braces
4842 // or inserting a cast to the target type.
4843 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4844 << isa<InitListExpr>(E) << ExprTy << CallType
4845 << AT.getRepresentativeTypeName(S.Context)
4846 << E->getSourceRange();
4847 break;
4848 }
4849
4850 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4851 "format string specifier index out of range");
4852 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004853 }
4854
Ted Kremenekab278de2010-01-28 23:39:18 +00004855 return true;
4856}
4857
Ted Kremenek02087932010-07-16 02:11:22 +00004858//===--- CHECK: Scanf format string checking ------------------------------===//
4859
4860namespace {
4861class CheckScanfHandler : public CheckFormatHandler {
4862public:
4863 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4864 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004865 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004866 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004867 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004868 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004869 llvm::SmallBitVector &CheckedVarArgs,
4870 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004871 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4872 numDataArgs, beg, hasVAListArg,
4873 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004874 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004875 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004876
4877 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4878 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004879 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004880
4881 bool HandleInvalidScanfConversionSpecifier(
4882 const analyze_scanf::ScanfSpecifier &FS,
4883 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004884 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004885
Craig Toppere14c0f82014-03-12 04:55:44 +00004886 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004887};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004888} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004889
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004890void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4891 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004892 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4893 getLocationOfByte(end), /*IsStringLocation*/true,
4894 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004895}
4896
Ted Kremenekce815422010-07-19 21:25:57 +00004897bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4898 const analyze_scanf::ScanfSpecifier &FS,
4899 const char *startSpecifier,
4900 unsigned specifierLen) {
4901
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004902 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004903 FS.getConversionSpecifier();
4904
4905 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4906 getLocationOfByte(CS.getStart()),
4907 startSpecifier, specifierLen,
4908 CS.getStart(), CS.getLength());
4909}
4910
Ted Kremenek02087932010-07-16 02:11:22 +00004911bool CheckScanfHandler::HandleScanfSpecifier(
4912 const analyze_scanf::ScanfSpecifier &FS,
4913 const char *startSpecifier,
4914 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00004915 using namespace analyze_scanf;
4916 using namespace analyze_format_string;
4917
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004918 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004919
Ted Kremenek6cd69422010-07-19 22:01:06 +00004920 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4921 // be used to decide if we are using positional arguments consistently.
4922 if (FS.consumesDataArgument()) {
4923 if (atFirstArg) {
4924 atFirstArg = false;
4925 usesPositionalArgs = FS.usesPositionalArg();
4926 }
4927 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004928 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4929 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004930 return false;
4931 }
Ted Kremenek02087932010-07-16 02:11:22 +00004932 }
4933
4934 // Check if the field with is non-zero.
4935 const OptionalAmount &Amt = FS.getFieldWidth();
4936 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4937 if (Amt.getConstantAmount() == 0) {
4938 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4939 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004940 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4941 getLocationOfByte(Amt.getStart()),
4942 /*IsStringLocation*/true, R,
4943 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004944 }
4945 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004946
Ted Kremenek02087932010-07-16 02:11:22 +00004947 if (!FS.consumesDataArgument()) {
4948 // FIXME: Technically specifying a precision or field width here
4949 // makes no sense. Worth issuing a warning at some point.
4950 return true;
4951 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004952
Ted Kremenek02087932010-07-16 02:11:22 +00004953 // Consume the argument.
4954 unsigned argIndex = FS.getArgIndex();
4955 if (argIndex < NumDataArgs) {
4956 // The check to see if the argIndex is valid will come later.
4957 // We set the bit here because we may exit early from this
4958 // function if we encounter some other error.
4959 CoveredArgs.set(argIndex);
4960 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004961
Ted Kremenek4407ea42010-07-20 20:04:47 +00004962 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004963 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004964 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4965 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004966 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004967 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004968 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004969 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4970 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004971
Jordan Rose92303592012-09-08 04:00:03 +00004972 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4973 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4974
Ted Kremenek02087932010-07-16 02:11:22 +00004975 // The remaining checks depend on the data arguments.
4976 if (HasVAListArg)
4977 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004978
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004979 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004980 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004981
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004982 // Check that the argument type matches the format specifier.
4983 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004984 if (!Ex)
4985 return true;
4986
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004987 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004988
4989 if (!AT.isValid()) {
4990 return true;
4991 }
4992
Seth Cantrellb4802962015-03-04 03:12:10 +00004993 analyze_format_string::ArgType::MatchKind match =
4994 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004995 if (match == analyze_format_string::ArgType::Match) {
4996 return true;
4997 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004998
Seth Cantrell79340072015-03-04 05:58:08 +00004999 ScanfSpecifier fixedFS = FS;
5000 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5001 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005002
Seth Cantrell79340072015-03-04 05:58:08 +00005003 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5004 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5005 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5006 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005007
Seth Cantrell79340072015-03-04 05:58:08 +00005008 if (success) {
5009 // Get the fix string from the fixed format specifier.
5010 SmallString<128> buf;
5011 llvm::raw_svector_ostream os(buf);
5012 fixedFS.toString(os);
5013
5014 EmitFormatDiagnostic(
5015 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5016 << Ex->getType() << false << Ex->getSourceRange(),
5017 Ex->getLocStart(),
5018 /*IsStringLocation*/ false,
5019 getSpecifierRange(startSpecifier, specifierLen),
5020 FixItHint::CreateReplacement(
5021 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5022 } else {
5023 EmitFormatDiagnostic(S.PDiag(diag)
5024 << AT.getRepresentativeTypeName(S.Context)
5025 << Ex->getType() << false << Ex->getSourceRange(),
5026 Ex->getLocStart(),
5027 /*IsStringLocation*/ false,
5028 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005029 }
5030
Ted Kremenek02087932010-07-16 02:11:22 +00005031 return true;
5032}
5033
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005034static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5035 const Expr *OrigFormatExpr,
5036 ArrayRef<const Expr *> Args,
5037 bool HasVAListArg, unsigned format_idx,
5038 unsigned firstDataArg,
5039 Sema::FormatStringType Type,
5040 bool inFunctionCall,
5041 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005042 llvm::SmallBitVector &CheckedVarArgs,
5043 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005044 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005045 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005046 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005047 S, inFunctionCall, Args[format_idx],
5048 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005049 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005050 return;
5051 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005052
Ted Kremenekab278de2010-01-28 23:39:18 +00005053 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005054 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005055 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005056 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005057 const ConstantArrayType *T =
5058 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005059 assert(T && "String literal not of constant array type!");
5060 size_t TypeSize = T->getSize().getZExtValue();
5061 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005062 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005063
5064 // Emit a warning if the string literal is truncated and does not contain an
5065 // embedded null character.
5066 if (TypeSize <= StrRef.size() &&
5067 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5068 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005069 S, inFunctionCall, Args[format_idx],
5070 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005071 FExpr->getLocStart(),
5072 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5073 return;
5074 }
5075
Ted Kremenekab278de2010-01-28 23:39:18 +00005076 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005077 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005078 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005079 S, inFunctionCall, Args[format_idx],
5080 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005081 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005082 return;
5083 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005084
5085 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5086 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5087 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5088 numDataArgs, (Type == Sema::FST_NSString ||
5089 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005090 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005091 inFunctionCall, CallType, CheckedVarArgs,
5092 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005093
Hans Wennborg23926bd2011-12-15 10:25:47 +00005094 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005095 S.getLangOpts(),
5096 S.Context.getTargetInfo(),
5097 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005098 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005099 } else if (Type == Sema::FST_Scanf) {
5100 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005101 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005102 inFunctionCall, CallType, CheckedVarArgs,
5103 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005104
Hans Wennborg23926bd2011-12-15 10:25:47 +00005105 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005106 S.getLangOpts(),
5107 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005108 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005109 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005110}
5111
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005112bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5113 // Str - The format string. NOTE: this is NOT null-terminated!
5114 StringRef StrRef = FExpr->getString();
5115 const char *Str = StrRef.data();
5116 // Account for cases where the string literal is truncated in a declaration.
5117 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5118 assert(T && "String literal not of constant array type!");
5119 size_t TypeSize = T->getSize().getZExtValue();
5120 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5121 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5122 getLangOpts(),
5123 Context.getTargetInfo());
5124}
5125
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005126//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5127
5128// Returns the related absolute value function that is larger, of 0 if one
5129// does not exist.
5130static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5131 switch (AbsFunction) {
5132 default:
5133 return 0;
5134
5135 case Builtin::BI__builtin_abs:
5136 return Builtin::BI__builtin_labs;
5137 case Builtin::BI__builtin_labs:
5138 return Builtin::BI__builtin_llabs;
5139 case Builtin::BI__builtin_llabs:
5140 return 0;
5141
5142 case Builtin::BI__builtin_fabsf:
5143 return Builtin::BI__builtin_fabs;
5144 case Builtin::BI__builtin_fabs:
5145 return Builtin::BI__builtin_fabsl;
5146 case Builtin::BI__builtin_fabsl:
5147 return 0;
5148
5149 case Builtin::BI__builtin_cabsf:
5150 return Builtin::BI__builtin_cabs;
5151 case Builtin::BI__builtin_cabs:
5152 return Builtin::BI__builtin_cabsl;
5153 case Builtin::BI__builtin_cabsl:
5154 return 0;
5155
5156 case Builtin::BIabs:
5157 return Builtin::BIlabs;
5158 case Builtin::BIlabs:
5159 return Builtin::BIllabs;
5160 case Builtin::BIllabs:
5161 return 0;
5162
5163 case Builtin::BIfabsf:
5164 return Builtin::BIfabs;
5165 case Builtin::BIfabs:
5166 return Builtin::BIfabsl;
5167 case Builtin::BIfabsl:
5168 return 0;
5169
5170 case Builtin::BIcabsf:
5171 return Builtin::BIcabs;
5172 case Builtin::BIcabs:
5173 return Builtin::BIcabsl;
5174 case Builtin::BIcabsl:
5175 return 0;
5176 }
5177}
5178
5179// Returns the argument type of the absolute value function.
5180static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5181 unsigned AbsType) {
5182 if (AbsType == 0)
5183 return QualType();
5184
5185 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5186 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5187 if (Error != ASTContext::GE_None)
5188 return QualType();
5189
5190 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5191 if (!FT)
5192 return QualType();
5193
5194 if (FT->getNumParams() != 1)
5195 return QualType();
5196
5197 return FT->getParamType(0);
5198}
5199
5200// Returns the best absolute value function, or zero, based on type and
5201// current absolute value function.
5202static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5203 unsigned AbsFunctionKind) {
5204 unsigned BestKind = 0;
5205 uint64_t ArgSize = Context.getTypeSize(ArgType);
5206 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5207 Kind = getLargerAbsoluteValueFunction(Kind)) {
5208 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5209 if (Context.getTypeSize(ParamType) >= ArgSize) {
5210 if (BestKind == 0)
5211 BestKind = Kind;
5212 else if (Context.hasSameType(ParamType, ArgType)) {
5213 BestKind = Kind;
5214 break;
5215 }
5216 }
5217 }
5218 return BestKind;
5219}
5220
5221enum AbsoluteValueKind {
5222 AVK_Integer,
5223 AVK_Floating,
5224 AVK_Complex
5225};
5226
5227static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5228 if (T->isIntegralOrEnumerationType())
5229 return AVK_Integer;
5230 if (T->isRealFloatingType())
5231 return AVK_Floating;
5232 if (T->isAnyComplexType())
5233 return AVK_Complex;
5234
5235 llvm_unreachable("Type not integer, floating, or complex");
5236}
5237
5238// Changes the absolute value function to a different type. Preserves whether
5239// the function is a builtin.
5240static unsigned changeAbsFunction(unsigned AbsKind,
5241 AbsoluteValueKind ValueKind) {
5242 switch (ValueKind) {
5243 case AVK_Integer:
5244 switch (AbsKind) {
5245 default:
5246 return 0;
5247 case Builtin::BI__builtin_fabsf:
5248 case Builtin::BI__builtin_fabs:
5249 case Builtin::BI__builtin_fabsl:
5250 case Builtin::BI__builtin_cabsf:
5251 case Builtin::BI__builtin_cabs:
5252 case Builtin::BI__builtin_cabsl:
5253 return Builtin::BI__builtin_abs;
5254 case Builtin::BIfabsf:
5255 case Builtin::BIfabs:
5256 case Builtin::BIfabsl:
5257 case Builtin::BIcabsf:
5258 case Builtin::BIcabs:
5259 case Builtin::BIcabsl:
5260 return Builtin::BIabs;
5261 }
5262 case AVK_Floating:
5263 switch (AbsKind) {
5264 default:
5265 return 0;
5266 case Builtin::BI__builtin_abs:
5267 case Builtin::BI__builtin_labs:
5268 case Builtin::BI__builtin_llabs:
5269 case Builtin::BI__builtin_cabsf:
5270 case Builtin::BI__builtin_cabs:
5271 case Builtin::BI__builtin_cabsl:
5272 return Builtin::BI__builtin_fabsf;
5273 case Builtin::BIabs:
5274 case Builtin::BIlabs:
5275 case Builtin::BIllabs:
5276 case Builtin::BIcabsf:
5277 case Builtin::BIcabs:
5278 case Builtin::BIcabsl:
5279 return Builtin::BIfabsf;
5280 }
5281 case AVK_Complex:
5282 switch (AbsKind) {
5283 default:
5284 return 0;
5285 case Builtin::BI__builtin_abs:
5286 case Builtin::BI__builtin_labs:
5287 case Builtin::BI__builtin_llabs:
5288 case Builtin::BI__builtin_fabsf:
5289 case Builtin::BI__builtin_fabs:
5290 case Builtin::BI__builtin_fabsl:
5291 return Builtin::BI__builtin_cabsf;
5292 case Builtin::BIabs:
5293 case Builtin::BIlabs:
5294 case Builtin::BIllabs:
5295 case Builtin::BIfabsf:
5296 case Builtin::BIfabs:
5297 case Builtin::BIfabsl:
5298 return Builtin::BIcabsf;
5299 }
5300 }
5301 llvm_unreachable("Unable to convert function");
5302}
5303
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005304static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005305 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5306 if (!FnInfo)
5307 return 0;
5308
5309 switch (FDecl->getBuiltinID()) {
5310 default:
5311 return 0;
5312 case Builtin::BI__builtin_abs:
5313 case Builtin::BI__builtin_fabs:
5314 case Builtin::BI__builtin_fabsf:
5315 case Builtin::BI__builtin_fabsl:
5316 case Builtin::BI__builtin_labs:
5317 case Builtin::BI__builtin_llabs:
5318 case Builtin::BI__builtin_cabs:
5319 case Builtin::BI__builtin_cabsf:
5320 case Builtin::BI__builtin_cabsl:
5321 case Builtin::BIabs:
5322 case Builtin::BIlabs:
5323 case Builtin::BIllabs:
5324 case Builtin::BIfabs:
5325 case Builtin::BIfabsf:
5326 case Builtin::BIfabsl:
5327 case Builtin::BIcabs:
5328 case Builtin::BIcabsf:
5329 case Builtin::BIcabsl:
5330 return FDecl->getBuiltinID();
5331 }
5332 llvm_unreachable("Unknown Builtin type");
5333}
5334
5335// If the replacement is valid, emit a note with replacement function.
5336// Additionally, suggest including the proper header if not already included.
5337static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005338 unsigned AbsKind, QualType ArgType) {
5339 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005340 const char *HeaderName = nullptr;
5341 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005342 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5343 FunctionName = "std::abs";
5344 if (ArgType->isIntegralOrEnumerationType()) {
5345 HeaderName = "cstdlib";
5346 } else if (ArgType->isRealFloatingType()) {
5347 HeaderName = "cmath";
5348 } else {
5349 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005350 }
Richard Trieubeffb832014-04-15 23:47:53 +00005351
5352 // Lookup all std::abs
5353 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005354 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005355 R.suppressDiagnostics();
5356 S.LookupQualifiedName(R, Std);
5357
5358 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005359 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005360 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5361 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5362 } else {
5363 FDecl = dyn_cast<FunctionDecl>(I);
5364 }
5365 if (!FDecl)
5366 continue;
5367
5368 // Found std::abs(), check that they are the right ones.
5369 if (FDecl->getNumParams() != 1)
5370 continue;
5371
5372 // Check that the parameter type can handle the argument.
5373 QualType ParamType = FDecl->getParamDecl(0)->getType();
5374 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5375 S.Context.getTypeSize(ArgType) <=
5376 S.Context.getTypeSize(ParamType)) {
5377 // Found a function, don't need the header hint.
5378 EmitHeaderHint = false;
5379 break;
5380 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005381 }
Richard Trieubeffb832014-04-15 23:47:53 +00005382 }
5383 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005384 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005385 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5386
5387 if (HeaderName) {
5388 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5389 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5390 R.suppressDiagnostics();
5391 S.LookupName(R, S.getCurScope());
5392
5393 if (R.isSingleResult()) {
5394 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5395 if (FD && FD->getBuiltinID() == AbsKind) {
5396 EmitHeaderHint = false;
5397 } else {
5398 return;
5399 }
5400 } else if (!R.empty()) {
5401 return;
5402 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005403 }
5404 }
5405
5406 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005407 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005408
Richard Trieubeffb832014-04-15 23:47:53 +00005409 if (!HeaderName)
5410 return;
5411
5412 if (!EmitHeaderHint)
5413 return;
5414
Alp Toker5d96e0a2014-07-11 20:53:51 +00005415 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5416 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005417}
5418
5419static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5420 if (!FDecl)
5421 return false;
5422
5423 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5424 return false;
5425
5426 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5427
5428 while (ND && ND->isInlineNamespace()) {
5429 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005430 }
Richard Trieubeffb832014-04-15 23:47:53 +00005431
5432 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5433 return false;
5434
5435 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5436 return false;
5437
5438 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005439}
5440
5441// Warn when using the wrong abs() function.
5442void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5443 const FunctionDecl *FDecl,
5444 IdentifierInfo *FnInfo) {
5445 if (Call->getNumArgs() != 1)
5446 return;
5447
5448 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005449 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5450 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005451 return;
5452
5453 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5454 QualType ParamType = Call->getArg(0)->getType();
5455
Alp Toker5d96e0a2014-07-11 20:53:51 +00005456 // Unsigned types cannot be negative. Suggest removing the absolute value
5457 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005458 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005459 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005460 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005461 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5462 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005463 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005464 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5465 return;
5466 }
5467
David Majnemer7f77eb92015-11-15 03:04:34 +00005468 // Taking the absolute value of a pointer is very suspicious, they probably
5469 // wanted to index into an array, dereference a pointer, call a function, etc.
5470 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5471 unsigned DiagType = 0;
5472 if (ArgType->isFunctionType())
5473 DiagType = 1;
5474 else if (ArgType->isArrayType())
5475 DiagType = 2;
5476
5477 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5478 return;
5479 }
5480
Richard Trieubeffb832014-04-15 23:47:53 +00005481 // std::abs has overloads which prevent most of the absolute value problems
5482 // from occurring.
5483 if (IsStdAbs)
5484 return;
5485
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005486 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5487 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5488
5489 // The argument and parameter are the same kind. Check if they are the right
5490 // size.
5491 if (ArgValueKind == ParamValueKind) {
5492 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5493 return;
5494
5495 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5496 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5497 << FDecl << ArgType << ParamType;
5498
5499 if (NewAbsKind == 0)
5500 return;
5501
5502 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005503 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005504 return;
5505 }
5506
5507 // ArgValueKind != ParamValueKind
5508 // The wrong type of absolute value function was used. Attempt to find the
5509 // proper one.
5510 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5511 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5512 if (NewAbsKind == 0)
5513 return;
5514
5515 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5516 << FDecl << ParamValueKind << ArgValueKind;
5517
5518 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005519 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005520}
5521
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005522//===--- CHECK: Standard memory functions ---------------------------------===//
5523
Nico Weber0e6daef2013-12-26 23:38:39 +00005524/// \brief Takes the expression passed to the size_t parameter of functions
5525/// such as memcmp, strncat, etc and warns if it's a comparison.
5526///
5527/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5528static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5529 IdentifierInfo *FnName,
5530 SourceLocation FnLoc,
5531 SourceLocation RParenLoc) {
5532 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5533 if (!Size)
5534 return false;
5535
5536 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5537 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5538 return false;
5539
Nico Weber0e6daef2013-12-26 23:38:39 +00005540 SourceRange SizeRange = Size->getSourceRange();
5541 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5542 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005543 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005544 << FnName << FixItHint::CreateInsertion(
5545 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005546 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005547 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005548 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005549 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5550 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005551
5552 return true;
5553}
5554
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005555/// \brief Determine whether the given type is or contains a dynamic class type
5556/// (e.g., whether it has a vtable).
5557static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5558 bool &IsContained) {
5559 // Look through array types while ignoring qualifiers.
5560 const Type *Ty = T->getBaseElementTypeUnsafe();
5561 IsContained = false;
5562
5563 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5564 RD = RD ? RD->getDefinition() : nullptr;
5565 if (!RD)
5566 return nullptr;
5567
5568 if (RD->isDynamicClass())
5569 return RD;
5570
5571 // Check all the fields. If any bases were dynamic, the class is dynamic.
5572 // It's impossible for a class to transitively contain itself by value, so
5573 // infinite recursion is impossible.
5574 for (auto *FD : RD->fields()) {
5575 bool SubContained;
5576 if (const CXXRecordDecl *ContainedRD =
5577 getContainedDynamicClass(FD->getType(), SubContained)) {
5578 IsContained = true;
5579 return ContainedRD;
5580 }
5581 }
5582
5583 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005584}
5585
Chandler Carruth889ed862011-06-21 23:04:20 +00005586/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005587/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005588static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005589 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005590 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5591 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5592 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005593
Craig Topperc3ec1492014-05-26 06:22:03 +00005594 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005595}
5596
Chandler Carruth889ed862011-06-21 23:04:20 +00005597/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005598static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005599 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5600 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5601 if (SizeOf->getKind() == clang::UETT_SizeOf)
5602 return SizeOf->getTypeOfArgument();
5603
5604 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005605}
5606
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005607/// \brief Check for dangerous or invalid arguments to memset().
5608///
Chandler Carruthac687262011-06-03 06:23:57 +00005609/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005610/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5611/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005612///
5613/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005614void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005615 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005616 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005617 assert(BId != 0);
5618
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005619 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005620 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005621 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005622 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005623 return;
5624
Anna Zaks22122702012-01-17 00:37:07 +00005625 unsigned LastArg = (BId == Builtin::BImemset ||
5626 BId == Builtin::BIstrndup ? 1 : 2);
5627 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005628 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005629
Nico Weber0e6daef2013-12-26 23:38:39 +00005630 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5631 Call->getLocStart(), Call->getRParenLoc()))
5632 return;
5633
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005634 // We have special checking when the length is a sizeof expression.
5635 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5636 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5637 llvm::FoldingSetNodeID SizeOfArgID;
5638
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005639 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5640 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005641 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005642
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005643 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005644 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005645 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005646 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005647
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005648 // Never warn about void type pointers. This can be used to suppress
5649 // false positives.
5650 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005651 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005652
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005653 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5654 // actually comparing the expressions for equality. Because computing the
5655 // expression IDs can be expensive, we only do this if the diagnostic is
5656 // enabled.
5657 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005658 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5659 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005660 // We only compute IDs for expressions if the warning is enabled, and
5661 // cache the sizeof arg's ID.
5662 if (SizeOfArgID == llvm::FoldingSetNodeID())
5663 SizeOfArg->Profile(SizeOfArgID, Context, true);
5664 llvm::FoldingSetNodeID DestID;
5665 Dest->Profile(DestID, Context, true);
5666 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005667 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5668 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005669 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005670 StringRef ReadableName = FnName->getName();
5671
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005672 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005673 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005674 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005675 if (!PointeeTy->isIncompleteType() &&
5676 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005677 ActionIdx = 2; // If the pointee's size is sizeof(char),
5678 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005679
5680 // If the function is defined as a builtin macro, do not show macro
5681 // expansion.
5682 SourceLocation SL = SizeOfArg->getExprLoc();
5683 SourceRange DSR = Dest->getSourceRange();
5684 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005685 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005686
5687 if (SM.isMacroArgExpansion(SL)) {
5688 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5689 SL = SM.getSpellingLoc(SL);
5690 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5691 SM.getSpellingLoc(DSR.getEnd()));
5692 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5693 SM.getSpellingLoc(SSR.getEnd()));
5694 }
5695
Anna Zaksd08d9152012-05-30 23:14:52 +00005696 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005697 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005698 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005699 << PointeeTy
5700 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005701 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005702 << SSR);
5703 DiagRuntimeBehavior(SL, SizeOfArg,
5704 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5705 << ActionIdx
5706 << SSR);
5707
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005708 break;
5709 }
5710 }
5711
5712 // Also check for cases where the sizeof argument is the exact same
5713 // type as the memory argument, and where it points to a user-defined
5714 // record type.
5715 if (SizeOfArgTy != QualType()) {
5716 if (PointeeTy->isRecordType() &&
5717 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5718 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5719 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5720 << FnName << SizeOfArgTy << ArgIdx
5721 << PointeeTy << Dest->getSourceRange()
5722 << LenExpr->getSourceRange());
5723 break;
5724 }
Nico Weberc5e73862011-06-14 16:14:58 +00005725 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005726 } else if (DestTy->isArrayType()) {
5727 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005728 }
Nico Weberc5e73862011-06-14 16:14:58 +00005729
Nico Weberc44b35e2015-03-21 17:37:46 +00005730 if (PointeeTy == QualType())
5731 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005732
Nico Weberc44b35e2015-03-21 17:37:46 +00005733 // Always complain about dynamic classes.
5734 bool IsContained;
5735 if (const CXXRecordDecl *ContainedRD =
5736 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005737
Nico Weberc44b35e2015-03-21 17:37:46 +00005738 unsigned OperationType = 0;
5739 // "overwritten" if we're warning about the destination for any call
5740 // but memcmp; otherwise a verb appropriate to the call.
5741 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5742 if (BId == Builtin::BImemcpy)
5743 OperationType = 1;
5744 else if(BId == Builtin::BImemmove)
5745 OperationType = 2;
5746 else if (BId == Builtin::BImemcmp)
5747 OperationType = 3;
5748 }
5749
John McCall31168b02011-06-15 23:02:42 +00005750 DiagRuntimeBehavior(
5751 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005752 PDiag(diag::warn_dyn_class_memaccess)
5753 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5754 << FnName << IsContained << ContainedRD << OperationType
5755 << Call->getCallee()->getSourceRange());
5756 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5757 BId != Builtin::BImemset)
5758 DiagRuntimeBehavior(
5759 Dest->getExprLoc(), Dest,
5760 PDiag(diag::warn_arc_object_memaccess)
5761 << ArgIdx << FnName << PointeeTy
5762 << Call->getCallee()->getSourceRange());
5763 else
5764 continue;
5765
5766 DiagRuntimeBehavior(
5767 Dest->getExprLoc(), Dest,
5768 PDiag(diag::note_bad_memaccess_silence)
5769 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5770 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005771 }
5772}
5773
Ted Kremenek6865f772011-08-18 20:55:45 +00005774// A little helper routine: ignore addition and subtraction of integer literals.
5775// This intentionally does not ignore all integer constant expressions because
5776// we don't want to remove sizeof().
5777static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5778 Ex = Ex->IgnoreParenCasts();
5779
5780 for (;;) {
5781 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5782 if (!BO || !BO->isAdditiveOp())
5783 break;
5784
5785 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5786 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5787
5788 if (isa<IntegerLiteral>(RHS))
5789 Ex = LHS;
5790 else if (isa<IntegerLiteral>(LHS))
5791 Ex = RHS;
5792 else
5793 break;
5794 }
5795
5796 return Ex;
5797}
5798
Anna Zaks13b08572012-08-08 21:42:23 +00005799static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5800 ASTContext &Context) {
5801 // Only handle constant-sized or VLAs, but not flexible members.
5802 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5803 // Only issue the FIXIT for arrays of size > 1.
5804 if (CAT->getSize().getSExtValue() <= 1)
5805 return false;
5806 } else if (!Ty->isVariableArrayType()) {
5807 return false;
5808 }
5809 return true;
5810}
5811
Ted Kremenek6865f772011-08-18 20:55:45 +00005812// Warn if the user has made the 'size' argument to strlcpy or strlcat
5813// be the size of the source, instead of the destination.
5814void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5815 IdentifierInfo *FnName) {
5816
5817 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005818 unsigned NumArgs = Call->getNumArgs();
5819 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005820 return;
5821
5822 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5823 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005824 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005825
5826 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5827 Call->getLocStart(), Call->getRParenLoc()))
5828 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005829
5830 // Look for 'strlcpy(dst, x, sizeof(x))'
5831 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5832 CompareWithSrc = Ex;
5833 else {
5834 // Look for 'strlcpy(dst, x, strlen(x))'
5835 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005836 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5837 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005838 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5839 }
5840 }
5841
5842 if (!CompareWithSrc)
5843 return;
5844
5845 // Determine if the argument to sizeof/strlen is equal to the source
5846 // argument. In principle there's all kinds of things you could do
5847 // here, for instance creating an == expression and evaluating it with
5848 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5849 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5850 if (!SrcArgDRE)
5851 return;
5852
5853 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5854 if (!CompareWithSrcDRE ||
5855 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5856 return;
5857
5858 const Expr *OriginalSizeArg = Call->getArg(2);
5859 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5860 << OriginalSizeArg->getSourceRange() << FnName;
5861
5862 // Output a FIXIT hint if the destination is an array (rather than a
5863 // pointer to an array). This could be enhanced to handle some
5864 // pointers if we know the actual size, like if DstArg is 'array+2'
5865 // we could say 'sizeof(array)-2'.
5866 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005867 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005868 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005869
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005870 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005871 llvm::raw_svector_ostream OS(sizeString);
5872 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005873 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005874 OS << ")";
5875
5876 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5877 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5878 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005879}
5880
Anna Zaks314cd092012-02-01 19:08:57 +00005881/// Check if two expressions refer to the same declaration.
5882static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5883 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5884 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5885 return D1->getDecl() == D2->getDecl();
5886 return false;
5887}
5888
5889static const Expr *getStrlenExprArg(const Expr *E) {
5890 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5891 const FunctionDecl *FD = CE->getDirectCallee();
5892 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005893 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005894 return CE->getArg(0)->IgnoreParenCasts();
5895 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005896 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005897}
5898
5899// Warn on anti-patterns as the 'size' argument to strncat.
5900// The correct size argument should look like following:
5901// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5902void Sema::CheckStrncatArguments(const CallExpr *CE,
5903 IdentifierInfo *FnName) {
5904 // Don't crash if the user has the wrong number of arguments.
5905 if (CE->getNumArgs() < 3)
5906 return;
5907 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5908 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5909 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5910
Nico Weber0e6daef2013-12-26 23:38:39 +00005911 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5912 CE->getRParenLoc()))
5913 return;
5914
Anna Zaks314cd092012-02-01 19:08:57 +00005915 // Identify common expressions, which are wrongly used as the size argument
5916 // to strncat and may lead to buffer overflows.
5917 unsigned PatternType = 0;
5918 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5919 // - sizeof(dst)
5920 if (referToTheSameDecl(SizeOfArg, DstArg))
5921 PatternType = 1;
5922 // - sizeof(src)
5923 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5924 PatternType = 2;
5925 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5926 if (BE->getOpcode() == BO_Sub) {
5927 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5928 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5929 // - sizeof(dst) - strlen(dst)
5930 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5931 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5932 PatternType = 1;
5933 // - sizeof(src) - (anything)
5934 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5935 PatternType = 2;
5936 }
5937 }
5938
5939 if (PatternType == 0)
5940 return;
5941
Anna Zaks5069aa32012-02-03 01:27:37 +00005942 // Generate the diagnostic.
5943 SourceLocation SL = LenArg->getLocStart();
5944 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005945 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005946
5947 // If the function is defined as a builtin macro, do not show macro expansion.
5948 if (SM.isMacroArgExpansion(SL)) {
5949 SL = SM.getSpellingLoc(SL);
5950 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5951 SM.getSpellingLoc(SR.getEnd()));
5952 }
5953
Anna Zaks13b08572012-08-08 21:42:23 +00005954 // Check if the destination is an array (rather than a pointer to an array).
5955 QualType DstTy = DstArg->getType();
5956 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5957 Context);
5958 if (!isKnownSizeArray) {
5959 if (PatternType == 1)
5960 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5961 else
5962 Diag(SL, diag::warn_strncat_src_size) << SR;
5963 return;
5964 }
5965
Anna Zaks314cd092012-02-01 19:08:57 +00005966 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005967 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005968 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005969 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005970
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005971 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005972 llvm::raw_svector_ostream OS(sizeString);
5973 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005974 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005975 OS << ") - ";
5976 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005977 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005978 OS << ") - 1";
5979
Anna Zaks5069aa32012-02-03 01:27:37 +00005980 Diag(SL, diag::note_strncat_wrong_size)
5981 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005982}
5983
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005984//===--- CHECK: Return Address of Stack Variable --------------------------===//
5985
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005986static const Expr *EvalVal(const Expr *E,
5987 SmallVectorImpl<const DeclRefExpr *> &refVars,
5988 const Decl *ParentDecl);
5989static const Expr *EvalAddr(const Expr *E,
5990 SmallVectorImpl<const DeclRefExpr *> &refVars,
5991 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005992
5993/// CheckReturnStackAddr - Check if a return statement returns the address
5994/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005995static void
5996CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5997 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005998
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005999 const Expr *stackE = nullptr;
6000 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006001
6002 // Perform checking for returned stack addresses, local blocks,
6003 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006004 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006005 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006006 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006007 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006008 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006009 }
6010
Craig Topperc3ec1492014-05-26 06:22:03 +00006011 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006012 return; // Nothing suspicious was found.
6013
6014 SourceLocation diagLoc;
6015 SourceRange diagRange;
6016 if (refVars.empty()) {
6017 diagLoc = stackE->getLocStart();
6018 diagRange = stackE->getSourceRange();
6019 } else {
6020 // We followed through a reference variable. 'stackE' contains the
6021 // problematic expression but we will warn at the return statement pointing
6022 // at the reference variable. We will later display the "trail" of
6023 // reference variables using notes.
6024 diagLoc = refVars[0]->getLocStart();
6025 diagRange = refVars[0]->getSourceRange();
6026 }
6027
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006028 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6029 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006030 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006031 << DR->getDecl()->getDeclName() << diagRange;
6032 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006033 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006034 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006035 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006036 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00006037 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6038 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006039 }
6040
6041 // Display the "trail" of reference variables that we followed until we
6042 // found the problematic expression using notes.
6043 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006044 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006045 // If this var binds to another reference var, show the range of the next
6046 // var, otherwise the var binds to the problematic expression, in which case
6047 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006048 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6049 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006050 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6051 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006052 }
6053}
6054
6055/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6056/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006057/// to a location on the stack, a local block, an address of a label, or a
6058/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006059/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006060/// encounter a subexpression that (1) clearly does not lead to one of the
6061/// above problematic expressions (2) is something we cannot determine leads to
6062/// a problematic expression based on such local checking.
6063///
6064/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6065/// the expression that they point to. Such variables are added to the
6066/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006067///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006068/// EvalAddr processes expressions that are pointers that are used as
6069/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006070/// At the base case of the recursion is a check for the above problematic
6071/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006072///
6073/// This implementation handles:
6074///
6075/// * pointer-to-pointer casts
6076/// * implicit conversions from array references to pointers
6077/// * taking the address of fields
6078/// * arbitrary interplay between "&" and "*" operators
6079/// * pointer arithmetic from an address of a stack variable
6080/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006081static const Expr *EvalAddr(const Expr *E,
6082 SmallVectorImpl<const DeclRefExpr *> &refVars,
6083 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006084 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006085 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006086
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006087 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006088 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006089 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006090 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006091 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006092
Peter Collingbourne91147592011-04-15 00:35:48 +00006093 E = E->IgnoreParens();
6094
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006095 // Our "symbolic interpreter" is just a dispatch off the currently
6096 // viewed AST node. We then recursively traverse the AST by calling
6097 // EvalAddr and EvalVal appropriately.
6098 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006099 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006100 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006101
Richard Smith40f08eb2014-01-30 22:05:38 +00006102 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006103 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006104 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006105
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006106 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006107 // If this is a reference variable, follow through to the expression that
6108 // it points to.
6109 if (V->hasLocalStorage() &&
6110 V->getType()->isReferenceType() && V->hasInit()) {
6111 // Add the reference variable to the "trail".
6112 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006113 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006114 }
6115
Craig Topperc3ec1492014-05-26 06:22:03 +00006116 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006117 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006118
Chris Lattner934edb22007-12-28 05:31:15 +00006119 case Stmt::UnaryOperatorClass: {
6120 // The only unary operator that make sense to handle here
6121 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006122 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006123
John McCalle3027922010-08-25 11:45:40 +00006124 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006125 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006126 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006127 }
Mike Stump11289f42009-09-09 15:08:12 +00006128
Chris Lattner934edb22007-12-28 05:31:15 +00006129 case Stmt::BinaryOperatorClass: {
6130 // Handle pointer arithmetic. All other binary operators are not valid
6131 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006132 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006133 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006134
John McCalle3027922010-08-25 11:45:40 +00006135 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006136 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006137
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006138 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006139
6140 // Determine which argument is the real pointer base. It could be
6141 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006142 if (!Base->getType()->isPointerType())
6143 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006144
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006145 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006146 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006147 }
Steve Naroff2752a172008-09-10 19:17:48 +00006148
Chris Lattner934edb22007-12-28 05:31:15 +00006149 // For conditional operators we need to see if either the LHS or RHS are
6150 // valid DeclRefExpr*s. If one of them is valid, we return it.
6151 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006152 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006153
Chris Lattner934edb22007-12-28 05:31:15 +00006154 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006155 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006156 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006157 // In C++, we can have a throw-expression, which has 'void' type.
6158 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006159 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006160 return LHS;
6161 }
Chris Lattner934edb22007-12-28 05:31:15 +00006162
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006163 // In C++, we can have a throw-expression, which has 'void' type.
6164 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006165 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006166
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006167 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006168 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006169
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006170 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006171 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006172 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006173 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006174
6175 case Stmt::AddrLabelExprClass:
6176 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006177
John McCall28fc7092011-11-10 05:35:25 +00006178 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006179 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6180 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006181
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006182 // For casts, we need to handle conversions from arrays to
6183 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006184 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006185 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006186 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006187 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006188 case Stmt::CXXStaticCastExprClass:
6189 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006190 case Stmt::CXXConstCastExprClass:
6191 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006192 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006193 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006194 case CK_LValueToRValue:
6195 case CK_NoOp:
6196 case CK_BaseToDerived:
6197 case CK_DerivedToBase:
6198 case CK_UncheckedDerivedToBase:
6199 case CK_Dynamic:
6200 case CK_CPointerToObjCPointerCast:
6201 case CK_BlockPointerToObjCPointerCast:
6202 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006203 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006204
6205 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006206 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006207
Richard Trieudadefde2014-07-02 04:39:38 +00006208 case CK_BitCast:
6209 if (SubExpr->getType()->isAnyPointerType() ||
6210 SubExpr->getType()->isBlockPointerType() ||
6211 SubExpr->getType()->isObjCQualifiedIdType())
6212 return EvalAddr(SubExpr, refVars, ParentDecl);
6213 else
6214 return nullptr;
6215
Eli Friedman8195ad72012-02-23 23:04:32 +00006216 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006217 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006218 }
Chris Lattner934edb22007-12-28 05:31:15 +00006219 }
Mike Stump11289f42009-09-09 15:08:12 +00006220
Douglas Gregorfe314812011-06-21 17:03:29 +00006221 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006222 if (const Expr *Result =
6223 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6224 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006225 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006226 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006227
Chris Lattner934edb22007-12-28 05:31:15 +00006228 // Everything else: we simply don't reason about them.
6229 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006230 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006231 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006232}
Mike Stump11289f42009-09-09 15:08:12 +00006233
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006234/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6235/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006236static const Expr *EvalVal(const Expr *E,
6237 SmallVectorImpl<const DeclRefExpr *> &refVars,
6238 const Decl *ParentDecl) {
6239 do {
6240 // We should only be called for evaluating non-pointer expressions, or
6241 // expressions with a pointer type that are not used as references but
6242 // instead
6243 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006244
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006245 // Our "symbolic interpreter" is just a dispatch off the currently
6246 // viewed AST node. We then recursively traverse the AST by calling
6247 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006248
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006249 E = E->IgnoreParens();
6250 switch (E->getStmtClass()) {
6251 case Stmt::ImplicitCastExprClass: {
6252 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6253 if (IE->getValueKind() == VK_LValue) {
6254 E = IE->getSubExpr();
6255 continue;
6256 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006257 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006258 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006259
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006260 case Stmt::ExprWithCleanupsClass:
6261 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6262 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006263
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006264 case Stmt::DeclRefExprClass: {
6265 // When we hit a DeclRefExpr we are looking at code that refers to a
6266 // variable's name. If it's not a reference variable we check if it has
6267 // local storage within the function, and if so, return the expression.
6268 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6269
6270 // If we leave the immediate function, the lifetime isn't about to end.
6271 if (DR->refersToEnclosingVariableOrCapture())
6272 return nullptr;
6273
6274 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6275 // Check if it refers to itself, e.g. "int& i = i;".
6276 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006277 return DR;
6278
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006279 if (V->hasLocalStorage()) {
6280 if (!V->getType()->isReferenceType())
6281 return DR;
6282
6283 // Reference variable, follow through to the expression that
6284 // it points to.
6285 if (V->hasInit()) {
6286 // Add the reference variable to the "trail".
6287 refVars.push_back(DR);
6288 return EvalVal(V->getInit(), refVars, V);
6289 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006290 }
6291 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006292
6293 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006294 }
Mike Stump11289f42009-09-09 15:08:12 +00006295
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006296 case Stmt::UnaryOperatorClass: {
6297 // The only unary operator that make sense to handle here
6298 // is Deref. All others don't resolve to a "name." This includes
6299 // handling all sorts of rvalues passed to a unary operator.
6300 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006301
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006302 if (U->getOpcode() == UO_Deref)
6303 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006304
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006305 return nullptr;
6306 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006307
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006308 case Stmt::ArraySubscriptExprClass: {
6309 // Array subscripts are potential references to data on the stack. We
6310 // retrieve the DeclRefExpr* for the array variable if it indeed
6311 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006312 const auto *ASE = cast<ArraySubscriptExpr>(E);
6313 if (ASE->isTypeDependent())
6314 return nullptr;
6315 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006316 }
Mike Stump11289f42009-09-09 15:08:12 +00006317
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006318 case Stmt::OMPArraySectionExprClass: {
6319 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6320 ParentDecl);
6321 }
Mike Stump11289f42009-09-09 15:08:12 +00006322
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006323 case Stmt::ConditionalOperatorClass: {
6324 // For conditional operators we need to see if either the LHS or RHS are
6325 // non-NULL Expr's. If one is non-NULL, we return it.
6326 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006327
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006328 // Handle the GNU extension for missing LHS.
6329 if (const Expr *LHSExpr = C->getLHS()) {
6330 // In C++, we can have a throw-expression, which has 'void' type.
6331 if (!LHSExpr->getType()->isVoidType())
6332 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6333 return LHS;
6334 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006335
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006336 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006337 if (C->getRHS()->getType()->isVoidType())
6338 return nullptr;
6339
6340 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006341 }
6342
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006343 // Accesses to members are potential references to data on the stack.
6344 case Stmt::MemberExprClass: {
6345 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006346
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006347 // Check for indirect access. We only want direct field accesses.
6348 if (M->isArrow())
6349 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006350
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006351 // Check whether the member type is itself a reference, in which case
6352 // we're not going to refer to the member, but to what the member refers
6353 // to.
6354 if (M->getMemberDecl()->getType()->isReferenceType())
6355 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006356
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006357 return EvalVal(M->getBase(), refVars, ParentDecl);
6358 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006359
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006360 case Stmt::MaterializeTemporaryExprClass:
6361 if (const Expr *Result =
6362 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6363 refVars, ParentDecl))
6364 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006365 return E;
6366
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006367 default:
6368 // Check that we don't return or take the address of a reference to a
6369 // temporary. This is only useful in C++.
6370 if (!E->isTypeDependent() && E->isRValue())
6371 return E;
6372
6373 // Everything else: we simply don't reason about them.
6374 return nullptr;
6375 }
6376 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006377}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006378
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006379void
6380Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6381 SourceLocation ReturnLoc,
6382 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006383 const AttrVec *Attrs,
6384 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006385 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6386
6387 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006388 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6389 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006390 CheckNonNullExpr(*this, RetValExp))
6391 Diag(ReturnLoc, diag::warn_null_ret)
6392 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006393
6394 // C++11 [basic.stc.dynamic.allocation]p4:
6395 // If an allocation function declared with a non-throwing
6396 // exception-specification fails to allocate storage, it shall return
6397 // a null pointer. Any other allocation function that fails to allocate
6398 // storage shall indicate failure only by throwing an exception [...]
6399 if (FD) {
6400 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6401 if (Op == OO_New || Op == OO_Array_New) {
6402 const FunctionProtoType *Proto
6403 = FD->getType()->castAs<FunctionProtoType>();
6404 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6405 CheckNonNullExpr(*this, RetValExp))
6406 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6407 << FD << getLangOpts().CPlusPlus11;
6408 }
6409 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006410}
6411
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006412//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6413
6414/// Check for comparisons of floating point operands using != and ==.
6415/// Issue a warning if these are no self-comparisons, as they are not likely
6416/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006417void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006418 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6419 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006420
6421 // Special case: check for x == x (which is OK).
6422 // Do not emit warnings for such cases.
6423 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6424 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6425 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006426 return;
Mike Stump11289f42009-09-09 15:08:12 +00006427
Ted Kremenekeda40e22007-11-29 00:59:04 +00006428 // Special case: check for comparisons against literals that can be exactly
6429 // represented by APFloat. In such cases, do not emit a warning. This
6430 // is a heuristic: often comparison against such literals are used to
6431 // detect if a value in a variable has not changed. This clearly can
6432 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006433 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6434 if (FLL->isExact())
6435 return;
6436 } else
6437 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6438 if (FLR->isExact())
6439 return;
Mike Stump11289f42009-09-09 15:08:12 +00006440
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006441 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006442 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006443 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006444 return;
Mike Stump11289f42009-09-09 15:08:12 +00006445
David Blaikie1f4ff152012-07-16 20:47:22 +00006446 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006447 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006448 return;
Mike Stump11289f42009-09-09 15:08:12 +00006449
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006450 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006451 Diag(Loc, diag::warn_floatingpoint_eq)
6452 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006453}
John McCallca01b222010-01-04 23:21:16 +00006454
John McCall70aa5392010-01-06 05:24:50 +00006455//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6456//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006457
John McCall70aa5392010-01-06 05:24:50 +00006458namespace {
John McCallca01b222010-01-04 23:21:16 +00006459
John McCall70aa5392010-01-06 05:24:50 +00006460/// Structure recording the 'active' range of an integer-valued
6461/// expression.
6462struct IntRange {
6463 /// The number of bits active in the int.
6464 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006465
John McCall70aa5392010-01-06 05:24:50 +00006466 /// True if the int is known not to have negative values.
6467 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006468
John McCall70aa5392010-01-06 05:24:50 +00006469 IntRange(unsigned Width, bool NonNegative)
6470 : Width(Width), NonNegative(NonNegative)
6471 {}
John McCallca01b222010-01-04 23:21:16 +00006472
John McCall817d4af2010-11-10 23:38:19 +00006473 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006474 static IntRange forBoolType() {
6475 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006476 }
6477
John McCall817d4af2010-11-10 23:38:19 +00006478 /// Returns the range of an opaque value of the given integral type.
6479 static IntRange forValueOfType(ASTContext &C, QualType T) {
6480 return forValueOfCanonicalType(C,
6481 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006482 }
6483
John McCall817d4af2010-11-10 23:38:19 +00006484 /// Returns the range of an opaque value of a canonical integral type.
6485 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006486 assert(T->isCanonicalUnqualified());
6487
6488 if (const VectorType *VT = dyn_cast<VectorType>(T))
6489 T = VT->getElementType().getTypePtr();
6490 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6491 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006492 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6493 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006494
David Majnemer6a426652013-06-07 22:07:20 +00006495 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006496 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006497 EnumDecl *Enum = ET->getDecl();
6498 if (!Enum->isCompleteDefinition())
6499 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006500
David Majnemer6a426652013-06-07 22:07:20 +00006501 unsigned NumPositive = Enum->getNumPositiveBits();
6502 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006503
David Majnemer6a426652013-06-07 22:07:20 +00006504 if (NumNegative == 0)
6505 return IntRange(NumPositive, true/*NonNegative*/);
6506 else
6507 return IntRange(std::max(NumPositive + 1, NumNegative),
6508 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006509 }
John McCall70aa5392010-01-06 05:24:50 +00006510
6511 const BuiltinType *BT = cast<BuiltinType>(T);
6512 assert(BT->isInteger());
6513
6514 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6515 }
6516
John McCall817d4af2010-11-10 23:38:19 +00006517 /// Returns the "target" range of a canonical integral type, i.e.
6518 /// the range of values expressible in the type.
6519 ///
6520 /// This matches forValueOfCanonicalType except that enums have the
6521 /// full range of their type, not the range of their enumerators.
6522 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6523 assert(T->isCanonicalUnqualified());
6524
6525 if (const VectorType *VT = dyn_cast<VectorType>(T))
6526 T = VT->getElementType().getTypePtr();
6527 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6528 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006529 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6530 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006531 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006532 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006533
6534 const BuiltinType *BT = cast<BuiltinType>(T);
6535 assert(BT->isInteger());
6536
6537 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6538 }
6539
6540 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006541 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006542 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006543 L.NonNegative && R.NonNegative);
6544 }
6545
John McCall817d4af2010-11-10 23:38:19 +00006546 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006547 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006548 return IntRange(std::min(L.Width, R.Width),
6549 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006550 }
6551};
6552
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006553IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006554 if (value.isSigned() && value.isNegative())
6555 return IntRange(value.getMinSignedBits(), false);
6556
6557 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006558 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006559
6560 // isNonNegative() just checks the sign bit without considering
6561 // signedness.
6562 return IntRange(value.getActiveBits(), true);
6563}
6564
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006565IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6566 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006567 if (result.isInt())
6568 return GetValueRange(C, result.getInt(), MaxWidth);
6569
6570 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006571 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6572 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6573 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6574 R = IntRange::join(R, El);
6575 }
John McCall70aa5392010-01-06 05:24:50 +00006576 return R;
6577 }
6578
6579 if (result.isComplexInt()) {
6580 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6581 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6582 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006583 }
6584
6585 // This can happen with lossless casts to intptr_t of "based" lvalues.
6586 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006587 // FIXME: The only reason we need to pass the type in here is to get
6588 // the sign right on this one case. It would be nice if APValue
6589 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006590 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006591 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006592}
John McCall70aa5392010-01-06 05:24:50 +00006593
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006594QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006595 QualType Ty = E->getType();
6596 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6597 Ty = AtomicRHS->getValueType();
6598 return Ty;
6599}
6600
John McCall70aa5392010-01-06 05:24:50 +00006601/// Pseudo-evaluate the given integer expression, estimating the
6602/// range of values it might take.
6603///
6604/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006605IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006606 E = E->IgnoreParens();
6607
6608 // Try a full evaluation first.
6609 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006610 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006611 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006612
6613 // I think we only want to look through implicit casts here; if the
6614 // user has an explicit widening cast, we should treat the value as
6615 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006616 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006617 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006618 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6619
Eli Friedmane6d33952013-07-08 20:20:06 +00006620 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006621
George Burgess IVdf1ed002016-01-13 01:52:39 +00006622 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6623 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00006624
John McCall70aa5392010-01-06 05:24:50 +00006625 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006626 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006627 return OutputTypeRange;
6628
6629 IntRange SubRange
6630 = GetExprRange(C, CE->getSubExpr(),
6631 std::min(MaxWidth, OutputTypeRange.Width));
6632
6633 // Bail out if the subexpr's range is as wide as the cast type.
6634 if (SubRange.Width >= OutputTypeRange.Width)
6635 return OutputTypeRange;
6636
6637 // Otherwise, we take the smaller width, and we're non-negative if
6638 // either the output type or the subexpr is.
6639 return IntRange(SubRange.Width,
6640 SubRange.NonNegative || OutputTypeRange.NonNegative);
6641 }
6642
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006643 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006644 // If we can fold the condition, just take that operand.
6645 bool CondResult;
6646 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6647 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6648 : CO->getFalseExpr(),
6649 MaxWidth);
6650
6651 // Otherwise, conservatively merge.
6652 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6653 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6654 return IntRange::join(L, R);
6655 }
6656
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006657 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006658 switch (BO->getOpcode()) {
6659
6660 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006661 case BO_LAnd:
6662 case BO_LOr:
6663 case BO_LT:
6664 case BO_GT:
6665 case BO_LE:
6666 case BO_GE:
6667 case BO_EQ:
6668 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006669 return IntRange::forBoolType();
6670
John McCallc3688382011-07-13 06:35:24 +00006671 // The type of the assignments is the type of the LHS, so the RHS
6672 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006673 case BO_MulAssign:
6674 case BO_DivAssign:
6675 case BO_RemAssign:
6676 case BO_AddAssign:
6677 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006678 case BO_XorAssign:
6679 case BO_OrAssign:
6680 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006681 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006682
John McCallc3688382011-07-13 06:35:24 +00006683 // Simple assignments just pass through the RHS, which will have
6684 // been coerced to the LHS type.
6685 case BO_Assign:
6686 // TODO: bitfields?
6687 return GetExprRange(C, BO->getRHS(), MaxWidth);
6688
John McCall70aa5392010-01-06 05:24:50 +00006689 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006690 case BO_PtrMemD:
6691 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006692 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006693
John McCall2ce81ad2010-01-06 22:07:33 +00006694 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006695 case BO_And:
6696 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006697 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6698 GetExprRange(C, BO->getRHS(), MaxWidth));
6699
John McCall70aa5392010-01-06 05:24:50 +00006700 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006701 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006702 // ...except that we want to treat '1 << (blah)' as logically
6703 // positive. It's an important idiom.
6704 if (IntegerLiteral *I
6705 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6706 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006707 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006708 return IntRange(R.Width, /*NonNegative*/ true);
6709 }
6710 }
6711 // fallthrough
6712
John McCalle3027922010-08-25 11:45:40 +00006713 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006714 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006715
John McCall2ce81ad2010-01-06 22:07:33 +00006716 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006717 case BO_Shr:
6718 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006719 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6720
6721 // If the shift amount is a positive constant, drop the width by
6722 // that much.
6723 llvm::APSInt shift;
6724 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6725 shift.isNonNegative()) {
6726 unsigned zext = shift.getZExtValue();
6727 if (zext >= L.Width)
6728 L.Width = (L.NonNegative ? 0 : 1);
6729 else
6730 L.Width -= zext;
6731 }
6732
6733 return L;
6734 }
6735
6736 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006737 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006738 return GetExprRange(C, BO->getRHS(), MaxWidth);
6739
John McCall2ce81ad2010-01-06 22:07:33 +00006740 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006741 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006742 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006743 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006744 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006745
John McCall51431812011-07-14 22:39:48 +00006746 // The width of a division result is mostly determined by the size
6747 // of the LHS.
6748 case BO_Div: {
6749 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006750 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006751 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6752
6753 // If the divisor is constant, use that.
6754 llvm::APSInt divisor;
6755 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6756 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6757 if (log2 >= L.Width)
6758 L.Width = (L.NonNegative ? 0 : 1);
6759 else
6760 L.Width = std::min(L.Width - log2, MaxWidth);
6761 return L;
6762 }
6763
6764 // Otherwise, just use the LHS's width.
6765 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6766 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6767 }
6768
6769 // The result of a remainder can't be larger than the result of
6770 // either side.
6771 case BO_Rem: {
6772 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006773 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006774 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6775 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6776
6777 IntRange meet = IntRange::meet(L, R);
6778 meet.Width = std::min(meet.Width, MaxWidth);
6779 return meet;
6780 }
6781
6782 // The default behavior is okay for these.
6783 case BO_Mul:
6784 case BO_Add:
6785 case BO_Xor:
6786 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006787 break;
6788 }
6789
John McCall51431812011-07-14 22:39:48 +00006790 // The default case is to treat the operation as if it were closed
6791 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006792 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6793 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6794 return IntRange::join(L, R);
6795 }
6796
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006797 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006798 switch (UO->getOpcode()) {
6799 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006800 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006801 return IntRange::forBoolType();
6802
6803 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006804 case UO_Deref:
6805 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006806 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006807
6808 default:
6809 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6810 }
6811 }
6812
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006813 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006814 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6815
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006816 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006817 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006818 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006819
Eli Friedmane6d33952013-07-08 20:20:06 +00006820 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006821}
John McCall263a48b2010-01-04 23:31:57 +00006822
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006823IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006824 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006825}
6826
John McCall263a48b2010-01-04 23:31:57 +00006827/// Checks whether the given value, which currently has the given
6828/// source semantics, has the same value when coerced through the
6829/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006830bool IsSameFloatAfterCast(const llvm::APFloat &value,
6831 const llvm::fltSemantics &Src,
6832 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006833 llvm::APFloat truncated = value;
6834
6835 bool ignored;
6836 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6837 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6838
6839 return truncated.bitwiseIsEqual(value);
6840}
6841
6842/// Checks whether the given value, which currently has the given
6843/// source semantics, has the same value when coerced through the
6844/// target semantics.
6845///
6846/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006847bool IsSameFloatAfterCast(const APValue &value,
6848 const llvm::fltSemantics &Src,
6849 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006850 if (value.isFloat())
6851 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6852
6853 if (value.isVector()) {
6854 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6855 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6856 return false;
6857 return true;
6858 }
6859
6860 assert(value.isComplexFloat());
6861 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6862 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6863}
6864
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006865void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006866
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006867bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00006868 // Suppress cases where we are comparing against an enum constant.
6869 if (const DeclRefExpr *DR =
6870 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6871 if (isa<EnumConstantDecl>(DR->getDecl()))
6872 return false;
6873
6874 // Suppress cases where the '0' value is expanded from a macro.
6875 if (E->getLocStart().isMacroID())
6876 return false;
6877
John McCallcc7e5bf2010-05-06 08:58:33 +00006878 llvm::APSInt Value;
6879 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6880}
6881
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006882bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00006883 // Strip off implicit integral promotions.
6884 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006885 if (ICE->getCastKind() != CK_IntegralCast &&
6886 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006887 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006888 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006889 }
6890
6891 return E->getType()->isEnumeralType();
6892}
6893
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006894void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006895 // Disable warning in template instantiations.
6896 if (!S.ActiveTemplateInstantiations.empty())
6897 return;
6898
John McCalle3027922010-08-25 11:45:40 +00006899 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006900 if (E->isValueDependent())
6901 return;
6902
John McCalle3027922010-08-25 11:45:40 +00006903 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006904 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006905 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006906 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006907 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006908 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006909 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006910 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006911 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006912 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006913 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006914 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006915 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006916 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006917 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006918 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6919 }
6920}
6921
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006922void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
6923 Expr *Constant, Expr *Other,
6924 llvm::APSInt Value,
6925 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006926 // Disable warning in template instantiations.
6927 if (!S.ActiveTemplateInstantiations.empty())
6928 return;
6929
Richard Trieu0f097742014-04-04 04:13:47 +00006930 // TODO: Investigate using GetExprRange() to get tighter bounds
6931 // on the bit ranges.
6932 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006933 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006934 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006935 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6936 unsigned OtherWidth = OtherRange.Width;
6937
6938 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6939
Richard Trieu560910c2012-11-14 22:50:24 +00006940 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006941 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006942 return;
6943
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006944 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006945 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006946
Richard Trieu0f097742014-04-04 04:13:47 +00006947 // Used for diagnostic printout.
6948 enum {
6949 LiteralConstant = 0,
6950 CXXBoolLiteralTrue,
6951 CXXBoolLiteralFalse
6952 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006953
Richard Trieu0f097742014-04-04 04:13:47 +00006954 if (!OtherIsBooleanType) {
6955 QualType ConstantT = Constant->getType();
6956 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006957
Richard Trieu0f097742014-04-04 04:13:47 +00006958 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6959 return;
6960 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6961 "comparison with non-integer type");
6962
6963 bool ConstantSigned = ConstantT->isSignedIntegerType();
6964 bool CommonSigned = CommonT->isSignedIntegerType();
6965
6966 bool EqualityOnly = false;
6967
6968 if (CommonSigned) {
6969 // The common type is signed, therefore no signed to unsigned conversion.
6970 if (!OtherRange.NonNegative) {
6971 // Check that the constant is representable in type OtherT.
6972 if (ConstantSigned) {
6973 if (OtherWidth >= Value.getMinSignedBits())
6974 return;
6975 } else { // !ConstantSigned
6976 if (OtherWidth >= Value.getActiveBits() + 1)
6977 return;
6978 }
6979 } else { // !OtherSigned
6980 // Check that the constant is representable in type OtherT.
6981 // Negative values are out of range.
6982 if (ConstantSigned) {
6983 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6984 return;
6985 } else { // !ConstantSigned
6986 if (OtherWidth >= Value.getActiveBits())
6987 return;
6988 }
Richard Trieu560910c2012-11-14 22:50:24 +00006989 }
Richard Trieu0f097742014-04-04 04:13:47 +00006990 } else { // !CommonSigned
6991 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006992 if (OtherWidth >= Value.getActiveBits())
6993 return;
Craig Toppercf360162014-06-18 05:13:11 +00006994 } else { // OtherSigned
6995 assert(!ConstantSigned &&
6996 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006997 // Check to see if the constant is representable in OtherT.
6998 if (OtherWidth > Value.getActiveBits())
6999 return;
7000 // Check to see if the constant is equivalent to a negative value
7001 // cast to CommonT.
7002 if (S.Context.getIntWidth(ConstantT) ==
7003 S.Context.getIntWidth(CommonT) &&
7004 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7005 return;
7006 // The constant value rests between values that OtherT can represent
7007 // after conversion. Relational comparison still works, but equality
7008 // comparisons will be tautological.
7009 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007010 }
7011 }
Richard Trieu0f097742014-04-04 04:13:47 +00007012
7013 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7014
7015 if (op == BO_EQ || op == BO_NE) {
7016 IsTrue = op == BO_NE;
7017 } else if (EqualityOnly) {
7018 return;
7019 } else if (RhsConstant) {
7020 if (op == BO_GT || op == BO_GE)
7021 IsTrue = !PositiveConstant;
7022 else // op == BO_LT || op == BO_LE
7023 IsTrue = PositiveConstant;
7024 } else {
7025 if (op == BO_LT || op == BO_LE)
7026 IsTrue = !PositiveConstant;
7027 else // op == BO_GT || op == BO_GE
7028 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007029 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007030 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007031 // Other isKnownToHaveBooleanValue
7032 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7033 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7034 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7035
7036 static const struct LinkedConditions {
7037 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7038 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7039 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7040 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7041 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7042 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7043
7044 } TruthTable = {
7045 // Constant on LHS. | Constant on RHS. |
7046 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7047 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7048 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7049 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7050 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7051 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7052 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7053 };
7054
7055 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7056
7057 enum ConstantValue ConstVal = Zero;
7058 if (Value.isUnsigned() || Value.isNonNegative()) {
7059 if (Value == 0) {
7060 LiteralOrBoolConstant =
7061 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7062 ConstVal = Zero;
7063 } else if (Value == 1) {
7064 LiteralOrBoolConstant =
7065 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7066 ConstVal = One;
7067 } else {
7068 LiteralOrBoolConstant = LiteralConstant;
7069 ConstVal = GT_One;
7070 }
7071 } else {
7072 ConstVal = LT_Zero;
7073 }
7074
7075 CompareBoolWithConstantResult CmpRes;
7076
7077 switch (op) {
7078 case BO_LT:
7079 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7080 break;
7081 case BO_GT:
7082 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7083 break;
7084 case BO_LE:
7085 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7086 break;
7087 case BO_GE:
7088 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7089 break;
7090 case BO_EQ:
7091 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7092 break;
7093 case BO_NE:
7094 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7095 break;
7096 default:
7097 CmpRes = Unkwn;
7098 break;
7099 }
7100
7101 if (CmpRes == AFals) {
7102 IsTrue = false;
7103 } else if (CmpRes == ATrue) {
7104 IsTrue = true;
7105 } else {
7106 return;
7107 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007108 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007109
7110 // If this is a comparison to an enum constant, include that
7111 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007112 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007113 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7114 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7115
7116 SmallString<64> PrettySourceValue;
7117 llvm::raw_svector_ostream OS(PrettySourceValue);
7118 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007119 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007120 else
7121 OS << Value;
7122
Richard Trieu0f097742014-04-04 04:13:47 +00007123 S.DiagRuntimeBehavior(
7124 E->getOperatorLoc(), E,
7125 S.PDiag(diag::warn_out_of_range_compare)
7126 << OS.str() << LiteralOrBoolConstant
7127 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7128 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007129}
7130
John McCallcc7e5bf2010-05-06 08:58:33 +00007131/// Analyze the operands of the given comparison. Implements the
7132/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007133void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007134 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7135 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007136}
John McCall263a48b2010-01-04 23:31:57 +00007137
John McCallca01b222010-01-04 23:21:16 +00007138/// \brief Implements -Wsign-compare.
7139///
Richard Trieu82402a02011-09-15 21:56:47 +00007140/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007141void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007142 // The type the comparison is being performed in.
7143 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007144
7145 // Only analyze comparison operators where both sides have been converted to
7146 // the same type.
7147 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7148 return AnalyzeImpConvsInComparison(S, E);
7149
7150 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007151 if (E->isValueDependent())
7152 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007153
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007154 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7155 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007156
7157 bool IsComparisonConstant = false;
7158
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007159 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007160 // of 'true' or 'false'.
7161 if (T->isIntegralType(S.Context)) {
7162 llvm::APSInt RHSValue;
7163 bool IsRHSIntegralLiteral =
7164 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7165 llvm::APSInt LHSValue;
7166 bool IsLHSIntegralLiteral =
7167 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7168 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7169 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7170 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7171 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7172 else
7173 IsComparisonConstant =
7174 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007175 } else if (!T->hasUnsignedIntegerRepresentation())
7176 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007177
John McCallcc7e5bf2010-05-06 08:58:33 +00007178 // We don't do anything special if this isn't an unsigned integral
7179 // comparison: we're only interested in integral comparisons, and
7180 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007181 //
7182 // We also don't care about value-dependent expressions or expressions
7183 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007184 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007185 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007186
John McCallcc7e5bf2010-05-06 08:58:33 +00007187 // Check to see if one of the (unmodified) operands is of different
7188 // signedness.
7189 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007190 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7191 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007192 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007193 signedOperand = LHS;
7194 unsignedOperand = RHS;
7195 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7196 signedOperand = RHS;
7197 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007198 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007199 CheckTrivialUnsignedComparison(S, E);
7200 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007201 }
7202
John McCallcc7e5bf2010-05-06 08:58:33 +00007203 // Otherwise, calculate the effective range of the signed operand.
7204 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007205
John McCallcc7e5bf2010-05-06 08:58:33 +00007206 // Go ahead and analyze implicit conversions in the operands. Note
7207 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007208 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7209 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007210
John McCallcc7e5bf2010-05-06 08:58:33 +00007211 // If the signed range is non-negative, -Wsign-compare won't fire,
7212 // but we should still check for comparisons which are always true
7213 // or false.
7214 if (signedRange.NonNegative)
7215 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007216
7217 // For (in)equality comparisons, if the unsigned operand is a
7218 // constant which cannot collide with a overflowed signed operand,
7219 // then reinterpreting the signed operand as unsigned will not
7220 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007221 if (E->isEqualityOp()) {
7222 unsigned comparisonWidth = S.Context.getIntWidth(T);
7223 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007224
John McCallcc7e5bf2010-05-06 08:58:33 +00007225 // We should never be unable to prove that the unsigned operand is
7226 // non-negative.
7227 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7228
7229 if (unsignedRange.Width < comparisonWidth)
7230 return;
7231 }
7232
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007233 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7234 S.PDiag(diag::warn_mixed_sign_comparison)
7235 << LHS->getType() << RHS->getType()
7236 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007237}
7238
John McCall1f425642010-11-11 03:21:53 +00007239/// Analyzes an attempt to assign the given value to a bitfield.
7240///
7241/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007242bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7243 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007244 assert(Bitfield->isBitField());
7245 if (Bitfield->isInvalidDecl())
7246 return false;
7247
John McCalldeebbcf2010-11-11 05:33:51 +00007248 // White-list bool bitfields.
7249 if (Bitfield->getType()->isBooleanType())
7250 return false;
7251
Douglas Gregor789adec2011-02-04 13:09:01 +00007252 // Ignore value- or type-dependent expressions.
7253 if (Bitfield->getBitWidth()->isValueDependent() ||
7254 Bitfield->getBitWidth()->isTypeDependent() ||
7255 Init->isValueDependent() ||
7256 Init->isTypeDependent())
7257 return false;
7258
John McCall1f425642010-11-11 03:21:53 +00007259 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7260
Richard Smith5fab0c92011-12-28 19:48:30 +00007261 llvm::APSInt Value;
7262 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007263 return false;
7264
John McCall1f425642010-11-11 03:21:53 +00007265 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007266 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007267
7268 if (OriginalWidth <= FieldWidth)
7269 return false;
7270
Eli Friedmanc267a322012-01-26 23:11:39 +00007271 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007272 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007273 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007274
Eli Friedmanc267a322012-01-26 23:11:39 +00007275 // Check whether the stored value is equal to the original value.
7276 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007277 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007278 return false;
7279
Eli Friedmanc267a322012-01-26 23:11:39 +00007280 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007281 // therefore don't strictly fit into a signed bitfield of width 1.
7282 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007283 return false;
7284
John McCall1f425642010-11-11 03:21:53 +00007285 std::string PrettyValue = Value.toString(10);
7286 std::string PrettyTrunc = TruncatedValue.toString(10);
7287
7288 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7289 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7290 << Init->getSourceRange();
7291
7292 return true;
7293}
7294
John McCalld2a53122010-11-09 23:24:47 +00007295/// Analyze the given simple or compound assignment for warning-worthy
7296/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007297void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007298 // Just recurse on the LHS.
7299 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7300
7301 // We want to recurse on the RHS as normal unless we're assigning to
7302 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007303 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007304 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007305 E->getOperatorLoc())) {
7306 // Recurse, ignoring any implicit conversions on the RHS.
7307 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7308 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007309 }
7310 }
7311
7312 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7313}
7314
John McCall263a48b2010-01-04 23:31:57 +00007315/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007316void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7317 SourceLocation CContext, unsigned diag,
7318 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007319 if (pruneControlFlow) {
7320 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7321 S.PDiag(diag)
7322 << SourceType << T << E->getSourceRange()
7323 << SourceRange(CContext));
7324 return;
7325 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007326 S.Diag(E->getExprLoc(), diag)
7327 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7328}
7329
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007330/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007331void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7332 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007333 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007334}
7335
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007336/// Diagnose an implicit cast from a literal expression. Does not warn when the
7337/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00007338void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
7339 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007340 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00007341 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007342 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007343 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7344 T->hasUnsignedIntegerRepresentation());
7345 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00007346 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007347 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00007348 return;
7349
Eli Friedman07185912013-08-29 23:44:43 +00007350 // FIXME: Force the precision of the source value down so we don't print
7351 // digits which are usually useless (we don't really care here if we
7352 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7353 // would automatically print the shortest representation, but it's a bit
7354 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007355 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007356 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7357 precision = (precision * 59 + 195) / 196;
7358 Value.toString(PrettySourceValue, precision);
7359
David Blaikie9b88cc02012-05-15 17:18:27 +00007360 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00007361 if (T->isSpecificBuiltinType(BuiltinType::Bool))
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007362 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007363 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007364 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007365
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007366 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00007367 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
7368 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00007369}
7370
John McCall18a2c2c2010-11-09 22:22:12 +00007371std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7372 if (!Range.Width) return "0";
7373
7374 llvm::APSInt ValueInRange = Value;
7375 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007376 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007377 return ValueInRange.toString(10);
7378}
7379
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007380bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007381 if (!isa<ImplicitCastExpr>(Ex))
7382 return false;
7383
7384 Expr *InnerE = Ex->IgnoreParenImpCasts();
7385 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7386 const Type *Source =
7387 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7388 if (Target->isDependentType())
7389 return false;
7390
7391 const BuiltinType *FloatCandidateBT =
7392 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7393 const Type *BoolCandidateType = ToBool ? Target : Source;
7394
7395 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7396 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7397}
7398
7399void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7400 SourceLocation CC) {
7401 unsigned NumArgs = TheCall->getNumArgs();
7402 for (unsigned i = 0; i < NumArgs; ++i) {
7403 Expr *CurrA = TheCall->getArg(i);
7404 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7405 continue;
7406
7407 bool IsSwapped = ((i > 0) &&
7408 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7409 IsSwapped |= ((i < (NumArgs - 1)) &&
7410 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7411 if (IsSwapped) {
7412 // Warn on this floating-point to bool conversion.
7413 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7414 CurrA->getType(), CC,
7415 diag::warn_impcast_floating_point_to_bool);
7416 }
7417 }
7418}
7419
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007420void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007421 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7422 E->getExprLoc()))
7423 return;
7424
Richard Trieu09d6b802016-01-08 23:35:06 +00007425 // Don't warn on functions which have return type nullptr_t.
7426 if (isa<CallExpr>(E))
7427 return;
7428
Richard Trieu5b993502014-10-15 03:42:06 +00007429 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7430 const Expr::NullPointerConstantKind NullKind =
7431 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7432 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7433 return;
7434
7435 // Return if target type is a safe conversion.
7436 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7437 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7438 return;
7439
7440 SourceLocation Loc = E->getSourceRange().getBegin();
7441
Richard Trieu0a5e1662016-02-13 00:58:53 +00007442 // Venture through the macro stacks to get to the source of macro arguments.
7443 // The new location is a better location than the complete location that was
7444 // passed in.
7445 while (S.SourceMgr.isMacroArgExpansion(Loc))
7446 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
7447
7448 while (S.SourceMgr.isMacroArgExpansion(CC))
7449 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
7450
Richard Trieu5b993502014-10-15 03:42:06 +00007451 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00007452 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
7453 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7454 Loc, S.SourceMgr, S.getLangOpts());
7455 if (MacroName == "NULL")
7456 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00007457 }
7458
7459 // Only warn if the null and context location are in the same macro expansion.
7460 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7461 return;
7462
7463 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7464 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7465 << FixItHint::CreateReplacement(Loc,
7466 S.getFixItZeroLiteralForType(T, Loc));
7467}
7468
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007469void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7470 ObjCArrayLiteral *ArrayLiteral);
7471void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7472 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00007473
7474/// Check a single element within a collection literal against the
7475/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007476void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7477 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007478 // Skip a bitcast to 'id' or qualified 'id'.
7479 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7480 if (ICE->getCastKind() == CK_BitCast &&
7481 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7482 Element = ICE->getSubExpr();
7483 }
7484
7485 QualType ElementType = Element->getType();
7486 ExprResult ElementResult(Element);
7487 if (ElementType->getAs<ObjCObjectPointerType>() &&
7488 S.CheckSingleAssignmentConstraints(TargetElementType,
7489 ElementResult,
7490 false, false)
7491 != Sema::Compatible) {
7492 S.Diag(Element->getLocStart(),
7493 diag::warn_objc_collection_literal_element)
7494 << ElementType << ElementKind << TargetElementType
7495 << Element->getSourceRange();
7496 }
7497
7498 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7499 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7500 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7501 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7502}
7503
7504/// Check an Objective-C array literal being converted to the given
7505/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007506void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7507 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007508 if (!S.NSArrayDecl)
7509 return;
7510
7511 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7512 if (!TargetObjCPtr)
7513 return;
7514
7515 if (TargetObjCPtr->isUnspecialized() ||
7516 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7517 != S.NSArrayDecl->getCanonicalDecl())
7518 return;
7519
7520 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7521 if (TypeArgs.size() != 1)
7522 return;
7523
7524 QualType TargetElementType = TypeArgs[0];
7525 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7526 checkObjCCollectionLiteralElement(S, TargetElementType,
7527 ArrayLiteral->getElement(I),
7528 0);
7529 }
7530}
7531
7532/// Check an Objective-C dictionary literal being converted to the given
7533/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007534void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7535 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007536 if (!S.NSDictionaryDecl)
7537 return;
7538
7539 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7540 if (!TargetObjCPtr)
7541 return;
7542
7543 if (TargetObjCPtr->isUnspecialized() ||
7544 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7545 != S.NSDictionaryDecl->getCanonicalDecl())
7546 return;
7547
7548 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7549 if (TypeArgs.size() != 2)
7550 return;
7551
7552 QualType TargetKeyType = TypeArgs[0];
7553 QualType TargetObjectType = TypeArgs[1];
7554 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7555 auto Element = DictionaryLiteral->getKeyValueElement(I);
7556 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7557 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7558 }
7559}
7560
Richard Trieufc404c72016-02-05 23:02:38 +00007561// Helper function to filter out cases for constant width constant conversion.
7562// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007563bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7564 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00007565 // If initializing from a constant, and the constant starts with '0',
7566 // then it is a binary, octal, or hexadecimal. Allow these constants
7567 // to fill all the bits, even if there is a sign change.
7568 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7569 const char FirstLiteralCharacter =
7570 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7571 if (FirstLiteralCharacter == '0')
7572 return false;
7573 }
7574
7575 // If the CC location points to a '{', and the type is char, then assume
7576 // assume it is an array initialization.
7577 if (CC.isValid() && T->isCharType()) {
7578 const char FirstContextCharacter =
7579 S.getSourceManager().getCharacterData(CC)[0];
7580 if (FirstContextCharacter == '{')
7581 return false;
7582 }
7583
7584 return true;
7585}
7586
John McCallcc7e5bf2010-05-06 08:58:33 +00007587void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007588 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007589 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007590
John McCallcc7e5bf2010-05-06 08:58:33 +00007591 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7592 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7593 if (Source == Target) return;
7594 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007595
Chandler Carruthc22845a2011-07-26 05:40:03 +00007596 // If the conversion context location is invalid don't complain. We also
7597 // don't want to emit a warning if the issue occurs from the expansion of
7598 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7599 // delay this check as long as possible. Once we detect we are in that
7600 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007601 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007602 return;
7603
Richard Trieu021baa32011-09-23 20:10:00 +00007604 // Diagnose implicit casts to bool.
7605 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7606 if (isa<StringLiteral>(E))
7607 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007608 // and expressions, for instance, assert(0 && "error here"), are
7609 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007610 return DiagnoseImpCast(S, E, T, CC,
7611 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007612 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7613 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7614 // This covers the literal expressions that evaluate to Objective-C
7615 // objects.
7616 return DiagnoseImpCast(S, E, T, CC,
7617 diag::warn_impcast_objective_c_literal_to_bool);
7618 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007619 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7620 // Warn on pointer to bool conversion that is always true.
7621 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7622 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007623 }
Richard Trieu021baa32011-09-23 20:10:00 +00007624 }
John McCall263a48b2010-01-04 23:31:57 +00007625
Douglas Gregor5054cb02015-07-07 03:58:22 +00007626 // Check implicit casts from Objective-C collection literals to specialized
7627 // collection types, e.g., NSArray<NSString *> *.
7628 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7629 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7630 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7631 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7632
John McCall263a48b2010-01-04 23:31:57 +00007633 // Strip vector types.
7634 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007635 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007636 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007637 return;
John McCallacf0ee52010-10-08 02:01:28 +00007638 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007639 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007640
7641 // If the vector cast is cast between two vectors of the same size, it is
7642 // a bitcast, not a conversion.
7643 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7644 return;
John McCall263a48b2010-01-04 23:31:57 +00007645
7646 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7647 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7648 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007649 if (auto VecTy = dyn_cast<VectorType>(Target))
7650 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007651
7652 // Strip complex types.
7653 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007654 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007655 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007656 return;
7657
John McCallacf0ee52010-10-08 02:01:28 +00007658 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007659 }
John McCall263a48b2010-01-04 23:31:57 +00007660
7661 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7662 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7663 }
7664
7665 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7666 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7667
7668 // If the source is floating point...
7669 if (SourceBT && SourceBT->isFloatingPoint()) {
7670 // ...and the target is floating point...
7671 if (TargetBT && TargetBT->isFloatingPoint()) {
7672 // ...then warn if we're dropping FP rank.
7673
7674 // Builtin FP kinds are ordered by increasing FP rank.
7675 if (SourceBT->getKind() > TargetBT->getKind()) {
7676 // Don't warn about float constants that are precisely
7677 // representable in the target type.
7678 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007679 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007680 // Value might be a float, a float vector, or a float complex.
7681 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007682 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7683 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007684 return;
7685 }
7686
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007687 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007688 return;
7689
John McCallacf0ee52010-10-08 02:01:28 +00007690 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007691 }
7692 // ... or possibly if we're increasing rank, too
7693 else if (TargetBT->getKind() > SourceBT->getKind()) {
7694 if (S.SourceMgr.isInSystemMacro(CC))
7695 return;
7696
7697 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007698 }
7699 return;
7700 }
7701
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007702 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007703 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007704 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007705 return;
7706
Chandler Carruth22c7a792011-02-17 11:05:49 +00007707 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007708 // We also want to warn on, e.g., "int i = -1.234"
7709 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7710 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7711 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7712
Chandler Carruth016ef402011-04-10 08:36:24 +00007713 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7714 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007715 } else {
7716 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7717 }
7718 }
John McCall263a48b2010-01-04 23:31:57 +00007719
Richard Smith54894fd2015-12-30 01:06:52 +00007720 // Detect the case where a call result is converted from floating-point to
7721 // to bool, and the final argument to the call is converted from bool, to
7722 // discover this typo:
7723 //
7724 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
7725 //
7726 // FIXME: This is an incredibly special case; is there some more general
7727 // way to detect this class of misplaced-parentheses bug?
7728 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007729 // Check last argument of function call to see if it is an
7730 // implicit cast from a type matching the type the result
7731 // is being cast to.
7732 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00007733 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007734 Expr *LastA = CEx->getArg(NumArgs - 1);
7735 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00007736 if (isa<ImplicitCastExpr>(LastA) &&
7737 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007738 // Warn on this floating-point to bool conversion
7739 DiagnoseImpCast(S, E, T, CC,
7740 diag::warn_impcast_floating_point_to_bool);
7741 }
7742 }
7743 }
John McCall263a48b2010-01-04 23:31:57 +00007744 return;
7745 }
7746
Richard Trieu5b993502014-10-15 03:42:06 +00007747 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007748
David Blaikie9366d2b2012-06-19 21:19:06 +00007749 if (!Source->isIntegerType() || !Target->isIntegerType())
7750 return;
7751
David Blaikie7555b6a2012-05-15 16:56:36 +00007752 // TODO: remove this early return once the false positives for constant->bool
7753 // in templates, macros, etc, are reduced or removed.
7754 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7755 return;
7756
John McCallcc7e5bf2010-05-06 08:58:33 +00007757 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007758 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007759
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007760 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007761 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007762 // TODO: this should happen for bitfield stores, too.
7763 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00007764 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007765 if (S.SourceMgr.isInSystemMacro(CC))
7766 return;
7767
John McCall18a2c2c2010-11-09 22:22:12 +00007768 std::string PrettySourceValue = Value.toString(10);
7769 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007770
Ted Kremenek33ba9952011-10-22 02:37:33 +00007771 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7772 S.PDiag(diag::warn_impcast_integer_precision_constant)
7773 << PrettySourceValue << PrettyTargetValue
7774 << E->getType() << T << E->getSourceRange()
7775 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007776 return;
7777 }
7778
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007779 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7780 if (S.SourceMgr.isInSystemMacro(CC))
7781 return;
7782
David Blaikie9455da02012-04-12 22:40:54 +00007783 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007784 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7785 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007786 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007787 }
7788
Richard Trieudcb55572016-01-29 23:51:16 +00007789 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
7790 SourceRange.NonNegative && Source->isSignedIntegerType()) {
7791 // Warn when doing a signed to signed conversion, warn if the positive
7792 // source value is exactly the width of the target type, which will
7793 // cause a negative value to be stored.
7794
7795 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00007796 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
7797 !S.SourceMgr.isInSystemMacro(CC)) {
7798 if (isSameWidthConstantConversion(S, E, T, CC)) {
7799 std::string PrettySourceValue = Value.toString(10);
7800 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00007801
Richard Trieufc404c72016-02-05 23:02:38 +00007802 S.DiagRuntimeBehavior(
7803 E->getExprLoc(), E,
7804 S.PDiag(diag::warn_impcast_integer_precision_constant)
7805 << PrettySourceValue << PrettyTargetValue << E->getType() << T
7806 << E->getSourceRange() << clang::SourceRange(CC));
7807 return;
Richard Trieudcb55572016-01-29 23:51:16 +00007808 }
7809 }
Richard Trieufc404c72016-02-05 23:02:38 +00007810
Richard Trieudcb55572016-01-29 23:51:16 +00007811 // Fall through for non-constants to give a sign conversion warning.
7812 }
7813
John McCallcc7e5bf2010-05-06 08:58:33 +00007814 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7815 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7816 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007817 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007818 return;
7819
John McCallcc7e5bf2010-05-06 08:58:33 +00007820 unsigned DiagID = diag::warn_impcast_integer_sign;
7821
7822 // Traditionally, gcc has warned about this under -Wsign-compare.
7823 // We also want to warn about it in -Wconversion.
7824 // So if -Wconversion is off, use a completely identical diagnostic
7825 // in the sign-compare group.
7826 // The conditional-checking code will
7827 if (ICContext) {
7828 DiagID = diag::warn_impcast_integer_sign_conditional;
7829 *ICContext = true;
7830 }
7831
John McCallacf0ee52010-10-08 02:01:28 +00007832 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007833 }
7834
Douglas Gregora78f1932011-02-22 02:45:07 +00007835 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007836 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7837 // type, to give us better diagnostics.
7838 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007839 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007840 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7841 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7842 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7843 SourceType = S.Context.getTypeDeclType(Enum);
7844 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7845 }
7846 }
7847
Douglas Gregora78f1932011-02-22 02:45:07 +00007848 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7849 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007850 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7851 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007852 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007853 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007854 return;
7855
Douglas Gregor364f7db2011-03-12 00:14:31 +00007856 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007857 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007858 }
John McCall263a48b2010-01-04 23:31:57 +00007859}
7860
David Blaikie18e9ac72012-05-15 21:57:38 +00007861void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7862 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007863
7864void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007865 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007866 E = E->IgnoreParenImpCasts();
7867
7868 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007869 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007870
John McCallacf0ee52010-10-08 02:01:28 +00007871 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007872 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007873 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007874}
7875
David Blaikie18e9ac72012-05-15 21:57:38 +00007876void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7877 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007878 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007879
7880 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007881 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7882 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007883
7884 // If -Wconversion would have warned about either of the candidates
7885 // for a signedness conversion to the context type...
7886 if (!Suspicious) return;
7887
7888 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007889 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007890 return;
7891
John McCallcc7e5bf2010-05-06 08:58:33 +00007892 // ...then check whether it would have warned about either of the
7893 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007894 if (E->getType() == T) return;
7895
7896 Suspicious = false;
7897 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7898 E->getType(), CC, &Suspicious);
7899 if (!Suspicious)
7900 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007901 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007902}
7903
Richard Trieu65724892014-11-15 06:37:39 +00007904/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7905/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007906void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00007907 if (S.getLangOpts().Bool)
7908 return;
7909 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7910}
7911
John McCallcc7e5bf2010-05-06 08:58:33 +00007912/// AnalyzeImplicitConversions - Find and report any interesting
7913/// implicit conversions in the given expression. There are a couple
7914/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007915void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007916 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007917 Expr *E = OrigE->IgnoreParenImpCasts();
7918
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007919 if (E->isTypeDependent() || E->isValueDependent())
7920 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007921
John McCallcc7e5bf2010-05-06 08:58:33 +00007922 // For conditional operators, we analyze the arguments as if they
7923 // were being fed directly into the output.
7924 if (isa<ConditionalOperator>(E)) {
7925 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007926 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007927 return;
7928 }
7929
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007930 // Check implicit argument conversions for function calls.
7931 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7932 CheckImplicitArgumentConversions(S, Call, CC);
7933
John McCallcc7e5bf2010-05-06 08:58:33 +00007934 // Go ahead and check any implicit conversions we might have skipped.
7935 // The non-canonical typecheck is just an optimization;
7936 // CheckImplicitConversion will filter out dead implicit conversions.
7937 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007938 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007939
7940 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00007941
7942 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
7943 // The bound subexpressions in a PseudoObjectExpr are not reachable
7944 // as transitive children.
7945 // FIXME: Use a more uniform representation for this.
7946 for (auto *SE : POE->semantics())
7947 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
7948 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007949 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00007950
John McCallcc7e5bf2010-05-06 08:58:33 +00007951 // Skip past explicit casts.
7952 if (isa<ExplicitCastExpr>(E)) {
7953 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007954 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007955 }
7956
John McCalld2a53122010-11-09 23:24:47 +00007957 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7958 // Do a somewhat different check with comparison operators.
7959 if (BO->isComparisonOp())
7960 return AnalyzeComparison(S, BO);
7961
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007962 // And with simple assignments.
7963 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007964 return AnalyzeAssignment(S, BO);
7965 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007966
7967 // These break the otherwise-useful invariant below. Fortunately,
7968 // we don't really need to recurse into them, because any internal
7969 // expressions should have been analyzed already when they were
7970 // built into statements.
7971 if (isa<StmtExpr>(E)) return;
7972
7973 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007974 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007975
7976 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007977 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007978 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007979 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007980 for (Stmt *SubStmt : E->children()) {
7981 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007982 if (!ChildExpr)
7983 continue;
7984
Richard Trieu955231d2014-01-25 01:10:35 +00007985 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007986 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007987 // Ignore checking string literals that are in logical and operators.
7988 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007989 continue;
7990 AnalyzeImplicitConversions(S, ChildExpr, CC);
7991 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007992
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007993 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007994 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7995 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007996 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007997
7998 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7999 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008000 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008001 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008002
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008003 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8004 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008005 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008006}
8007
8008} // end anonymous namespace
8009
Richard Trieuc1888e02014-06-28 23:25:37 +00008010// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8011// Returns true when emitting a warning about taking the address of a reference.
8012static bool CheckForReference(Sema &SemaRef, const Expr *E,
8013 PartialDiagnostic PD) {
8014 E = E->IgnoreParenImpCasts();
8015
8016 const FunctionDecl *FD = nullptr;
8017
8018 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8019 if (!DRE->getDecl()->getType()->isReferenceType())
8020 return false;
8021 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8022 if (!M->getMemberDecl()->getType()->isReferenceType())
8023 return false;
8024 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008025 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008026 return false;
8027 FD = Call->getDirectCallee();
8028 } else {
8029 return false;
8030 }
8031
8032 SemaRef.Diag(E->getExprLoc(), PD);
8033
8034 // If possible, point to location of function.
8035 if (FD) {
8036 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8037 }
8038
8039 return true;
8040}
8041
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008042// Returns true if the SourceLocation is expanded from any macro body.
8043// Returns false if the SourceLocation is invalid, is from not in a macro
8044// expansion, or is from expanded from a top-level macro argument.
8045static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8046 if (Loc.isInvalid())
8047 return false;
8048
8049 while (Loc.isMacroID()) {
8050 if (SM.isMacroBodyExpansion(Loc))
8051 return true;
8052 Loc = SM.getImmediateMacroCallerLoc(Loc);
8053 }
8054
8055 return false;
8056}
8057
Richard Trieu3bb8b562014-02-26 02:36:06 +00008058/// \brief Diagnose pointers that are always non-null.
8059/// \param E the expression containing the pointer
8060/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8061/// compared to a null pointer
8062/// \param IsEqual True when the comparison is equal to a null pointer
8063/// \param Range Extra SourceRange to highlight in the diagnostic
8064void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8065 Expr::NullPointerConstantKind NullKind,
8066 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008067 if (!E)
8068 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008069
8070 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008071 if (E->getExprLoc().isMacroID()) {
8072 const SourceManager &SM = getSourceManager();
8073 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8074 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008075 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008076 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008077 E = E->IgnoreImpCasts();
8078
8079 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8080
Richard Trieuf7432752014-06-06 21:39:26 +00008081 if (isa<CXXThisExpr>(E)) {
8082 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8083 : diag::warn_this_bool_conversion;
8084 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8085 return;
8086 }
8087
Richard Trieu3bb8b562014-02-26 02:36:06 +00008088 bool IsAddressOf = false;
8089
8090 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8091 if (UO->getOpcode() != UO_AddrOf)
8092 return;
8093 IsAddressOf = true;
8094 E = UO->getSubExpr();
8095 }
8096
Richard Trieuc1888e02014-06-28 23:25:37 +00008097 if (IsAddressOf) {
8098 unsigned DiagID = IsCompare
8099 ? diag::warn_address_of_reference_null_compare
8100 : diag::warn_address_of_reference_bool_conversion;
8101 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8102 << IsEqual;
8103 if (CheckForReference(*this, E, PD)) {
8104 return;
8105 }
8106 }
8107
George Burgess IV850269a2015-12-08 22:02:00 +00008108 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
8109 std::string Str;
8110 llvm::raw_string_ostream S(Str);
8111 E->printPretty(S, nullptr, getPrintingPolicy());
8112 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8113 : diag::warn_cast_nonnull_to_bool;
8114 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8115 << E->getSourceRange() << Range << IsEqual;
8116 };
8117
8118 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8119 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8120 if (auto *Callee = Call->getDirectCallee()) {
8121 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
8122 ComplainAboutNonnullParamOrCall(false);
8123 return;
8124 }
8125 }
8126 }
8127
Richard Trieu3bb8b562014-02-26 02:36:06 +00008128 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008129 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008130 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8131 D = R->getDecl();
8132 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8133 D = M->getMemberDecl();
8134 }
8135
8136 // Weak Decls can be null.
8137 if (!D || D->isWeak())
8138 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008139
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008140 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008141 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8142 if (getCurFunction() &&
8143 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8144 if (PV->hasAttr<NonNullAttr>()) {
8145 ComplainAboutNonnullParamOrCall(true);
8146 return;
8147 }
8148
8149 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8150 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
8151 assert(ParamIter != FD->param_end());
8152 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8153
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008154 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8155 if (!NonNull->args_size()) {
George Burgess IV850269a2015-12-08 22:02:00 +00008156 ComplainAboutNonnullParamOrCall(true);
8157 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008158 }
George Burgess IV850269a2015-12-08 22:02:00 +00008159
8160 for (unsigned ArgNo : NonNull->args()) {
8161 if (ArgNo == ParamNo) {
8162 ComplainAboutNonnullParamOrCall(true);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008163 return;
8164 }
George Burgess IV850269a2015-12-08 22:02:00 +00008165 }
8166 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008167 }
8168 }
George Burgess IV850269a2015-12-08 22:02:00 +00008169 }
8170
Richard Trieu3bb8b562014-02-26 02:36:06 +00008171 QualType T = D->getType();
8172 const bool IsArray = T->isArrayType();
8173 const bool IsFunction = T->isFunctionType();
8174
Richard Trieuc1888e02014-06-28 23:25:37 +00008175 // Address of function is used to silence the function warning.
8176 if (IsAddressOf && IsFunction) {
8177 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008178 }
8179
8180 // Found nothing.
8181 if (!IsAddressOf && !IsFunction && !IsArray)
8182 return;
8183
8184 // Pretty print the expression for the diagnostic.
8185 std::string Str;
8186 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008187 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008188
8189 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8190 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008191 enum {
8192 AddressOf,
8193 FunctionPointer,
8194 ArrayPointer
8195 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008196 if (IsAddressOf)
8197 DiagType = AddressOf;
8198 else if (IsFunction)
8199 DiagType = FunctionPointer;
8200 else if (IsArray)
8201 DiagType = ArrayPointer;
8202 else
8203 llvm_unreachable("Could not determine diagnostic.");
8204 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8205 << Range << IsEqual;
8206
8207 if (!IsFunction)
8208 return;
8209
8210 // Suggest '&' to silence the function warning.
8211 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8212 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8213
8214 // Check to see if '()' fixit should be emitted.
8215 QualType ReturnType;
8216 UnresolvedSet<4> NonTemplateOverloads;
8217 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8218 if (ReturnType.isNull())
8219 return;
8220
8221 if (IsCompare) {
8222 // There are two cases here. If there is null constant, the only suggest
8223 // for a pointer return type. If the null is 0, then suggest if the return
8224 // type is a pointer or an integer type.
8225 if (!ReturnType->isPointerType()) {
8226 if (NullKind == Expr::NPCK_ZeroExpression ||
8227 NullKind == Expr::NPCK_ZeroLiteral) {
8228 if (!ReturnType->isIntegerType())
8229 return;
8230 } else {
8231 return;
8232 }
8233 }
8234 } else { // !IsCompare
8235 // For function to bool, only suggest if the function pointer has bool
8236 // return type.
8237 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8238 return;
8239 }
8240 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008241 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008242}
8243
John McCallcc7e5bf2010-05-06 08:58:33 +00008244/// Diagnoses "dangerous" implicit conversions within the given
8245/// expression (which is a full expression). Implements -Wconversion
8246/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008247///
8248/// \param CC the "context" location of the implicit conversion, i.e.
8249/// the most location of the syntactic entity requiring the implicit
8250/// conversion
8251void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008252 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008253 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008254 return;
8255
8256 // Don't diagnose for value- or type-dependent expressions.
8257 if (E->isTypeDependent() || E->isValueDependent())
8258 return;
8259
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008260 // Check for array bounds violations in cases where the check isn't triggered
8261 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8262 // ArraySubscriptExpr is on the RHS of a variable initialization.
8263 CheckArrayAccess(E);
8264
John McCallacf0ee52010-10-08 02:01:28 +00008265 // This is not the right CC for (e.g.) a variable initialization.
8266 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008267}
8268
Richard Trieu65724892014-11-15 06:37:39 +00008269/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8270/// Input argument E is a logical expression.
8271void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8272 ::CheckBoolLikeConversion(*this, E, CC);
8273}
8274
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008275/// Diagnose when expression is an integer constant expression and its evaluation
8276/// results in integer overflow
8277void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008278 // Use a work list to deal with nested struct initializers.
8279 SmallVector<Expr *, 2> Exprs(1, E);
8280
8281 do {
8282 Expr *E = Exprs.pop_back_val();
8283
8284 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8285 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8286 continue;
8287 }
8288
8289 if (auto InitList = dyn_cast<InitListExpr>(E))
8290 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8291 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008292}
8293
Richard Smithc406cb72013-01-17 01:17:56 +00008294namespace {
8295/// \brief Visitor for expressions which looks for unsequenced operations on the
8296/// same object.
8297class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008298 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8299
Richard Smithc406cb72013-01-17 01:17:56 +00008300 /// \brief A tree of sequenced regions within an expression. Two regions are
8301 /// unsequenced if one is an ancestor or a descendent of the other. When we
8302 /// finish processing an expression with sequencing, such as a comma
8303 /// expression, we fold its tree nodes into its parent, since they are
8304 /// unsequenced with respect to nodes we will visit later.
8305 class SequenceTree {
8306 struct Value {
8307 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8308 unsigned Parent : 31;
8309 bool Merged : 1;
8310 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008311 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008312
8313 public:
8314 /// \brief A region within an expression which may be sequenced with respect
8315 /// to some other region.
8316 class Seq {
8317 explicit Seq(unsigned N) : Index(N) {}
8318 unsigned Index;
8319 friend class SequenceTree;
8320 public:
8321 Seq() : Index(0) {}
8322 };
8323
8324 SequenceTree() { Values.push_back(Value(0)); }
8325 Seq root() const { return Seq(0); }
8326
8327 /// \brief Create a new sequence of operations, which is an unsequenced
8328 /// subset of \p Parent. This sequence of operations is sequenced with
8329 /// respect to other children of \p Parent.
8330 Seq allocate(Seq Parent) {
8331 Values.push_back(Value(Parent.Index));
8332 return Seq(Values.size() - 1);
8333 }
8334
8335 /// \brief Merge a sequence of operations into its parent.
8336 void merge(Seq S) {
8337 Values[S.Index].Merged = true;
8338 }
8339
8340 /// \brief Determine whether two operations are unsequenced. This operation
8341 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8342 /// should have been merged into its parent as appropriate.
8343 bool isUnsequenced(Seq Cur, Seq Old) {
8344 unsigned C = representative(Cur.Index);
8345 unsigned Target = representative(Old.Index);
8346 while (C >= Target) {
8347 if (C == Target)
8348 return true;
8349 C = Values[C].Parent;
8350 }
8351 return false;
8352 }
8353
8354 private:
8355 /// \brief Pick a representative for a sequence.
8356 unsigned representative(unsigned K) {
8357 if (Values[K].Merged)
8358 // Perform path compression as we go.
8359 return Values[K].Parent = representative(Values[K].Parent);
8360 return K;
8361 }
8362 };
8363
8364 /// An object for which we can track unsequenced uses.
8365 typedef NamedDecl *Object;
8366
8367 /// Different flavors of object usage which we track. We only track the
8368 /// least-sequenced usage of each kind.
8369 enum UsageKind {
8370 /// A read of an object. Multiple unsequenced reads are OK.
8371 UK_Use,
8372 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008373 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008374 UK_ModAsValue,
8375 /// A modification of an object which is not sequenced before the value
8376 /// computation of the expression, such as n++.
8377 UK_ModAsSideEffect,
8378
8379 UK_Count = UK_ModAsSideEffect + 1
8380 };
8381
8382 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008383 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008384 Expr *Use;
8385 SequenceTree::Seq Seq;
8386 };
8387
8388 struct UsageInfo {
8389 UsageInfo() : Diagnosed(false) {}
8390 Usage Uses[UK_Count];
8391 /// Have we issued a diagnostic for this variable already?
8392 bool Diagnosed;
8393 };
8394 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8395
8396 Sema &SemaRef;
8397 /// Sequenced regions within the expression.
8398 SequenceTree Tree;
8399 /// Declaration modifications and references which we have seen.
8400 UsageInfoMap UsageMap;
8401 /// The region we are currently within.
8402 SequenceTree::Seq Region;
8403 /// Filled in with declarations which were modified as a side-effect
8404 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008405 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008406 /// Expressions to check later. We defer checking these to reduce
8407 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008408 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008409
8410 /// RAII object wrapping the visitation of a sequenced subexpression of an
8411 /// expression. At the end of this process, the side-effects of the evaluation
8412 /// become sequenced with respect to the value computation of the result, so
8413 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8414 /// UK_ModAsValue.
8415 struct SequencedSubexpression {
8416 SequencedSubexpression(SequenceChecker &Self)
8417 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8418 Self.ModAsSideEffect = &ModAsSideEffect;
8419 }
8420 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00008421 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8422 MI != ME; ++MI) {
8423 UsageInfo &U = Self.UsageMap[MI->first];
8424 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8425 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8426 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00008427 }
8428 Self.ModAsSideEffect = OldModAsSideEffect;
8429 }
8430
8431 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008432 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8433 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008434 };
8435
Richard Smith40238f02013-06-20 22:21:56 +00008436 /// RAII object wrapping the visitation of a subexpression which we might
8437 /// choose to evaluate as a constant. If any subexpression is evaluated and
8438 /// found to be non-constant, this allows us to suppress the evaluation of
8439 /// the outer expression.
8440 class EvaluationTracker {
8441 public:
8442 EvaluationTracker(SequenceChecker &Self)
8443 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8444 Self.EvalTracker = this;
8445 }
8446 ~EvaluationTracker() {
8447 Self.EvalTracker = Prev;
8448 if (Prev)
8449 Prev->EvalOK &= EvalOK;
8450 }
8451
8452 bool evaluate(const Expr *E, bool &Result) {
8453 if (!EvalOK || E->isValueDependent())
8454 return false;
8455 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8456 return EvalOK;
8457 }
8458
8459 private:
8460 SequenceChecker &Self;
8461 EvaluationTracker *Prev;
8462 bool EvalOK;
8463 } *EvalTracker;
8464
Richard Smithc406cb72013-01-17 01:17:56 +00008465 /// \brief Find the object which is produced by the specified expression,
8466 /// if any.
8467 Object getObject(Expr *E, bool Mod) const {
8468 E = E->IgnoreParenCasts();
8469 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8470 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8471 return getObject(UO->getSubExpr(), Mod);
8472 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8473 if (BO->getOpcode() == BO_Comma)
8474 return getObject(BO->getRHS(), Mod);
8475 if (Mod && BO->isAssignmentOp())
8476 return getObject(BO->getLHS(), Mod);
8477 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8478 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8479 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8480 return ME->getMemberDecl();
8481 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8482 // FIXME: If this is a reference, map through to its value.
8483 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008484 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008485 }
8486
8487 /// \brief Note that an object was modified or used by an expression.
8488 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8489 Usage &U = UI.Uses[UK];
8490 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8491 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8492 ModAsSideEffect->push_back(std::make_pair(O, U));
8493 U.Use = Ref;
8494 U.Seq = Region;
8495 }
8496 }
8497 /// \brief Check whether a modification or use conflicts with a prior usage.
8498 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8499 bool IsModMod) {
8500 if (UI.Diagnosed)
8501 return;
8502
8503 const Usage &U = UI.Uses[OtherKind];
8504 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8505 return;
8506
8507 Expr *Mod = U.Use;
8508 Expr *ModOrUse = Ref;
8509 if (OtherKind == UK_Use)
8510 std::swap(Mod, ModOrUse);
8511
8512 SemaRef.Diag(Mod->getExprLoc(),
8513 IsModMod ? diag::warn_unsequenced_mod_mod
8514 : diag::warn_unsequenced_mod_use)
8515 << O << SourceRange(ModOrUse->getExprLoc());
8516 UI.Diagnosed = true;
8517 }
8518
8519 void notePreUse(Object O, Expr *Use) {
8520 UsageInfo &U = UsageMap[O];
8521 // Uses conflict with other modifications.
8522 checkUsage(O, U, Use, UK_ModAsValue, false);
8523 }
8524 void notePostUse(Object O, Expr *Use) {
8525 UsageInfo &U = UsageMap[O];
8526 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8527 addUsage(U, O, Use, UK_Use);
8528 }
8529
8530 void notePreMod(Object O, Expr *Mod) {
8531 UsageInfo &U = UsageMap[O];
8532 // Modifications conflict with other modifications and with uses.
8533 checkUsage(O, U, Mod, UK_ModAsValue, true);
8534 checkUsage(O, U, Mod, UK_Use, false);
8535 }
8536 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8537 UsageInfo &U = UsageMap[O];
8538 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8539 addUsage(U, O, Use, UK);
8540 }
8541
8542public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008543 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008544 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8545 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008546 Visit(E);
8547 }
8548
8549 void VisitStmt(Stmt *S) {
8550 // Skip all statements which aren't expressions for now.
8551 }
8552
8553 void VisitExpr(Expr *E) {
8554 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008555 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008556 }
8557
8558 void VisitCastExpr(CastExpr *E) {
8559 Object O = Object();
8560 if (E->getCastKind() == CK_LValueToRValue)
8561 O = getObject(E->getSubExpr(), false);
8562
8563 if (O)
8564 notePreUse(O, E);
8565 VisitExpr(E);
8566 if (O)
8567 notePostUse(O, E);
8568 }
8569
8570 void VisitBinComma(BinaryOperator *BO) {
8571 // C++11 [expr.comma]p1:
8572 // Every value computation and side effect associated with the left
8573 // expression is sequenced before every value computation and side
8574 // effect associated with the right expression.
8575 SequenceTree::Seq LHS = Tree.allocate(Region);
8576 SequenceTree::Seq RHS = Tree.allocate(Region);
8577 SequenceTree::Seq OldRegion = Region;
8578
8579 {
8580 SequencedSubexpression SeqLHS(*this);
8581 Region = LHS;
8582 Visit(BO->getLHS());
8583 }
8584
8585 Region = RHS;
8586 Visit(BO->getRHS());
8587
8588 Region = OldRegion;
8589
8590 // Forget that LHS and RHS are sequenced. They are both unsequenced
8591 // with respect to other stuff.
8592 Tree.merge(LHS);
8593 Tree.merge(RHS);
8594 }
8595
8596 void VisitBinAssign(BinaryOperator *BO) {
8597 // The modification is sequenced after the value computation of the LHS
8598 // and RHS, so check it before inspecting the operands and update the
8599 // map afterwards.
8600 Object O = getObject(BO->getLHS(), true);
8601 if (!O)
8602 return VisitExpr(BO);
8603
8604 notePreMod(O, BO);
8605
8606 // C++11 [expr.ass]p7:
8607 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8608 // only once.
8609 //
8610 // Therefore, for a compound assignment operator, O is considered used
8611 // everywhere except within the evaluation of E1 itself.
8612 if (isa<CompoundAssignOperator>(BO))
8613 notePreUse(O, BO);
8614
8615 Visit(BO->getLHS());
8616
8617 if (isa<CompoundAssignOperator>(BO))
8618 notePostUse(O, BO);
8619
8620 Visit(BO->getRHS());
8621
Richard Smith83e37bee2013-06-26 23:16:51 +00008622 // C++11 [expr.ass]p1:
8623 // the assignment is sequenced [...] before the value computation of the
8624 // assignment expression.
8625 // C11 6.5.16/3 has no such rule.
8626 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8627 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008628 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008629
Richard Smithc406cb72013-01-17 01:17:56 +00008630 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8631 VisitBinAssign(CAO);
8632 }
8633
8634 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8635 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8636 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8637 Object O = getObject(UO->getSubExpr(), true);
8638 if (!O)
8639 return VisitExpr(UO);
8640
8641 notePreMod(O, UO);
8642 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008643 // C++11 [expr.pre.incr]p1:
8644 // the expression ++x is equivalent to x+=1
8645 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8646 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008647 }
8648
8649 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8650 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8651 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8652 Object O = getObject(UO->getSubExpr(), true);
8653 if (!O)
8654 return VisitExpr(UO);
8655
8656 notePreMod(O, UO);
8657 Visit(UO->getSubExpr());
8658 notePostMod(O, UO, UK_ModAsSideEffect);
8659 }
8660
8661 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8662 void VisitBinLOr(BinaryOperator *BO) {
8663 // The side-effects of the LHS of an '&&' are sequenced before the
8664 // value computation of the RHS, and hence before the value computation
8665 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8666 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008667 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008668 {
8669 SequencedSubexpression Sequenced(*this);
8670 Visit(BO->getLHS());
8671 }
8672
8673 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008674 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008675 if (!Result)
8676 Visit(BO->getRHS());
8677 } else {
8678 // Check for unsequenced operations in the RHS, treating it as an
8679 // entirely separate evaluation.
8680 //
8681 // FIXME: If there are operations in the RHS which are unsequenced
8682 // with respect to operations outside the RHS, and those operations
8683 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008684 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008685 }
Richard Smithc406cb72013-01-17 01:17:56 +00008686 }
8687 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008688 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008689 {
8690 SequencedSubexpression Sequenced(*this);
8691 Visit(BO->getLHS());
8692 }
8693
8694 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008695 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008696 if (Result)
8697 Visit(BO->getRHS());
8698 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008699 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008700 }
Richard Smithc406cb72013-01-17 01:17:56 +00008701 }
8702
8703 // Only visit the condition, unless we can be sure which subexpression will
8704 // be chosen.
8705 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008706 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008707 {
8708 SequencedSubexpression Sequenced(*this);
8709 Visit(CO->getCond());
8710 }
Richard Smithc406cb72013-01-17 01:17:56 +00008711
8712 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008713 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008714 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008715 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008716 WorkList.push_back(CO->getTrueExpr());
8717 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008718 }
Richard Smithc406cb72013-01-17 01:17:56 +00008719 }
8720
Richard Smithe3dbfe02013-06-30 10:40:20 +00008721 void VisitCallExpr(CallExpr *CE) {
8722 // C++11 [intro.execution]p15:
8723 // When calling a function [...], every value computation and side effect
8724 // associated with any argument expression, or with the postfix expression
8725 // designating the called function, is sequenced before execution of every
8726 // expression or statement in the body of the function [and thus before
8727 // the value computation of its result].
8728 SequencedSubexpression Sequenced(*this);
8729 Base::VisitCallExpr(CE);
8730
8731 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8732 }
8733
Richard Smithc406cb72013-01-17 01:17:56 +00008734 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008735 // This is a call, so all subexpressions are sequenced before the result.
8736 SequencedSubexpression Sequenced(*this);
8737
Richard Smithc406cb72013-01-17 01:17:56 +00008738 if (!CCE->isListInitialization())
8739 return VisitExpr(CCE);
8740
8741 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008742 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008743 SequenceTree::Seq Parent = Region;
8744 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8745 E = CCE->arg_end();
8746 I != E; ++I) {
8747 Region = Tree.allocate(Parent);
8748 Elts.push_back(Region);
8749 Visit(*I);
8750 }
8751
8752 // Forget that the initializers are sequenced.
8753 Region = Parent;
8754 for (unsigned I = 0; I < Elts.size(); ++I)
8755 Tree.merge(Elts[I]);
8756 }
8757
8758 void VisitInitListExpr(InitListExpr *ILE) {
8759 if (!SemaRef.getLangOpts().CPlusPlus11)
8760 return VisitExpr(ILE);
8761
8762 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008763 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008764 SequenceTree::Seq Parent = Region;
8765 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8766 Expr *E = ILE->getInit(I);
8767 if (!E) continue;
8768 Region = Tree.allocate(Parent);
8769 Elts.push_back(Region);
8770 Visit(E);
8771 }
8772
8773 // Forget that the initializers are sequenced.
8774 Region = Parent;
8775 for (unsigned I = 0; I < Elts.size(); ++I)
8776 Tree.merge(Elts[I]);
8777 }
8778};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008779} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00008780
8781void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008782 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008783 WorkList.push_back(E);
8784 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008785 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008786 SequenceChecker(*this, Item, WorkList);
8787 }
Richard Smithc406cb72013-01-17 01:17:56 +00008788}
8789
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008790void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8791 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008792 CheckImplicitConversions(E, CheckLoc);
8793 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008794 if (!IsConstexpr && !E->isValueDependent())
8795 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008796}
8797
John McCall1f425642010-11-11 03:21:53 +00008798void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8799 FieldDecl *BitField,
8800 Expr *Init) {
8801 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8802}
8803
David Majnemer61a5bbf2015-04-07 22:08:51 +00008804static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8805 SourceLocation Loc) {
8806 if (!PType->isVariablyModifiedType())
8807 return;
8808 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8809 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8810 return;
8811 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008812 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8813 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8814 return;
8815 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008816 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8817 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8818 return;
8819 }
8820
8821 const ArrayType *AT = S.Context.getAsArrayType(PType);
8822 if (!AT)
8823 return;
8824
8825 if (AT->getSizeModifier() != ArrayType::Star) {
8826 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8827 return;
8828 }
8829
8830 S.Diag(Loc, diag::err_array_star_in_function_definition);
8831}
8832
Mike Stump0c2ec772010-01-21 03:59:47 +00008833/// CheckParmsForFunctionDef - Check that the parameters of the given
8834/// function are appropriate for the definition of a function. This
8835/// takes care of any checks that cannot be performed on the
8836/// declaration itself, e.g., that the types of each of the function
8837/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008838bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8839 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008840 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008841 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008842 for (; P != PEnd; ++P) {
8843 ParmVarDecl *Param = *P;
8844
Mike Stump0c2ec772010-01-21 03:59:47 +00008845 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8846 // function declarator that is part of a function definition of
8847 // that function shall not have incomplete type.
8848 //
8849 // This is also C++ [dcl.fct]p6.
8850 if (!Param->isInvalidDecl() &&
8851 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008852 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008853 Param->setInvalidDecl();
8854 HasInvalidParm = true;
8855 }
8856
8857 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8858 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008859 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008860 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008861 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008862 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008863 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008864
8865 // C99 6.7.5.3p12:
8866 // If the function declarator is not part of a definition of that
8867 // function, parameters may have incomplete type and may use the [*]
8868 // notation in their sequences of declarator specifiers to specify
8869 // variable length array types.
8870 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008871 // FIXME: This diagnostic should point the '[*]' if source-location
8872 // information is added for it.
8873 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008874
8875 // MSVC destroys objects passed by value in the callee. Therefore a
8876 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008877 // object's destructor. However, we don't perform any direct access check
8878 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008879 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8880 .getCXXABI()
8881 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008882 if (!Param->isInvalidDecl()) {
8883 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8884 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8885 if (!ClassDecl->isInvalidDecl() &&
8886 !ClassDecl->hasIrrelevantDestructor() &&
8887 !ClassDecl->isDependentContext()) {
8888 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8889 MarkFunctionReferenced(Param->getLocation(), Destructor);
8890 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8891 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008892 }
8893 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008894 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008895
8896 // Parameters with the pass_object_size attribute only need to be marked
8897 // constant at function definitions. Because we lack information about
8898 // whether we're on a declaration or definition when we're instantiating the
8899 // attribute, we need to check for constness here.
8900 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
8901 if (!Param->getType().isConstQualified())
8902 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
8903 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00008904 }
8905
8906 return HasInvalidParm;
8907}
John McCall2b5c1b22010-08-12 21:44:57 +00008908
8909/// CheckCastAlign - Implements -Wcast-align, which warns when a
8910/// pointer cast increases the alignment requirements.
8911void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8912 // This is actually a lot of work to potentially be doing on every
8913 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008914 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008915 return;
8916
8917 // Ignore dependent types.
8918 if (T->isDependentType() || Op->getType()->isDependentType())
8919 return;
8920
8921 // Require that the destination be a pointer type.
8922 const PointerType *DestPtr = T->getAs<PointerType>();
8923 if (!DestPtr) return;
8924
8925 // If the destination has alignment 1, we're done.
8926 QualType DestPointee = DestPtr->getPointeeType();
8927 if (DestPointee->isIncompleteType()) return;
8928 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8929 if (DestAlign.isOne()) return;
8930
8931 // Require that the source be a pointer type.
8932 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8933 if (!SrcPtr) return;
8934 QualType SrcPointee = SrcPtr->getPointeeType();
8935
8936 // Whitelist casts from cv void*. We already implicitly
8937 // whitelisted casts to cv void*, since they have alignment 1.
8938 // Also whitelist casts involving incomplete types, which implicitly
8939 // includes 'void'.
8940 if (SrcPointee->isIncompleteType()) return;
8941
8942 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8943 if (SrcAlign >= DestAlign) return;
8944
8945 Diag(TRange.getBegin(), diag::warn_cast_align)
8946 << Op->getType() << T
8947 << static_cast<unsigned>(SrcAlign.getQuantity())
8948 << static_cast<unsigned>(DestAlign.getQuantity())
8949 << TRange << Op->getSourceRange();
8950}
8951
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008952static const Type* getElementType(const Expr *BaseExpr) {
8953 const Type* EltType = BaseExpr->getType().getTypePtr();
8954 if (EltType->isAnyPointerType())
8955 return EltType->getPointeeType().getTypePtr();
8956 else if (EltType->isArrayType())
8957 return EltType->getBaseElementTypeUnsafe();
8958 return EltType;
8959}
8960
Chandler Carruth28389f02011-08-05 09:10:50 +00008961/// \brief Check whether this array fits the idiom of a size-one tail padded
8962/// array member of a struct.
8963///
8964/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8965/// commonly used to emulate flexible arrays in C89 code.
8966static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8967 const NamedDecl *ND) {
8968 if (Size != 1 || !ND) return false;
8969
8970 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8971 if (!FD) return false;
8972
8973 // Don't consider sizes resulting from macro expansions or template argument
8974 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008975
8976 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008977 while (TInfo) {
8978 TypeLoc TL = TInfo->getTypeLoc();
8979 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008980 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8981 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008982 TInfo = TDL->getTypeSourceInfo();
8983 continue;
8984 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008985 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8986 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008987 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8988 return false;
8989 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008990 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008991 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008992
8993 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008994 if (!RD) return false;
8995 if (RD->isUnion()) return false;
8996 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8997 if (!CRD->isStandardLayout()) return false;
8998 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008999
Benjamin Kramer8c543672011-08-06 03:04:42 +00009000 // See if this is the last field decl in the record.
9001 const Decl *D = FD;
9002 while ((D = D->getNextDeclInContext()))
9003 if (isa<FieldDecl>(D))
9004 return false;
9005 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009006}
9007
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009008void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009009 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009010 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009011 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009012 if (IndexExpr->isValueDependent())
9013 return;
9014
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00009015 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009016 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009017 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009018 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009019 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009020 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009021
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009022 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009023 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009024 return;
Richard Smith13f67182011-12-16 19:31:14 +00009025 if (IndexNegated)
9026 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009027
Craig Topperc3ec1492014-05-26 06:22:03 +00009028 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009029 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9030 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009031 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009032 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009033
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009034 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009035 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009036 if (!size.isStrictlyPositive())
9037 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009038
9039 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00009040 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009041 // Make sure we're comparing apples to apples when comparing index to size
9042 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9043 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009044 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009045 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009046 if (ptrarith_typesize != array_typesize) {
9047 // There's a cast to a different size type involved
9048 uint64_t ratio = array_typesize / ptrarith_typesize;
9049 // TODO: Be smarter about handling cases where array_typesize is not a
9050 // multiple of ptrarith_typesize
9051 if (ptrarith_typesize * ratio == array_typesize)
9052 size *= llvm::APInt(size.getBitWidth(), ratio);
9053 }
9054 }
9055
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009056 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009057 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009058 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009059 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009060
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009061 // For array subscripting the index must be less than size, but for pointer
9062 // arithmetic also allow the index (offset) to be equal to size since
9063 // computing the next address after the end of the array is legal and
9064 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009065 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009066 return;
9067
9068 // Also don't warn for arrays of size 1 which are members of some
9069 // structure. These are often used to approximate flexible arrays in C89
9070 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009071 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009072 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009073
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009074 // Suppress the warning if the subscript expression (as identified by the
9075 // ']' location) and the index expression are both from macro expansions
9076 // within a system header.
9077 if (ASE) {
9078 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9079 ASE->getRBracketLoc());
9080 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9081 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9082 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009083 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009084 return;
9085 }
9086 }
9087
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009088 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009089 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009090 DiagID = diag::warn_array_index_exceeds_bounds;
9091
9092 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9093 PDiag(DiagID) << index.toString(10, true)
9094 << size.toString(10, true)
9095 << (unsigned)size.getLimitedValue(~0U)
9096 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009097 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009098 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009099 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009100 DiagID = diag::warn_ptr_arith_precedes_bounds;
9101 if (index.isNegative()) index = -index;
9102 }
9103
9104 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9105 PDiag(DiagID) << index.toString(10, true)
9106 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009107 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009108
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009109 if (!ND) {
9110 // Try harder to find a NamedDecl to point at in the note.
9111 while (const ArraySubscriptExpr *ASE =
9112 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9113 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9114 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9115 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9116 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9117 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9118 }
9119
Chandler Carruth1af88f12011-02-17 21:10:52 +00009120 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009121 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9122 PDiag(diag::note_array_index_out_of_bounds)
9123 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009124}
9125
Ted Kremenekdf26df72011-03-01 18:41:00 +00009126void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009127 int AllowOnePastEnd = 0;
9128 while (expr) {
9129 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009130 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009131 case Stmt::ArraySubscriptExprClass: {
9132 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009133 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009134 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009135 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009136 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009137 case Stmt::OMPArraySectionExprClass: {
9138 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9139 if (ASE->getLowerBound())
9140 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9141 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9142 return;
9143 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009144 case Stmt::UnaryOperatorClass: {
9145 // Only unwrap the * and & unary operators
9146 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9147 expr = UO->getSubExpr();
9148 switch (UO->getOpcode()) {
9149 case UO_AddrOf:
9150 AllowOnePastEnd++;
9151 break;
9152 case UO_Deref:
9153 AllowOnePastEnd--;
9154 break;
9155 default:
9156 return;
9157 }
9158 break;
9159 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009160 case Stmt::ConditionalOperatorClass: {
9161 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9162 if (const Expr *lhs = cond->getLHS())
9163 CheckArrayAccess(lhs);
9164 if (const Expr *rhs = cond->getRHS())
9165 CheckArrayAccess(rhs);
9166 return;
9167 }
9168 default:
9169 return;
9170 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009171 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009172}
John McCall31168b02011-06-15 23:02:42 +00009173
9174//===--- CHECK: Objective-C retain cycles ----------------------------------//
9175
9176namespace {
9177 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009178 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009179 VarDecl *Variable;
9180 SourceRange Range;
9181 SourceLocation Loc;
9182 bool Indirect;
9183
9184 void setLocsFrom(Expr *e) {
9185 Loc = e->getExprLoc();
9186 Range = e->getSourceRange();
9187 }
9188 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009189} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009190
9191/// Consider whether capturing the given variable can possibly lead to
9192/// a retain cycle.
9193static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009194 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009195 // lifetime. In MRR, it's captured strongly if the variable is
9196 // __block and has an appropriate type.
9197 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9198 return false;
9199
9200 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009201 if (ref)
9202 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009203 return true;
9204}
9205
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009206static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009207 while (true) {
9208 e = e->IgnoreParens();
9209 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9210 switch (cast->getCastKind()) {
9211 case CK_BitCast:
9212 case CK_LValueBitCast:
9213 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009214 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009215 e = cast->getSubExpr();
9216 continue;
9217
John McCall31168b02011-06-15 23:02:42 +00009218 default:
9219 return false;
9220 }
9221 }
9222
9223 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9224 ObjCIvarDecl *ivar = ref->getDecl();
9225 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9226 return false;
9227
9228 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009229 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009230 return false;
9231
9232 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9233 owner.Indirect = true;
9234 return true;
9235 }
9236
9237 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9238 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9239 if (!var) return false;
9240 return considerVariable(var, ref, owner);
9241 }
9242
John McCall31168b02011-06-15 23:02:42 +00009243 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9244 if (member->isArrow()) return false;
9245
9246 // Don't count this as an indirect ownership.
9247 e = member->getBase();
9248 continue;
9249 }
9250
John McCallfe96e0b2011-11-06 09:01:30 +00009251 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9252 // Only pay attention to pseudo-objects on property references.
9253 ObjCPropertyRefExpr *pre
9254 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9255 ->IgnoreParens());
9256 if (!pre) return false;
9257 if (pre->isImplicitProperty()) return false;
9258 ObjCPropertyDecl *property = pre->getExplicitProperty();
9259 if (!property->isRetaining() &&
9260 !(property->getPropertyIvarDecl() &&
9261 property->getPropertyIvarDecl()->getType()
9262 .getObjCLifetime() == Qualifiers::OCL_Strong))
9263 return false;
9264
9265 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009266 if (pre->isSuperReceiver()) {
9267 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9268 if (!owner.Variable)
9269 return false;
9270 owner.Loc = pre->getLocation();
9271 owner.Range = pre->getSourceRange();
9272 return true;
9273 }
John McCallfe96e0b2011-11-06 09:01:30 +00009274 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9275 ->getSourceExpr());
9276 continue;
9277 }
9278
John McCall31168b02011-06-15 23:02:42 +00009279 // Array ivars?
9280
9281 return false;
9282 }
9283}
9284
9285namespace {
9286 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9287 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9288 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009289 Context(Context), Variable(variable), Capturer(nullptr),
9290 VarWillBeReased(false) {}
9291 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009292 VarDecl *Variable;
9293 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009294 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009295
9296 void VisitDeclRefExpr(DeclRefExpr *ref) {
9297 if (ref->getDecl() == Variable && !Capturer)
9298 Capturer = ref;
9299 }
9300
John McCall31168b02011-06-15 23:02:42 +00009301 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9302 if (Capturer) return;
9303 Visit(ref->getBase());
9304 if (Capturer && ref->isFreeIvar())
9305 Capturer = ref;
9306 }
9307
9308 void VisitBlockExpr(BlockExpr *block) {
9309 // Look inside nested blocks
9310 if (block->getBlockDecl()->capturesVariable(Variable))
9311 Visit(block->getBlockDecl()->getBody());
9312 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009313
9314 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9315 if (Capturer) return;
9316 if (OVE->getSourceExpr())
9317 Visit(OVE->getSourceExpr());
9318 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009319 void VisitBinaryOperator(BinaryOperator *BinOp) {
9320 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9321 return;
9322 Expr *LHS = BinOp->getLHS();
9323 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9324 if (DRE->getDecl() != Variable)
9325 return;
9326 if (Expr *RHS = BinOp->getRHS()) {
9327 RHS = RHS->IgnoreParenCasts();
9328 llvm::APSInt Value;
9329 VarWillBeReased =
9330 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9331 }
9332 }
9333 }
John McCall31168b02011-06-15 23:02:42 +00009334 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009335} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009336
9337/// Check whether the given argument is a block which captures a
9338/// variable.
9339static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9340 assert(owner.Variable && owner.Loc.isValid());
9341
9342 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009343
9344 // Look through [^{...} copy] and Block_copy(^{...}).
9345 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9346 Selector Cmd = ME->getSelector();
9347 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9348 e = ME->getInstanceReceiver();
9349 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009350 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009351 e = e->IgnoreParenCasts();
9352 }
9353 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9354 if (CE->getNumArgs() == 1) {
9355 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009356 if (Fn) {
9357 const IdentifierInfo *FnI = Fn->getIdentifier();
9358 if (FnI && FnI->isStr("_Block_copy")) {
9359 e = CE->getArg(0)->IgnoreParenCasts();
9360 }
9361 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009362 }
9363 }
9364
John McCall31168b02011-06-15 23:02:42 +00009365 BlockExpr *block = dyn_cast<BlockExpr>(e);
9366 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009367 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009368
9369 FindCaptureVisitor visitor(S.Context, owner.Variable);
9370 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009371 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009372}
9373
9374static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9375 RetainCycleOwner &owner) {
9376 assert(capturer);
9377 assert(owner.Variable && owner.Loc.isValid());
9378
9379 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9380 << owner.Variable << capturer->getSourceRange();
9381 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9382 << owner.Indirect << owner.Range;
9383}
9384
9385/// Check for a keyword selector that starts with the word 'add' or
9386/// 'set'.
9387static bool isSetterLikeSelector(Selector sel) {
9388 if (sel.isUnarySelector()) return false;
9389
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009390 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009391 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009392 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009393 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009394 else if (str.startswith("add")) {
9395 // Specially whitelist 'addOperationWithBlock:'.
9396 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9397 return false;
9398 str = str.substr(3);
9399 }
John McCall31168b02011-06-15 23:02:42 +00009400 else
9401 return false;
9402
9403 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009404 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009405}
9406
Benjamin Kramer3a743452015-03-09 15:03:32 +00009407static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9408 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009409 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9410 Message->getReceiverInterface(),
9411 NSAPI::ClassId_NSMutableArray);
9412 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009413 return None;
9414 }
9415
9416 Selector Sel = Message->getSelector();
9417
9418 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9419 S.NSAPIObj->getNSArrayMethodKind(Sel);
9420 if (!MKOpt) {
9421 return None;
9422 }
9423
9424 NSAPI::NSArrayMethodKind MK = *MKOpt;
9425
9426 switch (MK) {
9427 case NSAPI::NSMutableArr_addObject:
9428 case NSAPI::NSMutableArr_insertObjectAtIndex:
9429 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9430 return 0;
9431 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9432 return 1;
9433
9434 default:
9435 return None;
9436 }
9437
9438 return None;
9439}
9440
9441static
9442Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9443 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009444 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9445 Message->getReceiverInterface(),
9446 NSAPI::ClassId_NSMutableDictionary);
9447 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009448 return None;
9449 }
9450
9451 Selector Sel = Message->getSelector();
9452
9453 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9454 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9455 if (!MKOpt) {
9456 return None;
9457 }
9458
9459 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9460
9461 switch (MK) {
9462 case NSAPI::NSMutableDict_setObjectForKey:
9463 case NSAPI::NSMutableDict_setValueForKey:
9464 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9465 return 0;
9466
9467 default:
9468 return None;
9469 }
9470
9471 return None;
9472}
9473
9474static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009475 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9476 Message->getReceiverInterface(),
9477 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009478
Alex Denisov5dfac812015-08-06 04:51:14 +00009479 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9480 Message->getReceiverInterface(),
9481 NSAPI::ClassId_NSMutableOrderedSet);
9482 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009483 return None;
9484 }
9485
9486 Selector Sel = Message->getSelector();
9487
9488 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9489 if (!MKOpt) {
9490 return None;
9491 }
9492
9493 NSAPI::NSSetMethodKind MK = *MKOpt;
9494
9495 switch (MK) {
9496 case NSAPI::NSMutableSet_addObject:
9497 case NSAPI::NSOrderedSet_setObjectAtIndex:
9498 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9499 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9500 return 0;
9501 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9502 return 1;
9503 }
9504
9505 return None;
9506}
9507
9508void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9509 if (!Message->isInstanceMessage()) {
9510 return;
9511 }
9512
9513 Optional<int> ArgOpt;
9514
9515 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9516 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9517 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9518 return;
9519 }
9520
9521 int ArgIndex = *ArgOpt;
9522
Alex Denisove1d882c2015-03-04 17:55:52 +00009523 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9524 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9525 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9526 }
9527
Alex Denisov5dfac812015-08-06 04:51:14 +00009528 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009529 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009530 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009531 Diag(Message->getSourceRange().getBegin(),
9532 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009533 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009534 }
9535 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009536 } else {
9537 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9538
9539 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9540 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9541 }
9542
9543 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9544 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9545 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9546 ValueDecl *Decl = ReceiverRE->getDecl();
9547 Diag(Message->getSourceRange().getBegin(),
9548 diag::warn_objc_circular_container)
9549 << Decl->getName() << Decl->getName();
9550 if (!ArgRE->isObjCSelfExpr()) {
9551 Diag(Decl->getLocation(),
9552 diag::note_objc_circular_container_declared_here)
9553 << Decl->getName();
9554 }
9555 }
9556 }
9557 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9558 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9559 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9560 ObjCIvarDecl *Decl = IvarRE->getDecl();
9561 Diag(Message->getSourceRange().getBegin(),
9562 diag::warn_objc_circular_container)
9563 << Decl->getName() << Decl->getName();
9564 Diag(Decl->getLocation(),
9565 diag::note_objc_circular_container_declared_here)
9566 << Decl->getName();
9567 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009568 }
9569 }
9570 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009571}
9572
John McCall31168b02011-06-15 23:02:42 +00009573/// Check a message send to see if it's likely to cause a retain cycle.
9574void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9575 // Only check instance methods whose selector looks like a setter.
9576 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9577 return;
9578
9579 // Try to find a variable that the receiver is strongly owned by.
9580 RetainCycleOwner owner;
9581 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009582 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009583 return;
9584 } else {
9585 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9586 owner.Variable = getCurMethodDecl()->getSelfDecl();
9587 owner.Loc = msg->getSuperLoc();
9588 owner.Range = msg->getSuperLoc();
9589 }
9590
9591 // Check whether the receiver is captured by any of the arguments.
9592 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9593 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9594 return diagnoseRetainCycle(*this, capturer, owner);
9595}
9596
9597/// Check a property assign to see if it's likely to cause a retain cycle.
9598void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9599 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009600 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009601 return;
9602
9603 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9604 diagnoseRetainCycle(*this, capturer, owner);
9605}
9606
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009607void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9608 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009609 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009610 return;
9611
9612 // Because we don't have an expression for the variable, we have to set the
9613 // location explicitly here.
9614 Owner.Loc = Var->getLocation();
9615 Owner.Range = Var->getSourceRange();
9616
9617 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9618 diagnoseRetainCycle(*this, Capturer, Owner);
9619}
9620
Ted Kremenek9304da92012-12-21 08:04:28 +00009621static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9622 Expr *RHS, bool isProperty) {
9623 // Check if RHS is an Objective-C object literal, which also can get
9624 // immediately zapped in a weak reference. Note that we explicitly
9625 // allow ObjCStringLiterals, since those are designed to never really die.
9626 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009627
Ted Kremenek64873352012-12-21 22:46:35 +00009628 // This enum needs to match with the 'select' in
9629 // warn_objc_arc_literal_assign (off-by-1).
9630 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9631 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9632 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009633
9634 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009635 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009636 << (isProperty ? 0 : 1)
9637 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009638
9639 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009640}
9641
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009642static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9643 Qualifiers::ObjCLifetime LT,
9644 Expr *RHS, bool isProperty) {
9645 // Strip off any implicit cast added to get to the one ARC-specific.
9646 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9647 if (cast->getCastKind() == CK_ARCConsumeObject) {
9648 S.Diag(Loc, diag::warn_arc_retained_assign)
9649 << (LT == Qualifiers::OCL_ExplicitNone)
9650 << (isProperty ? 0 : 1)
9651 << RHS->getSourceRange();
9652 return true;
9653 }
9654 RHS = cast->getSubExpr();
9655 }
9656
9657 if (LT == Qualifiers::OCL_Weak &&
9658 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9659 return true;
9660
9661 return false;
9662}
9663
Ted Kremenekb36234d2012-12-21 08:04:20 +00009664bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9665 QualType LHS, Expr *RHS) {
9666 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9667
9668 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9669 return false;
9670
9671 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9672 return true;
9673
9674 return false;
9675}
9676
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009677void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9678 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009679 QualType LHSType;
9680 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009681 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009682 ObjCPropertyRefExpr *PRE
9683 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9684 if (PRE && !PRE->isImplicitProperty()) {
9685 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9686 if (PD)
9687 LHSType = PD->getType();
9688 }
9689
9690 if (LHSType.isNull())
9691 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009692
9693 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9694
9695 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009696 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009697 getCurFunction()->markSafeWeakUse(LHS);
9698 }
9699
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009700 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9701 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009702
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009703 // FIXME. Check for other life times.
9704 if (LT != Qualifiers::OCL_None)
9705 return;
9706
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009707 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009708 if (PRE->isImplicitProperty())
9709 return;
9710 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9711 if (!PD)
9712 return;
9713
Bill Wendling44426052012-12-20 19:22:21 +00009714 unsigned Attributes = PD->getPropertyAttributes();
9715 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009716 // when 'assign' attribute was not explicitly specified
9717 // by user, ignore it and rely on property type itself
9718 // for lifetime info.
9719 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9720 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9721 LHSType->isObjCRetainableType())
9722 return;
9723
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009724 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009725 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009726 Diag(Loc, diag::warn_arc_retained_property_assign)
9727 << RHS->getSourceRange();
9728 return;
9729 }
9730 RHS = cast->getSubExpr();
9731 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009732 }
Bill Wendling44426052012-12-20 19:22:21 +00009733 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009734 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9735 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009736 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009737 }
9738}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009739
9740//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9741
9742namespace {
9743bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9744 SourceLocation StmtLoc,
9745 const NullStmt *Body) {
9746 // Do not warn if the body is a macro that expands to nothing, e.g:
9747 //
9748 // #define CALL(x)
9749 // if (condition)
9750 // CALL(0);
9751 //
9752 if (Body->hasLeadingEmptyMacro())
9753 return false;
9754
9755 // Get line numbers of statement and body.
9756 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009757 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009758 &StmtLineInvalid);
9759 if (StmtLineInvalid)
9760 return false;
9761
9762 bool BodyLineInvalid;
9763 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9764 &BodyLineInvalid);
9765 if (BodyLineInvalid)
9766 return false;
9767
9768 // Warn if null statement and body are on the same line.
9769 if (StmtLine != BodyLine)
9770 return false;
9771
9772 return true;
9773}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009774} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009775
9776void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9777 const Stmt *Body,
9778 unsigned DiagID) {
9779 // Since this is a syntactic check, don't emit diagnostic for template
9780 // instantiations, this just adds noise.
9781 if (CurrentInstantiationScope)
9782 return;
9783
9784 // The body should be a null statement.
9785 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9786 if (!NBody)
9787 return;
9788
9789 // Do the usual checks.
9790 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9791 return;
9792
9793 Diag(NBody->getSemiLoc(), DiagID);
9794 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9795}
9796
9797void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9798 const Stmt *PossibleBody) {
9799 assert(!CurrentInstantiationScope); // Ensured by caller
9800
9801 SourceLocation StmtLoc;
9802 const Stmt *Body;
9803 unsigned DiagID;
9804 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9805 StmtLoc = FS->getRParenLoc();
9806 Body = FS->getBody();
9807 DiagID = diag::warn_empty_for_body;
9808 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9809 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9810 Body = WS->getBody();
9811 DiagID = diag::warn_empty_while_body;
9812 } else
9813 return; // Neither `for' nor `while'.
9814
9815 // The body should be a null statement.
9816 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9817 if (!NBody)
9818 return;
9819
9820 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009821 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009822 return;
9823
9824 // Do the usual checks.
9825 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9826 return;
9827
9828 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9829 // noise level low, emit diagnostics only if for/while is followed by a
9830 // CompoundStmt, e.g.:
9831 // for (int i = 0; i < n; i++);
9832 // {
9833 // a(i);
9834 // }
9835 // or if for/while is followed by a statement with more indentation
9836 // than for/while itself:
9837 // for (int i = 0; i < n; i++);
9838 // a(i);
9839 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9840 if (!ProbableTypo) {
9841 bool BodyColInvalid;
9842 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9843 PossibleBody->getLocStart(),
9844 &BodyColInvalid);
9845 if (BodyColInvalid)
9846 return;
9847
9848 bool StmtColInvalid;
9849 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9850 S->getLocStart(),
9851 &StmtColInvalid);
9852 if (StmtColInvalid)
9853 return;
9854
9855 if (BodyCol > StmtCol)
9856 ProbableTypo = true;
9857 }
9858
9859 if (ProbableTypo) {
9860 Diag(NBody->getSemiLoc(), DiagID);
9861 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9862 }
9863}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009864
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009865//===--- CHECK: Warn on self move with std::move. -------------------------===//
9866
9867/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9868void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9869 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009870 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9871 return;
9872
9873 if (!ActiveTemplateInstantiations.empty())
9874 return;
9875
9876 // Strip parens and casts away.
9877 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9878 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9879
9880 // Check for a call expression
9881 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9882 if (!CE || CE->getNumArgs() != 1)
9883 return;
9884
9885 // Check for a call to std::move
9886 const FunctionDecl *FD = CE->getDirectCallee();
9887 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9888 !FD->getIdentifier()->isStr("move"))
9889 return;
9890
9891 // Get argument from std::move
9892 RHSExpr = CE->getArg(0);
9893
9894 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9895 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9896
9897 // Two DeclRefExpr's, check that the decls are the same.
9898 if (LHSDeclRef && RHSDeclRef) {
9899 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9900 return;
9901 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9902 RHSDeclRef->getDecl()->getCanonicalDecl())
9903 return;
9904
9905 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9906 << LHSExpr->getSourceRange()
9907 << RHSExpr->getSourceRange();
9908 return;
9909 }
9910
9911 // Member variables require a different approach to check for self moves.
9912 // MemberExpr's are the same if every nested MemberExpr refers to the same
9913 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9914 // the base Expr's are CXXThisExpr's.
9915 const Expr *LHSBase = LHSExpr;
9916 const Expr *RHSBase = RHSExpr;
9917 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9918 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9919 if (!LHSME || !RHSME)
9920 return;
9921
9922 while (LHSME && RHSME) {
9923 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9924 RHSME->getMemberDecl()->getCanonicalDecl())
9925 return;
9926
9927 LHSBase = LHSME->getBase();
9928 RHSBase = RHSME->getBase();
9929 LHSME = dyn_cast<MemberExpr>(LHSBase);
9930 RHSME = dyn_cast<MemberExpr>(RHSBase);
9931 }
9932
9933 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9934 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9935 if (LHSDeclRef && RHSDeclRef) {
9936 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9937 return;
9938 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9939 RHSDeclRef->getDecl()->getCanonicalDecl())
9940 return;
9941
9942 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9943 << LHSExpr->getSourceRange()
9944 << RHSExpr->getSourceRange();
9945 return;
9946 }
9947
9948 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9949 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9950 << LHSExpr->getSourceRange()
9951 << RHSExpr->getSourceRange();
9952}
9953
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009954//===--- Layout compatibility ----------------------------------------------//
9955
9956namespace {
9957
9958bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9959
9960/// \brief Check if two enumeration types are layout-compatible.
9961bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9962 // C++11 [dcl.enum] p8:
9963 // Two enumeration types are layout-compatible if they have the same
9964 // underlying type.
9965 return ED1->isComplete() && ED2->isComplete() &&
9966 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9967}
9968
9969/// \brief Check if two fields are layout-compatible.
9970bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9971 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9972 return false;
9973
9974 if (Field1->isBitField() != Field2->isBitField())
9975 return false;
9976
9977 if (Field1->isBitField()) {
9978 // Make sure that the bit-fields are the same length.
9979 unsigned Bits1 = Field1->getBitWidthValue(C);
9980 unsigned Bits2 = Field2->getBitWidthValue(C);
9981
9982 if (Bits1 != Bits2)
9983 return false;
9984 }
9985
9986 return true;
9987}
9988
9989/// \brief Check if two standard-layout structs are layout-compatible.
9990/// (C++11 [class.mem] p17)
9991bool isLayoutCompatibleStruct(ASTContext &C,
9992 RecordDecl *RD1,
9993 RecordDecl *RD2) {
9994 // If both records are C++ classes, check that base classes match.
9995 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9996 // If one of records is a CXXRecordDecl we are in C++ mode,
9997 // thus the other one is a CXXRecordDecl, too.
9998 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9999 // Check number of base classes.
10000 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10001 return false;
10002
10003 // Check the base classes.
10004 for (CXXRecordDecl::base_class_const_iterator
10005 Base1 = D1CXX->bases_begin(),
10006 BaseEnd1 = D1CXX->bases_end(),
10007 Base2 = D2CXX->bases_begin();
10008 Base1 != BaseEnd1;
10009 ++Base1, ++Base2) {
10010 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10011 return false;
10012 }
10013 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10014 // If only RD2 is a C++ class, it should have zero base classes.
10015 if (D2CXX->getNumBases() > 0)
10016 return false;
10017 }
10018
10019 // Check the fields.
10020 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10021 Field2End = RD2->field_end(),
10022 Field1 = RD1->field_begin(),
10023 Field1End = RD1->field_end();
10024 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10025 if (!isLayoutCompatible(C, *Field1, *Field2))
10026 return false;
10027 }
10028 if (Field1 != Field1End || Field2 != Field2End)
10029 return false;
10030
10031 return true;
10032}
10033
10034/// \brief Check if two standard-layout unions are layout-compatible.
10035/// (C++11 [class.mem] p18)
10036bool isLayoutCompatibleUnion(ASTContext &C,
10037 RecordDecl *RD1,
10038 RecordDecl *RD2) {
10039 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010040 for (auto *Field2 : RD2->fields())
10041 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010042
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010043 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010044 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10045 I = UnmatchedFields.begin(),
10046 E = UnmatchedFields.end();
10047
10048 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010049 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010050 bool Result = UnmatchedFields.erase(*I);
10051 (void) Result;
10052 assert(Result);
10053 break;
10054 }
10055 }
10056 if (I == E)
10057 return false;
10058 }
10059
10060 return UnmatchedFields.empty();
10061}
10062
10063bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10064 if (RD1->isUnion() != RD2->isUnion())
10065 return false;
10066
10067 if (RD1->isUnion())
10068 return isLayoutCompatibleUnion(C, RD1, RD2);
10069 else
10070 return isLayoutCompatibleStruct(C, RD1, RD2);
10071}
10072
10073/// \brief Check if two types are layout-compatible in C++11 sense.
10074bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10075 if (T1.isNull() || T2.isNull())
10076 return false;
10077
10078 // C++11 [basic.types] p11:
10079 // If two types T1 and T2 are the same type, then T1 and T2 are
10080 // layout-compatible types.
10081 if (C.hasSameType(T1, T2))
10082 return true;
10083
10084 T1 = T1.getCanonicalType().getUnqualifiedType();
10085 T2 = T2.getCanonicalType().getUnqualifiedType();
10086
10087 const Type::TypeClass TC1 = T1->getTypeClass();
10088 const Type::TypeClass TC2 = T2->getTypeClass();
10089
10090 if (TC1 != TC2)
10091 return false;
10092
10093 if (TC1 == Type::Enum) {
10094 return isLayoutCompatible(C,
10095 cast<EnumType>(T1)->getDecl(),
10096 cast<EnumType>(T2)->getDecl());
10097 } else if (TC1 == Type::Record) {
10098 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10099 return false;
10100
10101 return isLayoutCompatible(C,
10102 cast<RecordType>(T1)->getDecl(),
10103 cast<RecordType>(T2)->getDecl());
10104 }
10105
10106 return false;
10107}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010108} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010109
10110//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10111
10112namespace {
10113/// \brief Given a type tag expression find the type tag itself.
10114///
10115/// \param TypeExpr Type tag expression, as it appears in user's code.
10116///
10117/// \param VD Declaration of an identifier that appears in a type tag.
10118///
10119/// \param MagicValue Type tag magic value.
10120bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10121 const ValueDecl **VD, uint64_t *MagicValue) {
10122 while(true) {
10123 if (!TypeExpr)
10124 return false;
10125
10126 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10127
10128 switch (TypeExpr->getStmtClass()) {
10129 case Stmt::UnaryOperatorClass: {
10130 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10131 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10132 TypeExpr = UO->getSubExpr();
10133 continue;
10134 }
10135 return false;
10136 }
10137
10138 case Stmt::DeclRefExprClass: {
10139 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10140 *VD = DRE->getDecl();
10141 return true;
10142 }
10143
10144 case Stmt::IntegerLiteralClass: {
10145 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10146 llvm::APInt MagicValueAPInt = IL->getValue();
10147 if (MagicValueAPInt.getActiveBits() <= 64) {
10148 *MagicValue = MagicValueAPInt.getZExtValue();
10149 return true;
10150 } else
10151 return false;
10152 }
10153
10154 case Stmt::BinaryConditionalOperatorClass:
10155 case Stmt::ConditionalOperatorClass: {
10156 const AbstractConditionalOperator *ACO =
10157 cast<AbstractConditionalOperator>(TypeExpr);
10158 bool Result;
10159 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10160 if (Result)
10161 TypeExpr = ACO->getTrueExpr();
10162 else
10163 TypeExpr = ACO->getFalseExpr();
10164 continue;
10165 }
10166 return false;
10167 }
10168
10169 case Stmt::BinaryOperatorClass: {
10170 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10171 if (BO->getOpcode() == BO_Comma) {
10172 TypeExpr = BO->getRHS();
10173 continue;
10174 }
10175 return false;
10176 }
10177
10178 default:
10179 return false;
10180 }
10181 }
10182}
10183
10184/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10185///
10186/// \param TypeExpr Expression that specifies a type tag.
10187///
10188/// \param MagicValues Registered magic values.
10189///
10190/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10191/// kind.
10192///
10193/// \param TypeInfo Information about the corresponding C type.
10194///
10195/// \returns true if the corresponding C type was found.
10196bool GetMatchingCType(
10197 const IdentifierInfo *ArgumentKind,
10198 const Expr *TypeExpr, const ASTContext &Ctx,
10199 const llvm::DenseMap<Sema::TypeTagMagicValue,
10200 Sema::TypeTagData> *MagicValues,
10201 bool &FoundWrongKind,
10202 Sema::TypeTagData &TypeInfo) {
10203 FoundWrongKind = false;
10204
10205 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010206 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010207
10208 uint64_t MagicValue;
10209
10210 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10211 return false;
10212
10213 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010214 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010215 if (I->getArgumentKind() != ArgumentKind) {
10216 FoundWrongKind = true;
10217 return false;
10218 }
10219 TypeInfo.Type = I->getMatchingCType();
10220 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10221 TypeInfo.MustBeNull = I->getMustBeNull();
10222 return true;
10223 }
10224 return false;
10225 }
10226
10227 if (!MagicValues)
10228 return false;
10229
10230 llvm::DenseMap<Sema::TypeTagMagicValue,
10231 Sema::TypeTagData>::const_iterator I =
10232 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10233 if (I == MagicValues->end())
10234 return false;
10235
10236 TypeInfo = I->second;
10237 return true;
10238}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010239} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010240
10241void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10242 uint64_t MagicValue, QualType Type,
10243 bool LayoutCompatible,
10244 bool MustBeNull) {
10245 if (!TypeTagForDatatypeMagicValues)
10246 TypeTagForDatatypeMagicValues.reset(
10247 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10248
10249 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10250 (*TypeTagForDatatypeMagicValues)[Magic] =
10251 TypeTagData(Type, LayoutCompatible, MustBeNull);
10252}
10253
10254namespace {
10255bool IsSameCharType(QualType T1, QualType T2) {
10256 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10257 if (!BT1)
10258 return false;
10259
10260 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10261 if (!BT2)
10262 return false;
10263
10264 BuiltinType::Kind T1Kind = BT1->getKind();
10265 BuiltinType::Kind T2Kind = BT2->getKind();
10266
10267 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10268 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10269 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10270 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10271}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010272} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010273
10274void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10275 const Expr * const *ExprArgs) {
10276 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10277 bool IsPointerAttr = Attr->getIsPointer();
10278
10279 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10280 bool FoundWrongKind;
10281 TypeTagData TypeInfo;
10282 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10283 TypeTagForDatatypeMagicValues.get(),
10284 FoundWrongKind, TypeInfo)) {
10285 if (FoundWrongKind)
10286 Diag(TypeTagExpr->getExprLoc(),
10287 diag::warn_type_tag_for_datatype_wrong_kind)
10288 << TypeTagExpr->getSourceRange();
10289 return;
10290 }
10291
10292 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10293 if (IsPointerAttr) {
10294 // Skip implicit cast of pointer to `void *' (as a function argument).
10295 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010296 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010297 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010298 ArgumentExpr = ICE->getSubExpr();
10299 }
10300 QualType ArgumentType = ArgumentExpr->getType();
10301
10302 // Passing a `void*' pointer shouldn't trigger a warning.
10303 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10304 return;
10305
10306 if (TypeInfo.MustBeNull) {
10307 // Type tag with matching void type requires a null pointer.
10308 if (!ArgumentExpr->isNullPointerConstant(Context,
10309 Expr::NPC_ValueDependentIsNotNull)) {
10310 Diag(ArgumentExpr->getExprLoc(),
10311 diag::warn_type_safety_null_pointer_required)
10312 << ArgumentKind->getName()
10313 << ArgumentExpr->getSourceRange()
10314 << TypeTagExpr->getSourceRange();
10315 }
10316 return;
10317 }
10318
10319 QualType RequiredType = TypeInfo.Type;
10320 if (IsPointerAttr)
10321 RequiredType = Context.getPointerType(RequiredType);
10322
10323 bool mismatch = false;
10324 if (!TypeInfo.LayoutCompatible) {
10325 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10326
10327 // C++11 [basic.fundamental] p1:
10328 // Plain char, signed char, and unsigned char are three distinct types.
10329 //
10330 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10331 // char' depending on the current char signedness mode.
10332 if (mismatch)
10333 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10334 RequiredType->getPointeeType())) ||
10335 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10336 mismatch = false;
10337 } else
10338 if (IsPointerAttr)
10339 mismatch = !isLayoutCompatible(Context,
10340 ArgumentType->getPointeeType(),
10341 RequiredType->getPointeeType());
10342 else
10343 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10344
10345 if (mismatch)
10346 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010347 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010348 << TypeInfo.LayoutCompatible << RequiredType
10349 << ArgumentExpr->getSourceRange()
10350 << TypeTagExpr->getSourceRange();
10351}