blob: 966d34939260fc7600dd71d90baa6cc1ecef2be4 [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.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003624 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
3625 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
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.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003630 if (Args.size() == firstDataArg) {
3631 const SemaDiagnosticBuilder &D =
3632 Diag(FormatLoc, diag::warn_format_nonliteral_noargs);
3633 switch (Type) {
3634 default:
3635 D << OrigFormatExpr->getSourceRange();
3636 break;
3637 case FST_Kprintf:
3638 case FST_FreeBSDKPrintf:
3639 case FST_Printf:
3640 D << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
3641 break;
3642 case FST_NSString:
3643 D << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
3644 break;
3645 }
3646 } else {
3647 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003648 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003649 }
Richard Smith55ce3522012-06-25 20:30:08 +00003650 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003651}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003652
Ted Kremenekab278de2010-01-28 23:39:18 +00003653namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003654class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3655protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003656 Sema &S;
3657 const StringLiteral *FExpr;
3658 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003659 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003660 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003661 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003662 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003663 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003664 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003665 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003666 bool usesPositionalArgs;
3667 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003668 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003669 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003670 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003671 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003672
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003673public:
Ted Kremenek02087932010-07-16 02:11:22 +00003674 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003675 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003676 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003677 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003678 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003679 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003680 llvm::SmallBitVector &CheckedVarArgs,
3681 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00003682 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003683 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3684 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003685 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003686 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003687 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003688 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00003689 CoveredArgs.resize(numDataArgs);
3690 CoveredArgs.reset();
3691 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003692
Ted Kremenek019d2242010-01-29 01:50:07 +00003693 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003694
Ted Kremenek02087932010-07-16 02:11:22 +00003695 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003696 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003697
Jordan Rose92303592012-09-08 04:00:03 +00003698 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003699 const analyze_format_string::FormatSpecifier &FS,
3700 const analyze_format_string::ConversionSpecifier &CS,
3701 const char *startSpecifier, unsigned specifierLen,
3702 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003703
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003704 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003705 const analyze_format_string::FormatSpecifier &FS,
3706 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003707
3708 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003709 const analyze_format_string::ConversionSpecifier &CS,
3710 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003711
Craig Toppere14c0f82014-03-12 04:55:44 +00003712 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003713
Craig Toppere14c0f82014-03-12 04:55:44 +00003714 void HandleInvalidPosition(const char *startSpecifier,
3715 unsigned specifierLen,
3716 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003717
Craig Toppere14c0f82014-03-12 04:55:44 +00003718 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003719
Craig Toppere14c0f82014-03-12 04:55:44 +00003720 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003721
Richard Trieu03cf7b72011-10-28 00:41:25 +00003722 template <typename Range>
3723 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3724 const Expr *ArgumentExpr,
3725 PartialDiagnostic PDiag,
3726 SourceLocation StringLoc,
3727 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003728 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003729
Ted Kremenek02087932010-07-16 02:11:22 +00003730protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003731 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3732 const char *startSpec,
3733 unsigned specifierLen,
3734 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003735
3736 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3737 const char *startSpec,
3738 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003739
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003740 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003741 CharSourceRange getSpecifierRange(const char *startSpecifier,
3742 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003743 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003744
Ted Kremenek5739de72010-01-29 01:06:55 +00003745 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003746
3747 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3748 const analyze_format_string::ConversionSpecifier &CS,
3749 const char *startSpecifier, unsigned specifierLen,
3750 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003751
3752 template <typename Range>
3753 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3754 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003755 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003756};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003757} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00003758
Ted Kremenek02087932010-07-16 02:11:22 +00003759SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003760 return OrigFormatExpr->getSourceRange();
3761}
3762
Ted Kremenek02087932010-07-16 02:11:22 +00003763CharSourceRange CheckFormatHandler::
3764getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003765 SourceLocation Start = getLocationOfByte(startSpecifier);
3766 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3767
3768 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003769 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003770
3771 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003772}
3773
Ted Kremenek02087932010-07-16 02:11:22 +00003774SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003775 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003776}
3777
Ted Kremenek02087932010-07-16 02:11:22 +00003778void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3779 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003780 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3781 getLocationOfByte(startSpecifier),
3782 /*IsStringLocation*/true,
3783 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003784}
3785
Jordan Rose92303592012-09-08 04:00:03 +00003786void CheckFormatHandler::HandleInvalidLengthModifier(
3787 const analyze_format_string::FormatSpecifier &FS,
3788 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003789 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003790 using namespace analyze_format_string;
3791
3792 const LengthModifier &LM = FS.getLengthModifier();
3793 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3794
3795 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003796 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003797 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003798 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003799 getLocationOfByte(LM.getStart()),
3800 /*IsStringLocation*/true,
3801 getSpecifierRange(startSpecifier, specifierLen));
3802
3803 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3804 << FixedLM->toString()
3805 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3806
3807 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003808 FixItHint Hint;
3809 if (DiagID == diag::warn_format_nonsensical_length)
3810 Hint = FixItHint::CreateRemoval(LMRange);
3811
3812 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003813 getLocationOfByte(LM.getStart()),
3814 /*IsStringLocation*/true,
3815 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003816 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003817 }
3818}
3819
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003820void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003821 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003822 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003823 using namespace analyze_format_string;
3824
3825 const LengthModifier &LM = FS.getLengthModifier();
3826 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3827
3828 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003829 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003830 if (FixedLM) {
3831 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3832 << LM.toString() << 0,
3833 getLocationOfByte(LM.getStart()),
3834 /*IsStringLocation*/true,
3835 getSpecifierRange(startSpecifier, specifierLen));
3836
3837 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3838 << FixedLM->toString()
3839 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3840
3841 } else {
3842 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3843 << LM.toString() << 0,
3844 getLocationOfByte(LM.getStart()),
3845 /*IsStringLocation*/true,
3846 getSpecifierRange(startSpecifier, specifierLen));
3847 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003848}
3849
3850void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3851 const analyze_format_string::ConversionSpecifier &CS,
3852 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003853 using namespace analyze_format_string;
3854
3855 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003856 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003857 if (FixedCS) {
3858 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3859 << CS.toString() << /*conversion specifier*/1,
3860 getLocationOfByte(CS.getStart()),
3861 /*IsStringLocation*/true,
3862 getSpecifierRange(startSpecifier, specifierLen));
3863
3864 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3865 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3866 << FixedCS->toString()
3867 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3868 } else {
3869 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3870 << CS.toString() << /*conversion specifier*/1,
3871 getLocationOfByte(CS.getStart()),
3872 /*IsStringLocation*/true,
3873 getSpecifierRange(startSpecifier, specifierLen));
3874 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003875}
3876
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003877void CheckFormatHandler::HandlePosition(const char *startPos,
3878 unsigned posLen) {
3879 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3880 getLocationOfByte(startPos),
3881 /*IsStringLocation*/true,
3882 getSpecifierRange(startPos, posLen));
3883}
3884
Ted Kremenekd1668192010-02-27 01:41:03 +00003885void
Ted Kremenek02087932010-07-16 02:11:22 +00003886CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3887 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003888 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3889 << (unsigned) p,
3890 getLocationOfByte(startPos), /*IsStringLocation*/true,
3891 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003892}
3893
Ted Kremenek02087932010-07-16 02:11:22 +00003894void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003895 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003896 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3897 getLocationOfByte(startPos),
3898 /*IsStringLocation*/true,
3899 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003900}
3901
Ted Kremenek02087932010-07-16 02:11:22 +00003902void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003903 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003904 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003905 EmitFormatDiagnostic(
3906 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3907 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3908 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003909 }
Ted Kremenek02087932010-07-16 02:11:22 +00003910}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003911
Jordan Rose58bbe422012-07-19 18:10:08 +00003912// Note that this may return NULL if there was an error parsing or building
3913// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003914const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003915 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003916}
3917
3918void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003919 // Does the number of data arguments exceed the number of
3920 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00003921 if (!HasVAListArg) {
3922 // Find any arguments that weren't covered.
3923 CoveredArgs.flip();
3924 signed notCoveredArg = CoveredArgs.find_first();
3925 if (notCoveredArg >= 0) {
3926 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003927 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
3928 } else {
3929 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00003930 }
3931 }
3932}
3933
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003934void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
3935 const Expr *ArgExpr) {
3936 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
3937 "Invalid state");
3938
3939 if (!ArgExpr)
3940 return;
3941
3942 SourceLocation Loc = ArgExpr->getLocStart();
3943
3944 if (S.getSourceManager().isInSystemMacro(Loc))
3945 return;
3946
3947 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
3948 for (auto E : DiagnosticExprs)
3949 PDiag << E->getSourceRange();
3950
3951 CheckFormatHandler::EmitFormatDiagnostic(
3952 S, IsFunctionCall, DiagnosticExprs[0],
3953 PDiag, Loc, /*IsStringLocation*/false,
3954 DiagnosticExprs[0]->getSourceRange());
3955}
3956
Ted Kremenekce815422010-07-19 21:25:57 +00003957bool
3958CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3959 SourceLocation Loc,
3960 const char *startSpec,
3961 unsigned specifierLen,
3962 const char *csStart,
3963 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00003964 bool keepGoing = true;
3965 if (argIndex < NumDataArgs) {
3966 // Consider the argument coverered, even though the specifier doesn't
3967 // make sense.
3968 CoveredArgs.set(argIndex);
3969 }
3970 else {
3971 // If argIndex exceeds the number of data arguments we
3972 // don't issue a warning because that is just a cascade of warnings (and
3973 // they may have intended '%%' anyway). We don't want to continue processing
3974 // the format string after this point, however, as we will like just get
3975 // gibberish when trying to match arguments.
3976 keepGoing = false;
3977 }
3978
Richard Trieu03cf7b72011-10-28 00:41:25 +00003979 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3980 << StringRef(csStart, csLen),
3981 Loc, /*IsStringLocation*/true,
3982 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003983
3984 return keepGoing;
3985}
3986
Richard Trieu03cf7b72011-10-28 00:41:25 +00003987void
3988CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3989 const char *startSpec,
3990 unsigned specifierLen) {
3991 EmitFormatDiagnostic(
3992 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3993 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3994}
3995
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003996bool
3997CheckFormatHandler::CheckNumArgs(
3998 const analyze_format_string::FormatSpecifier &FS,
3999 const analyze_format_string::ConversionSpecifier &CS,
4000 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4001
4002 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004003 PartialDiagnostic PDiag = FS.usesPositionalArg()
4004 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4005 << (argIndex+1) << NumDataArgs)
4006 : S.PDiag(diag::warn_printf_insufficient_data_args);
4007 EmitFormatDiagnostic(
4008 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4009 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004010
4011 // Since more arguments than conversion tokens are given, by extension
4012 // all arguments are covered, so mark this as so.
4013 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004014 return false;
4015 }
4016 return true;
4017}
4018
Richard Trieu03cf7b72011-10-28 00:41:25 +00004019template<typename Range>
4020void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4021 SourceLocation Loc,
4022 bool IsStringLocation,
4023 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004024 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004025 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004026 Loc, IsStringLocation, StringRange, FixIt);
4027}
4028
4029/// \brief If the format string is not within the funcion call, emit a note
4030/// so that the function call and string are in diagnostic messages.
4031///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004032/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004033/// call and only one diagnostic message will be produced. Otherwise, an
4034/// extra note will be emitted pointing to location of the format string.
4035///
4036/// \param ArgumentExpr the expression that is passed as the format string
4037/// argument in the function call. Used for getting locations when two
4038/// diagnostics are emitted.
4039///
4040/// \param PDiag the callee should already have provided any strings for the
4041/// diagnostic message. This function only adds locations and fixits
4042/// to diagnostics.
4043///
4044/// \param Loc primary location for diagnostic. If two diagnostics are
4045/// required, one will be at Loc and a new SourceLocation will be created for
4046/// the other one.
4047///
4048/// \param IsStringLocation if true, Loc points to the format string should be
4049/// used for the note. Otherwise, Loc points to the argument list and will
4050/// be used with PDiag.
4051///
4052/// \param StringRange some or all of the string to highlight. This is
4053/// templated so it can accept either a CharSourceRange or a SourceRange.
4054///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004055/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004056template<typename Range>
4057void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
4058 const Expr *ArgumentExpr,
4059 PartialDiagnostic PDiag,
4060 SourceLocation Loc,
4061 bool IsStringLocation,
4062 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004063 ArrayRef<FixItHint> FixIt) {
4064 if (InFunctionCall) {
4065 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4066 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004067 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004068 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004069 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4070 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004071
4072 const Sema::SemaDiagnosticBuilder &Note =
4073 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4074 diag::note_format_string_defined);
4075
4076 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004077 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004078 }
4079}
4080
Ted Kremenek02087932010-07-16 02:11:22 +00004081//===--- CHECK: Printf format string checking ------------------------------===//
4082
4083namespace {
4084class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004085 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004086
Ted Kremenek02087932010-07-16 02:11:22 +00004087public:
4088 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4089 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004090 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004091 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004092 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004093 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004094 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004095 llvm::SmallBitVector &CheckedVarArgs,
4096 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004097 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4098 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004099 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4100 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004101 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004102 {}
4103
Ted Kremenek02087932010-07-16 02:11:22 +00004104 bool HandleInvalidPrintfConversionSpecifier(
4105 const analyze_printf::PrintfSpecifier &FS,
4106 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004107 unsigned specifierLen) override;
4108
Ted Kremenek02087932010-07-16 02:11:22 +00004109 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4110 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004111 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004112 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4113 const char *StartSpecifier,
4114 unsigned SpecifierLen,
4115 const Expr *E);
4116
Ted Kremenek02087932010-07-16 02:11:22 +00004117 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4118 const char *startSpecifier, unsigned specifierLen);
4119 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4120 const analyze_printf::OptionalAmount &Amt,
4121 unsigned type,
4122 const char *startSpecifier, unsigned specifierLen);
4123 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4124 const analyze_printf::OptionalFlag &flag,
4125 const char *startSpecifier, unsigned specifierLen);
4126 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4127 const analyze_printf::OptionalFlag &ignoredFlag,
4128 const analyze_printf::OptionalFlag &flag,
4129 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004130 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004131 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004132
4133 void HandleEmptyObjCModifierFlag(const char *startFlag,
4134 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004135
Ted Kremenek2b417712015-07-02 05:39:16 +00004136 void HandleInvalidObjCModifierFlag(const char *startFlag,
4137 unsigned flagLen) override;
4138
4139 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4140 const char *flagsEnd,
4141 const char *conversionPosition)
4142 override;
4143};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004144} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004145
4146bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4147 const analyze_printf::PrintfSpecifier &FS,
4148 const char *startSpecifier,
4149 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004150 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004151 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004152
Ted Kremenekce815422010-07-19 21:25:57 +00004153 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4154 getLocationOfByte(CS.getStart()),
4155 startSpecifier, specifierLen,
4156 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004157}
4158
Ted Kremenek02087932010-07-16 02:11:22 +00004159bool CheckPrintfHandler::HandleAmount(
4160 const analyze_format_string::OptionalAmount &Amt,
4161 unsigned k, const char *startSpecifier,
4162 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004163 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004164 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004165 unsigned argIndex = Amt.getArgIndex();
4166 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004167 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4168 << k,
4169 getLocationOfByte(Amt.getStart()),
4170 /*IsStringLocation*/true,
4171 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004172 // Don't do any more checking. We will just emit
4173 // spurious errors.
4174 return false;
4175 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004176
Ted Kremenek5739de72010-01-29 01:06:55 +00004177 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004178 // Although not in conformance with C99, we also allow the argument to be
4179 // an 'unsigned int' as that is a reasonably safe case. GCC also
4180 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004181 CoveredArgs.set(argIndex);
4182 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004183 if (!Arg)
4184 return false;
4185
Ted Kremenek5739de72010-01-29 01:06:55 +00004186 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004187
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004188 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4189 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004190
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004191 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004192 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004193 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004194 << T << Arg->getSourceRange(),
4195 getLocationOfByte(Amt.getStart()),
4196 /*IsStringLocation*/true,
4197 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004198 // Don't do any more checking. We will just emit
4199 // spurious errors.
4200 return false;
4201 }
4202 }
4203 }
4204 return true;
4205}
Ted Kremenek5739de72010-01-29 01:06:55 +00004206
Tom Careb49ec692010-06-17 19:00:27 +00004207void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004208 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004209 const analyze_printf::OptionalAmount &Amt,
4210 unsigned type,
4211 const char *startSpecifier,
4212 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004213 const analyze_printf::PrintfConversionSpecifier &CS =
4214 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004215
Richard Trieu03cf7b72011-10-28 00:41:25 +00004216 FixItHint fixit =
4217 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4218 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4219 Amt.getConstantLength()))
4220 : FixItHint();
4221
4222 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4223 << type << CS.toString(),
4224 getLocationOfByte(Amt.getStart()),
4225 /*IsStringLocation*/true,
4226 getSpecifierRange(startSpecifier, specifierLen),
4227 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004228}
4229
Ted Kremenek02087932010-07-16 02:11:22 +00004230void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004231 const analyze_printf::OptionalFlag &flag,
4232 const char *startSpecifier,
4233 unsigned specifierLen) {
4234 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004235 const analyze_printf::PrintfConversionSpecifier &CS =
4236 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004237 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4238 << flag.toString() << CS.toString(),
4239 getLocationOfByte(flag.getPosition()),
4240 /*IsStringLocation*/true,
4241 getSpecifierRange(startSpecifier, specifierLen),
4242 FixItHint::CreateRemoval(
4243 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004244}
4245
4246void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004247 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004248 const analyze_printf::OptionalFlag &ignoredFlag,
4249 const analyze_printf::OptionalFlag &flag,
4250 const char *startSpecifier,
4251 unsigned specifierLen) {
4252 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004253 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4254 << ignoredFlag.toString() << flag.toString(),
4255 getLocationOfByte(ignoredFlag.getPosition()),
4256 /*IsStringLocation*/true,
4257 getSpecifierRange(startSpecifier, specifierLen),
4258 FixItHint::CreateRemoval(
4259 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004260}
4261
Ted Kremenek2b417712015-07-02 05:39:16 +00004262// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4263// bool IsStringLocation, Range StringRange,
4264// ArrayRef<FixItHint> Fixit = None);
4265
4266void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4267 unsigned flagLen) {
4268 // Warn about an empty flag.
4269 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4270 getLocationOfByte(startFlag),
4271 /*IsStringLocation*/true,
4272 getSpecifierRange(startFlag, flagLen));
4273}
4274
4275void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4276 unsigned flagLen) {
4277 // Warn about an invalid flag.
4278 auto Range = getSpecifierRange(startFlag, flagLen);
4279 StringRef flag(startFlag, flagLen);
4280 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4281 getLocationOfByte(startFlag),
4282 /*IsStringLocation*/true,
4283 Range, FixItHint::CreateRemoval(Range));
4284}
4285
4286void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4287 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4288 // Warn about using '[...]' without a '@' conversion.
4289 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4290 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4291 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4292 getLocationOfByte(conversionPosition),
4293 /*IsStringLocation*/true,
4294 Range, FixItHint::CreateRemoval(Range));
4295}
4296
Richard Smith55ce3522012-06-25 20:30:08 +00004297// Determines if the specified is a C++ class or struct containing
4298// a member with the specified name and kind (e.g. a CXXMethodDecl named
4299// "c_str()").
4300template<typename MemberKind>
4301static llvm::SmallPtrSet<MemberKind*, 1>
4302CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4303 const RecordType *RT = Ty->getAs<RecordType>();
4304 llvm::SmallPtrSet<MemberKind*, 1> Results;
4305
4306 if (!RT)
4307 return Results;
4308 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004309 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004310 return Results;
4311
Alp Tokerb6cc5922014-05-03 03:45:55 +00004312 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004313 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004314 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004315
4316 // We just need to include all members of the right kind turned up by the
4317 // filter, at this point.
4318 if (S.LookupQualifiedName(R, RT->getDecl()))
4319 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4320 NamedDecl *decl = (*I)->getUnderlyingDecl();
4321 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4322 Results.insert(FK);
4323 }
4324 return Results;
4325}
4326
Richard Smith2868a732014-02-28 01:36:39 +00004327/// Check if we could call '.c_str()' on an object.
4328///
4329/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4330/// allow the call, or if it would be ambiguous).
4331bool Sema::hasCStrMethod(const Expr *E) {
4332 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4333 MethodSet Results =
4334 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4335 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4336 MI != ME; ++MI)
4337 if ((*MI)->getMinRequiredArguments() == 0)
4338 return true;
4339 return false;
4340}
4341
Richard Smith55ce3522012-06-25 20:30:08 +00004342// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004343// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004344// Returns true when a c_str() conversion method is found.
4345bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004346 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004347 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4348
4349 MethodSet Results =
4350 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4351
4352 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4353 MI != ME; ++MI) {
4354 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004355 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004356 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004357 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004358 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004359 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4360 << "c_str()"
4361 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4362 return true;
4363 }
4364 }
4365
4366 return false;
4367}
4368
Ted Kremenekab278de2010-01-28 23:39:18 +00004369bool
Ted Kremenek02087932010-07-16 02:11:22 +00004370CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004371 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004372 const char *startSpecifier,
4373 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004374 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004375 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004376 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004377
Ted Kremenek6cd69422010-07-19 22:01:06 +00004378 if (FS.consumesDataArgument()) {
4379 if (atFirstArg) {
4380 atFirstArg = false;
4381 usesPositionalArgs = FS.usesPositionalArg();
4382 }
4383 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004384 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4385 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004386 return false;
4387 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004388 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004389
Ted Kremenekd1668192010-02-27 01:41:03 +00004390 // First check if the field width, precision, and conversion specifier
4391 // have matching data arguments.
4392 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4393 startSpecifier, specifierLen)) {
4394 return false;
4395 }
4396
4397 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4398 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004399 return false;
4400 }
4401
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004402 if (!CS.consumesDataArgument()) {
4403 // FIXME: Technically specifying a precision or field width here
4404 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004405 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004406 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004407
Ted Kremenek4a49d982010-02-26 19:18:41 +00004408 // Consume the argument.
4409 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004410 if (argIndex < NumDataArgs) {
4411 // The check to see if the argIndex is valid will come later.
4412 // We set the bit here because we may exit early from this
4413 // function if we encounter some other error.
4414 CoveredArgs.set(argIndex);
4415 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004416
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004417 // FreeBSD kernel extensions.
4418 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4419 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4420 // We need at least two arguments.
4421 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4422 return false;
4423
4424 // Claim the second argument.
4425 CoveredArgs.set(argIndex + 1);
4426
4427 // Type check the first argument (int for %b, pointer for %D)
4428 const Expr *Ex = getDataArg(argIndex);
4429 const analyze_printf::ArgType &AT =
4430 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4431 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4432 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4433 EmitFormatDiagnostic(
4434 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4435 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4436 << false << Ex->getSourceRange(),
4437 Ex->getLocStart(), /*IsStringLocation*/false,
4438 getSpecifierRange(startSpecifier, specifierLen));
4439
4440 // Type check the second argument (char * for both %b and %D)
4441 Ex = getDataArg(argIndex + 1);
4442 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4443 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4444 EmitFormatDiagnostic(
4445 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4446 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4447 << false << Ex->getSourceRange(),
4448 Ex->getLocStart(), /*IsStringLocation*/false,
4449 getSpecifierRange(startSpecifier, specifierLen));
4450
4451 return true;
4452 }
4453
Ted Kremenek4a49d982010-02-26 19:18:41 +00004454 // Check for using an Objective-C specific conversion specifier
4455 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004456 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004457 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4458 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004459 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004460
Tom Careb49ec692010-06-17 19:00:27 +00004461 // Check for invalid use of field width
4462 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004463 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004464 startSpecifier, specifierLen);
4465 }
4466
4467 // Check for invalid use of precision
4468 if (!FS.hasValidPrecision()) {
4469 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4470 startSpecifier, specifierLen);
4471 }
4472
4473 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004474 if (!FS.hasValidThousandsGroupingPrefix())
4475 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004476 if (!FS.hasValidLeadingZeros())
4477 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4478 if (!FS.hasValidPlusPrefix())
4479 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004480 if (!FS.hasValidSpacePrefix())
4481 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004482 if (!FS.hasValidAlternativeForm())
4483 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4484 if (!FS.hasValidLeftJustified())
4485 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4486
4487 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004488 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4489 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4490 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004491 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4492 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4493 startSpecifier, specifierLen);
4494
4495 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004496 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004497 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4498 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004499 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004500 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004501 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004502 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4503 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004504
Jordan Rose92303592012-09-08 04:00:03 +00004505 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4506 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4507
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004508 // The remaining checks depend on the data arguments.
4509 if (HasVAListArg)
4510 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004511
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004512 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004513 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004514
Jordan Rose58bbe422012-07-19 18:10:08 +00004515 const Expr *Arg = getDataArg(argIndex);
4516 if (!Arg)
4517 return true;
4518
4519 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004520}
4521
Jordan Roseaee34382012-09-05 22:56:26 +00004522static bool requiresParensToAddCast(const Expr *E) {
4523 // FIXME: We should have a general way to reason about operator
4524 // precedence and whether parens are actually needed here.
4525 // Take care of a few common cases where they aren't.
4526 const Expr *Inside = E->IgnoreImpCasts();
4527 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4528 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4529
4530 switch (Inside->getStmtClass()) {
4531 case Stmt::ArraySubscriptExprClass:
4532 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004533 case Stmt::CharacterLiteralClass:
4534 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004535 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004536 case Stmt::FloatingLiteralClass:
4537 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004538 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004539 case Stmt::ObjCArrayLiteralClass:
4540 case Stmt::ObjCBoolLiteralExprClass:
4541 case Stmt::ObjCBoxedExprClass:
4542 case Stmt::ObjCDictionaryLiteralClass:
4543 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004544 case Stmt::ObjCIvarRefExprClass:
4545 case Stmt::ObjCMessageExprClass:
4546 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004547 case Stmt::ObjCStringLiteralClass:
4548 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004549 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004550 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004551 case Stmt::UnaryOperatorClass:
4552 return false;
4553 default:
4554 return true;
4555 }
4556}
4557
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004558static std::pair<QualType, StringRef>
4559shouldNotPrintDirectly(const ASTContext &Context,
4560 QualType IntendedTy,
4561 const Expr *E) {
4562 // Use a 'while' to peel off layers of typedefs.
4563 QualType TyTy = IntendedTy;
4564 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4565 StringRef Name = UserTy->getDecl()->getName();
4566 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4567 .Case("NSInteger", Context.LongTy)
4568 .Case("NSUInteger", Context.UnsignedLongTy)
4569 .Case("SInt32", Context.IntTy)
4570 .Case("UInt32", Context.UnsignedIntTy)
4571 .Default(QualType());
4572
4573 if (!CastTy.isNull())
4574 return std::make_pair(CastTy, Name);
4575
4576 TyTy = UserTy->desugar();
4577 }
4578
4579 // Strip parens if necessary.
4580 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4581 return shouldNotPrintDirectly(Context,
4582 PE->getSubExpr()->getType(),
4583 PE->getSubExpr());
4584
4585 // If this is a conditional expression, then its result type is constructed
4586 // via usual arithmetic conversions and thus there might be no necessary
4587 // typedef sugar there. Recurse to operands to check for NSInteger &
4588 // Co. usage condition.
4589 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4590 QualType TrueTy, FalseTy;
4591 StringRef TrueName, FalseName;
4592
4593 std::tie(TrueTy, TrueName) =
4594 shouldNotPrintDirectly(Context,
4595 CO->getTrueExpr()->getType(),
4596 CO->getTrueExpr());
4597 std::tie(FalseTy, FalseName) =
4598 shouldNotPrintDirectly(Context,
4599 CO->getFalseExpr()->getType(),
4600 CO->getFalseExpr());
4601
4602 if (TrueTy == FalseTy)
4603 return std::make_pair(TrueTy, TrueName);
4604 else if (TrueTy.isNull())
4605 return std::make_pair(FalseTy, FalseName);
4606 else if (FalseTy.isNull())
4607 return std::make_pair(TrueTy, TrueName);
4608 }
4609
4610 return std::make_pair(QualType(), StringRef());
4611}
4612
Richard Smith55ce3522012-06-25 20:30:08 +00004613bool
4614CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4615 const char *StartSpecifier,
4616 unsigned SpecifierLen,
4617 const Expr *E) {
4618 using namespace analyze_format_string;
4619 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004620 // Now type check the data expression that matches the
4621 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004622 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4623 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004624 if (!AT.isValid())
4625 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004626
Jordan Rose598ec092012-12-05 18:44:40 +00004627 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004628 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4629 ExprTy = TET->getUnderlyingExpr()->getType();
4630 }
4631
Seth Cantrellb4802962015-03-04 03:12:10 +00004632 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4633
4634 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004635 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004636 }
Jordan Rose98709982012-06-04 22:48:57 +00004637
Jordan Rose22b74712012-09-05 22:56:19 +00004638 // Look through argument promotions for our error message's reported type.
4639 // This includes the integral and floating promotions, but excludes array
4640 // and function pointer decay; seeing that an argument intended to be a
4641 // string has type 'char [6]' is probably more confusing than 'char *'.
4642 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4643 if (ICE->getCastKind() == CK_IntegralCast ||
4644 ICE->getCastKind() == CK_FloatingCast) {
4645 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004646 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004647
4648 // Check if we didn't match because of an implicit cast from a 'char'
4649 // or 'short' to an 'int'. This is done because printf is a varargs
4650 // function.
4651 if (ICE->getType() == S.Context.IntTy ||
4652 ICE->getType() == S.Context.UnsignedIntTy) {
4653 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004654 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004655 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004656 }
Jordan Rose98709982012-06-04 22:48:57 +00004657 }
Jordan Rose598ec092012-12-05 18:44:40 +00004658 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4659 // Special case for 'a', which has type 'int' in C.
4660 // Note, however, that we do /not/ want to treat multibyte constants like
4661 // 'MooV' as characters! This form is deprecated but still exists.
4662 if (ExprTy == S.Context.IntTy)
4663 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4664 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004665 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004666
Jordan Rosebc53ed12014-05-31 04:12:14 +00004667 // Look through enums to their underlying type.
4668 bool IsEnum = false;
4669 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4670 ExprTy = EnumTy->getDecl()->getIntegerType();
4671 IsEnum = true;
4672 }
4673
Jordan Rose0e5badd2012-12-05 18:44:49 +00004674 // %C in an Objective-C context prints a unichar, not a wchar_t.
4675 // If the argument is an integer of some kind, believe the %C and suggest
4676 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004677 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004678 if (ObjCContext &&
4679 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4680 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4681 !ExprTy->isCharType()) {
4682 // 'unichar' is defined as a typedef of unsigned short, but we should
4683 // prefer using the typedef if it is visible.
4684 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004685
4686 // While we are here, check if the value is an IntegerLiteral that happens
4687 // to be within the valid range.
4688 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4689 const llvm::APInt &V = IL->getValue();
4690 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4691 return true;
4692 }
4693
Jordan Rose0e5badd2012-12-05 18:44:49 +00004694 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4695 Sema::LookupOrdinaryName);
4696 if (S.LookupName(Result, S.getCurScope())) {
4697 NamedDecl *ND = Result.getFoundDecl();
4698 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4699 if (TD->getUnderlyingType() == IntendedTy)
4700 IntendedTy = S.Context.getTypedefType(TD);
4701 }
4702 }
4703 }
4704
4705 // Special-case some of Darwin's platform-independence types by suggesting
4706 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004707 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004708 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004709 QualType CastTy;
4710 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4711 if (!CastTy.isNull()) {
4712 IntendedTy = CastTy;
4713 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004714 }
4715 }
4716
Jordan Rose22b74712012-09-05 22:56:19 +00004717 // We may be able to offer a FixItHint if it is a supported type.
4718 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004719 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004720 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004721
Jordan Rose22b74712012-09-05 22:56:19 +00004722 if (success) {
4723 // Get the fix string from the fixed format specifier
4724 SmallString<16> buf;
4725 llvm::raw_svector_ostream os(buf);
4726 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004727
Jordan Roseaee34382012-09-05 22:56:26 +00004728 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4729
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004730 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004731 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4732 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4733 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4734 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004735 // In this case, the specifier is wrong and should be changed to match
4736 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004737 EmitFormatDiagnostic(S.PDiag(diag)
4738 << AT.getRepresentativeTypeName(S.Context)
4739 << IntendedTy << IsEnum << E->getSourceRange(),
4740 E->getLocStart(),
4741 /*IsStringLocation*/ false, SpecRange,
4742 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004743 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004744 // The canonical type for formatting this value is different from the
4745 // actual type of the expression. (This occurs, for example, with Darwin's
4746 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4747 // should be printed as 'long' for 64-bit compatibility.)
4748 // Rather than emitting a normal format/argument mismatch, we want to
4749 // add a cast to the recommended type (and correct the format string
4750 // if necessary).
4751 SmallString<16> CastBuf;
4752 llvm::raw_svector_ostream CastFix(CastBuf);
4753 CastFix << "(";
4754 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4755 CastFix << ")";
4756
4757 SmallVector<FixItHint,4> Hints;
4758 if (!AT.matchesType(S.Context, IntendedTy))
4759 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4760
4761 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4762 // If there's already a cast present, just replace it.
4763 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4764 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4765
4766 } else if (!requiresParensToAddCast(E)) {
4767 // If the expression has high enough precedence,
4768 // just write the C-style cast.
4769 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4770 CastFix.str()));
4771 } else {
4772 // Otherwise, add parens around the expression as well as the cast.
4773 CastFix << "(";
4774 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4775 CastFix.str()));
4776
Alp Tokerb6cc5922014-05-03 03:45:55 +00004777 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004778 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4779 }
4780
Jordan Rose0e5badd2012-12-05 18:44:49 +00004781 if (ShouldNotPrintDirectly) {
4782 // The expression has a type that should not be printed directly.
4783 // We extract the name from the typedef because we don't want to show
4784 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004785 StringRef Name;
4786 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4787 Name = TypedefTy->getDecl()->getName();
4788 else
4789 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004790 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004791 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004792 << E->getSourceRange(),
4793 E->getLocStart(), /*IsStringLocation=*/false,
4794 SpecRange, Hints);
4795 } else {
4796 // In this case, the expression could be printed using a different
4797 // specifier, but we've decided that the specifier is probably correct
4798 // and we should cast instead. Just use the normal warning message.
4799 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004800 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4801 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004802 << E->getSourceRange(),
4803 E->getLocStart(), /*IsStringLocation*/false,
4804 SpecRange, Hints);
4805 }
Jordan Roseaee34382012-09-05 22:56:26 +00004806 }
Jordan Rose22b74712012-09-05 22:56:19 +00004807 } else {
4808 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4809 SpecifierLen);
4810 // Since the warning for passing non-POD types to variadic functions
4811 // was deferred until now, we emit a warning for non-POD
4812 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004813 switch (S.isValidVarArgType(ExprTy)) {
4814 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004815 case Sema::VAK_ValidInCXX11: {
4816 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4817 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4818 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4819 }
Richard Smithd7293d72013-08-05 18:49:43 +00004820
Seth Cantrellb4802962015-03-04 03:12:10 +00004821 EmitFormatDiagnostic(
4822 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4823 << IsEnum << CSR << E->getSourceRange(),
4824 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4825 break;
4826 }
Richard Smithd7293d72013-08-05 18:49:43 +00004827 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004828 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004829 EmitFormatDiagnostic(
4830 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004831 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004832 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004833 << CallType
4834 << AT.getRepresentativeTypeName(S.Context)
4835 << CSR
4836 << E->getSourceRange(),
4837 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004838 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004839 break;
4840
4841 case Sema::VAK_Invalid:
4842 if (ExprTy->isObjCObjectType())
4843 EmitFormatDiagnostic(
4844 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4845 << S.getLangOpts().CPlusPlus11
4846 << ExprTy
4847 << CallType
4848 << AT.getRepresentativeTypeName(S.Context)
4849 << CSR
4850 << E->getSourceRange(),
4851 E->getLocStart(), /*IsStringLocation*/false, CSR);
4852 else
4853 // FIXME: If this is an initializer list, suggest removing the braces
4854 // or inserting a cast to the target type.
4855 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4856 << isa<InitListExpr>(E) << ExprTy << CallType
4857 << AT.getRepresentativeTypeName(S.Context)
4858 << E->getSourceRange();
4859 break;
4860 }
4861
4862 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4863 "format string specifier index out of range");
4864 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004865 }
4866
Ted Kremenekab278de2010-01-28 23:39:18 +00004867 return true;
4868}
4869
Ted Kremenek02087932010-07-16 02:11:22 +00004870//===--- CHECK: Scanf format string checking ------------------------------===//
4871
4872namespace {
4873class CheckScanfHandler : public CheckFormatHandler {
4874public:
4875 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4876 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004877 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004878 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004879 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004880 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004881 llvm::SmallBitVector &CheckedVarArgs,
4882 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004883 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4884 numDataArgs, beg, hasVAListArg,
4885 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004886 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004887 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004888
4889 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4890 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004891 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004892
4893 bool HandleInvalidScanfConversionSpecifier(
4894 const analyze_scanf::ScanfSpecifier &FS,
4895 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004896 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004897
Craig Toppere14c0f82014-03-12 04:55:44 +00004898 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004899};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004900} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004901
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004902void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4903 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004904 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4905 getLocationOfByte(end), /*IsStringLocation*/true,
4906 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004907}
4908
Ted Kremenekce815422010-07-19 21:25:57 +00004909bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4910 const analyze_scanf::ScanfSpecifier &FS,
4911 const char *startSpecifier,
4912 unsigned specifierLen) {
4913
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004914 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004915 FS.getConversionSpecifier();
4916
4917 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4918 getLocationOfByte(CS.getStart()),
4919 startSpecifier, specifierLen,
4920 CS.getStart(), CS.getLength());
4921}
4922
Ted Kremenek02087932010-07-16 02:11:22 +00004923bool CheckScanfHandler::HandleScanfSpecifier(
4924 const analyze_scanf::ScanfSpecifier &FS,
4925 const char *startSpecifier,
4926 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00004927 using namespace analyze_scanf;
4928 using namespace analyze_format_string;
4929
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004930 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004931
Ted Kremenek6cd69422010-07-19 22:01:06 +00004932 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4933 // be used to decide if we are using positional arguments consistently.
4934 if (FS.consumesDataArgument()) {
4935 if (atFirstArg) {
4936 atFirstArg = false;
4937 usesPositionalArgs = FS.usesPositionalArg();
4938 }
4939 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004940 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4941 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004942 return false;
4943 }
Ted Kremenek02087932010-07-16 02:11:22 +00004944 }
4945
4946 // Check if the field with is non-zero.
4947 const OptionalAmount &Amt = FS.getFieldWidth();
4948 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4949 if (Amt.getConstantAmount() == 0) {
4950 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4951 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004952 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4953 getLocationOfByte(Amt.getStart()),
4954 /*IsStringLocation*/true, R,
4955 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004956 }
4957 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004958
Ted Kremenek02087932010-07-16 02:11:22 +00004959 if (!FS.consumesDataArgument()) {
4960 // FIXME: Technically specifying a precision or field width here
4961 // makes no sense. Worth issuing a warning at some point.
4962 return true;
4963 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004964
Ted Kremenek02087932010-07-16 02:11:22 +00004965 // Consume the argument.
4966 unsigned argIndex = FS.getArgIndex();
4967 if (argIndex < NumDataArgs) {
4968 // The check to see if the argIndex is valid will come later.
4969 // We set the bit here because we may exit early from this
4970 // function if we encounter some other error.
4971 CoveredArgs.set(argIndex);
4972 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004973
Ted Kremenek4407ea42010-07-20 20:04:47 +00004974 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004975 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004976 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4977 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004978 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004979 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004980 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004981 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4982 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004983
Jordan Rose92303592012-09-08 04:00:03 +00004984 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4985 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4986
Ted Kremenek02087932010-07-16 02:11:22 +00004987 // The remaining checks depend on the data arguments.
4988 if (HasVAListArg)
4989 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004990
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004991 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004992 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004993
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004994 // Check that the argument type matches the format specifier.
4995 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004996 if (!Ex)
4997 return true;
4998
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004999 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005000
5001 if (!AT.isValid()) {
5002 return true;
5003 }
5004
Seth Cantrellb4802962015-03-04 03:12:10 +00005005 analyze_format_string::ArgType::MatchKind match =
5006 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005007 if (match == analyze_format_string::ArgType::Match) {
5008 return true;
5009 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005010
Seth Cantrell79340072015-03-04 05:58:08 +00005011 ScanfSpecifier fixedFS = FS;
5012 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5013 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005014
Seth Cantrell79340072015-03-04 05:58:08 +00005015 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5016 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5017 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5018 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005019
Seth Cantrell79340072015-03-04 05:58:08 +00005020 if (success) {
5021 // Get the fix string from the fixed format specifier.
5022 SmallString<128> buf;
5023 llvm::raw_svector_ostream os(buf);
5024 fixedFS.toString(os);
5025
5026 EmitFormatDiagnostic(
5027 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5028 << Ex->getType() << false << Ex->getSourceRange(),
5029 Ex->getLocStart(),
5030 /*IsStringLocation*/ false,
5031 getSpecifierRange(startSpecifier, specifierLen),
5032 FixItHint::CreateReplacement(
5033 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5034 } else {
5035 EmitFormatDiagnostic(S.PDiag(diag)
5036 << AT.getRepresentativeTypeName(S.Context)
5037 << Ex->getType() << false << Ex->getSourceRange(),
5038 Ex->getLocStart(),
5039 /*IsStringLocation*/ false,
5040 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005041 }
5042
Ted Kremenek02087932010-07-16 02:11:22 +00005043 return true;
5044}
5045
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005046static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5047 const Expr *OrigFormatExpr,
5048 ArrayRef<const Expr *> Args,
5049 bool HasVAListArg, unsigned format_idx,
5050 unsigned firstDataArg,
5051 Sema::FormatStringType Type,
5052 bool inFunctionCall,
5053 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005054 llvm::SmallBitVector &CheckedVarArgs,
5055 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005056 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005057 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005058 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005059 S, inFunctionCall, Args[format_idx],
5060 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005061 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005062 return;
5063 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005064
Ted Kremenekab278de2010-01-28 23:39:18 +00005065 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005066 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005067 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005068 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005069 const ConstantArrayType *T =
5070 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005071 assert(T && "String literal not of constant array type!");
5072 size_t TypeSize = T->getSize().getZExtValue();
5073 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005074 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005075
5076 // Emit a warning if the string literal is truncated and does not contain an
5077 // embedded null character.
5078 if (TypeSize <= StrRef.size() &&
5079 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5080 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005081 S, inFunctionCall, Args[format_idx],
5082 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005083 FExpr->getLocStart(),
5084 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5085 return;
5086 }
5087
Ted Kremenekab278de2010-01-28 23:39:18 +00005088 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005089 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005090 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005091 S, inFunctionCall, Args[format_idx],
5092 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005093 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005094 return;
5095 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005096
5097 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5098 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5099 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5100 numDataArgs, (Type == Sema::FST_NSString ||
5101 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005102 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005103 inFunctionCall, CallType, CheckedVarArgs,
5104 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005105
Hans Wennborg23926bd2011-12-15 10:25:47 +00005106 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005107 S.getLangOpts(),
5108 S.Context.getTargetInfo(),
5109 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005110 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005111 } else if (Type == Sema::FST_Scanf) {
5112 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005113 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005114 inFunctionCall, CallType, CheckedVarArgs,
5115 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005116
Hans Wennborg23926bd2011-12-15 10:25:47 +00005117 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005118 S.getLangOpts(),
5119 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005120 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005121 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005122}
5123
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005124bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5125 // Str - The format string. NOTE: this is NOT null-terminated!
5126 StringRef StrRef = FExpr->getString();
5127 const char *Str = StrRef.data();
5128 // Account for cases where the string literal is truncated in a declaration.
5129 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5130 assert(T && "String literal not of constant array type!");
5131 size_t TypeSize = T->getSize().getZExtValue();
5132 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5133 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5134 getLangOpts(),
5135 Context.getTargetInfo());
5136}
5137
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005138//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5139
5140// Returns the related absolute value function that is larger, of 0 if one
5141// does not exist.
5142static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5143 switch (AbsFunction) {
5144 default:
5145 return 0;
5146
5147 case Builtin::BI__builtin_abs:
5148 return Builtin::BI__builtin_labs;
5149 case Builtin::BI__builtin_labs:
5150 return Builtin::BI__builtin_llabs;
5151 case Builtin::BI__builtin_llabs:
5152 return 0;
5153
5154 case Builtin::BI__builtin_fabsf:
5155 return Builtin::BI__builtin_fabs;
5156 case Builtin::BI__builtin_fabs:
5157 return Builtin::BI__builtin_fabsl;
5158 case Builtin::BI__builtin_fabsl:
5159 return 0;
5160
5161 case Builtin::BI__builtin_cabsf:
5162 return Builtin::BI__builtin_cabs;
5163 case Builtin::BI__builtin_cabs:
5164 return Builtin::BI__builtin_cabsl;
5165 case Builtin::BI__builtin_cabsl:
5166 return 0;
5167
5168 case Builtin::BIabs:
5169 return Builtin::BIlabs;
5170 case Builtin::BIlabs:
5171 return Builtin::BIllabs;
5172 case Builtin::BIllabs:
5173 return 0;
5174
5175 case Builtin::BIfabsf:
5176 return Builtin::BIfabs;
5177 case Builtin::BIfabs:
5178 return Builtin::BIfabsl;
5179 case Builtin::BIfabsl:
5180 return 0;
5181
5182 case Builtin::BIcabsf:
5183 return Builtin::BIcabs;
5184 case Builtin::BIcabs:
5185 return Builtin::BIcabsl;
5186 case Builtin::BIcabsl:
5187 return 0;
5188 }
5189}
5190
5191// Returns the argument type of the absolute value function.
5192static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5193 unsigned AbsType) {
5194 if (AbsType == 0)
5195 return QualType();
5196
5197 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5198 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5199 if (Error != ASTContext::GE_None)
5200 return QualType();
5201
5202 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5203 if (!FT)
5204 return QualType();
5205
5206 if (FT->getNumParams() != 1)
5207 return QualType();
5208
5209 return FT->getParamType(0);
5210}
5211
5212// Returns the best absolute value function, or zero, based on type and
5213// current absolute value function.
5214static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5215 unsigned AbsFunctionKind) {
5216 unsigned BestKind = 0;
5217 uint64_t ArgSize = Context.getTypeSize(ArgType);
5218 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5219 Kind = getLargerAbsoluteValueFunction(Kind)) {
5220 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5221 if (Context.getTypeSize(ParamType) >= ArgSize) {
5222 if (BestKind == 0)
5223 BestKind = Kind;
5224 else if (Context.hasSameType(ParamType, ArgType)) {
5225 BestKind = Kind;
5226 break;
5227 }
5228 }
5229 }
5230 return BestKind;
5231}
5232
5233enum AbsoluteValueKind {
5234 AVK_Integer,
5235 AVK_Floating,
5236 AVK_Complex
5237};
5238
5239static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5240 if (T->isIntegralOrEnumerationType())
5241 return AVK_Integer;
5242 if (T->isRealFloatingType())
5243 return AVK_Floating;
5244 if (T->isAnyComplexType())
5245 return AVK_Complex;
5246
5247 llvm_unreachable("Type not integer, floating, or complex");
5248}
5249
5250// Changes the absolute value function to a different type. Preserves whether
5251// the function is a builtin.
5252static unsigned changeAbsFunction(unsigned AbsKind,
5253 AbsoluteValueKind ValueKind) {
5254 switch (ValueKind) {
5255 case AVK_Integer:
5256 switch (AbsKind) {
5257 default:
5258 return 0;
5259 case Builtin::BI__builtin_fabsf:
5260 case Builtin::BI__builtin_fabs:
5261 case Builtin::BI__builtin_fabsl:
5262 case Builtin::BI__builtin_cabsf:
5263 case Builtin::BI__builtin_cabs:
5264 case Builtin::BI__builtin_cabsl:
5265 return Builtin::BI__builtin_abs;
5266 case Builtin::BIfabsf:
5267 case Builtin::BIfabs:
5268 case Builtin::BIfabsl:
5269 case Builtin::BIcabsf:
5270 case Builtin::BIcabs:
5271 case Builtin::BIcabsl:
5272 return Builtin::BIabs;
5273 }
5274 case AVK_Floating:
5275 switch (AbsKind) {
5276 default:
5277 return 0;
5278 case Builtin::BI__builtin_abs:
5279 case Builtin::BI__builtin_labs:
5280 case Builtin::BI__builtin_llabs:
5281 case Builtin::BI__builtin_cabsf:
5282 case Builtin::BI__builtin_cabs:
5283 case Builtin::BI__builtin_cabsl:
5284 return Builtin::BI__builtin_fabsf;
5285 case Builtin::BIabs:
5286 case Builtin::BIlabs:
5287 case Builtin::BIllabs:
5288 case Builtin::BIcabsf:
5289 case Builtin::BIcabs:
5290 case Builtin::BIcabsl:
5291 return Builtin::BIfabsf;
5292 }
5293 case AVK_Complex:
5294 switch (AbsKind) {
5295 default:
5296 return 0;
5297 case Builtin::BI__builtin_abs:
5298 case Builtin::BI__builtin_labs:
5299 case Builtin::BI__builtin_llabs:
5300 case Builtin::BI__builtin_fabsf:
5301 case Builtin::BI__builtin_fabs:
5302 case Builtin::BI__builtin_fabsl:
5303 return Builtin::BI__builtin_cabsf;
5304 case Builtin::BIabs:
5305 case Builtin::BIlabs:
5306 case Builtin::BIllabs:
5307 case Builtin::BIfabsf:
5308 case Builtin::BIfabs:
5309 case Builtin::BIfabsl:
5310 return Builtin::BIcabsf;
5311 }
5312 }
5313 llvm_unreachable("Unable to convert function");
5314}
5315
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005316static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005317 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5318 if (!FnInfo)
5319 return 0;
5320
5321 switch (FDecl->getBuiltinID()) {
5322 default:
5323 return 0;
5324 case Builtin::BI__builtin_abs:
5325 case Builtin::BI__builtin_fabs:
5326 case Builtin::BI__builtin_fabsf:
5327 case Builtin::BI__builtin_fabsl:
5328 case Builtin::BI__builtin_labs:
5329 case Builtin::BI__builtin_llabs:
5330 case Builtin::BI__builtin_cabs:
5331 case Builtin::BI__builtin_cabsf:
5332 case Builtin::BI__builtin_cabsl:
5333 case Builtin::BIabs:
5334 case Builtin::BIlabs:
5335 case Builtin::BIllabs:
5336 case Builtin::BIfabs:
5337 case Builtin::BIfabsf:
5338 case Builtin::BIfabsl:
5339 case Builtin::BIcabs:
5340 case Builtin::BIcabsf:
5341 case Builtin::BIcabsl:
5342 return FDecl->getBuiltinID();
5343 }
5344 llvm_unreachable("Unknown Builtin type");
5345}
5346
5347// If the replacement is valid, emit a note with replacement function.
5348// Additionally, suggest including the proper header if not already included.
5349static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005350 unsigned AbsKind, QualType ArgType) {
5351 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005352 const char *HeaderName = nullptr;
5353 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005354 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5355 FunctionName = "std::abs";
5356 if (ArgType->isIntegralOrEnumerationType()) {
5357 HeaderName = "cstdlib";
5358 } else if (ArgType->isRealFloatingType()) {
5359 HeaderName = "cmath";
5360 } else {
5361 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005362 }
Richard Trieubeffb832014-04-15 23:47:53 +00005363
5364 // Lookup all std::abs
5365 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005366 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005367 R.suppressDiagnostics();
5368 S.LookupQualifiedName(R, Std);
5369
5370 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005371 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005372 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5373 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5374 } else {
5375 FDecl = dyn_cast<FunctionDecl>(I);
5376 }
5377 if (!FDecl)
5378 continue;
5379
5380 // Found std::abs(), check that they are the right ones.
5381 if (FDecl->getNumParams() != 1)
5382 continue;
5383
5384 // Check that the parameter type can handle the argument.
5385 QualType ParamType = FDecl->getParamDecl(0)->getType();
5386 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5387 S.Context.getTypeSize(ArgType) <=
5388 S.Context.getTypeSize(ParamType)) {
5389 // Found a function, don't need the header hint.
5390 EmitHeaderHint = false;
5391 break;
5392 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005393 }
Richard Trieubeffb832014-04-15 23:47:53 +00005394 }
5395 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005396 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005397 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5398
5399 if (HeaderName) {
5400 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5401 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5402 R.suppressDiagnostics();
5403 S.LookupName(R, S.getCurScope());
5404
5405 if (R.isSingleResult()) {
5406 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5407 if (FD && FD->getBuiltinID() == AbsKind) {
5408 EmitHeaderHint = false;
5409 } else {
5410 return;
5411 }
5412 } else if (!R.empty()) {
5413 return;
5414 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005415 }
5416 }
5417
5418 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005419 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005420
Richard Trieubeffb832014-04-15 23:47:53 +00005421 if (!HeaderName)
5422 return;
5423
5424 if (!EmitHeaderHint)
5425 return;
5426
Alp Toker5d96e0a2014-07-11 20:53:51 +00005427 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5428 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005429}
5430
5431static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5432 if (!FDecl)
5433 return false;
5434
5435 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5436 return false;
5437
5438 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5439
5440 while (ND && ND->isInlineNamespace()) {
5441 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005442 }
Richard Trieubeffb832014-04-15 23:47:53 +00005443
5444 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5445 return false;
5446
5447 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5448 return false;
5449
5450 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005451}
5452
5453// Warn when using the wrong abs() function.
5454void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5455 const FunctionDecl *FDecl,
5456 IdentifierInfo *FnInfo) {
5457 if (Call->getNumArgs() != 1)
5458 return;
5459
5460 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005461 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5462 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005463 return;
5464
5465 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5466 QualType ParamType = Call->getArg(0)->getType();
5467
Alp Toker5d96e0a2014-07-11 20:53:51 +00005468 // Unsigned types cannot be negative. Suggest removing the absolute value
5469 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005470 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005471 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005472 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005473 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5474 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005475 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005476 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5477 return;
5478 }
5479
David Majnemer7f77eb92015-11-15 03:04:34 +00005480 // Taking the absolute value of a pointer is very suspicious, they probably
5481 // wanted to index into an array, dereference a pointer, call a function, etc.
5482 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5483 unsigned DiagType = 0;
5484 if (ArgType->isFunctionType())
5485 DiagType = 1;
5486 else if (ArgType->isArrayType())
5487 DiagType = 2;
5488
5489 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5490 return;
5491 }
5492
Richard Trieubeffb832014-04-15 23:47:53 +00005493 // std::abs has overloads which prevent most of the absolute value problems
5494 // from occurring.
5495 if (IsStdAbs)
5496 return;
5497
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005498 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5499 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5500
5501 // The argument and parameter are the same kind. Check if they are the right
5502 // size.
5503 if (ArgValueKind == ParamValueKind) {
5504 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5505 return;
5506
5507 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5508 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5509 << FDecl << ArgType << ParamType;
5510
5511 if (NewAbsKind == 0)
5512 return;
5513
5514 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005515 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005516 return;
5517 }
5518
5519 // ArgValueKind != ParamValueKind
5520 // The wrong type of absolute value function was used. Attempt to find the
5521 // proper one.
5522 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5523 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5524 if (NewAbsKind == 0)
5525 return;
5526
5527 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5528 << FDecl << ParamValueKind << ArgValueKind;
5529
5530 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005531 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005532}
5533
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005534//===--- CHECK: Standard memory functions ---------------------------------===//
5535
Nico Weber0e6daef2013-12-26 23:38:39 +00005536/// \brief Takes the expression passed to the size_t parameter of functions
5537/// such as memcmp, strncat, etc and warns if it's a comparison.
5538///
5539/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5540static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5541 IdentifierInfo *FnName,
5542 SourceLocation FnLoc,
5543 SourceLocation RParenLoc) {
5544 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5545 if (!Size)
5546 return false;
5547
5548 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5549 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5550 return false;
5551
Nico Weber0e6daef2013-12-26 23:38:39 +00005552 SourceRange SizeRange = Size->getSourceRange();
5553 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5554 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005555 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005556 << FnName << FixItHint::CreateInsertion(
5557 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005558 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005559 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005560 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005561 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5562 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005563
5564 return true;
5565}
5566
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005567/// \brief Determine whether the given type is or contains a dynamic class type
5568/// (e.g., whether it has a vtable).
5569static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5570 bool &IsContained) {
5571 // Look through array types while ignoring qualifiers.
5572 const Type *Ty = T->getBaseElementTypeUnsafe();
5573 IsContained = false;
5574
5575 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5576 RD = RD ? RD->getDefinition() : nullptr;
5577 if (!RD)
5578 return nullptr;
5579
5580 if (RD->isDynamicClass())
5581 return RD;
5582
5583 // Check all the fields. If any bases were dynamic, the class is dynamic.
5584 // It's impossible for a class to transitively contain itself by value, so
5585 // infinite recursion is impossible.
5586 for (auto *FD : RD->fields()) {
5587 bool SubContained;
5588 if (const CXXRecordDecl *ContainedRD =
5589 getContainedDynamicClass(FD->getType(), SubContained)) {
5590 IsContained = true;
5591 return ContainedRD;
5592 }
5593 }
5594
5595 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005596}
5597
Chandler Carruth889ed862011-06-21 23:04:20 +00005598/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005599/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005600static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005601 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005602 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5603 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5604 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005605
Craig Topperc3ec1492014-05-26 06:22:03 +00005606 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005607}
5608
Chandler Carruth889ed862011-06-21 23:04:20 +00005609/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005610static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005611 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5612 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5613 if (SizeOf->getKind() == clang::UETT_SizeOf)
5614 return SizeOf->getTypeOfArgument();
5615
5616 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005617}
5618
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005619/// \brief Check for dangerous or invalid arguments to memset().
5620///
Chandler Carruthac687262011-06-03 06:23:57 +00005621/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005622/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5623/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005624///
5625/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005626void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005627 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005628 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005629 assert(BId != 0);
5630
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005631 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005632 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005633 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005634 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005635 return;
5636
Anna Zaks22122702012-01-17 00:37:07 +00005637 unsigned LastArg = (BId == Builtin::BImemset ||
5638 BId == Builtin::BIstrndup ? 1 : 2);
5639 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005640 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005641
Nico Weber0e6daef2013-12-26 23:38:39 +00005642 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5643 Call->getLocStart(), Call->getRParenLoc()))
5644 return;
5645
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005646 // We have special checking when the length is a sizeof expression.
5647 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5648 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5649 llvm::FoldingSetNodeID SizeOfArgID;
5650
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005651 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5652 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005653 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005654
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005655 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005656 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005657 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005658 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005659
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005660 // Never warn about void type pointers. This can be used to suppress
5661 // false positives.
5662 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005663 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005664
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005665 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5666 // actually comparing the expressions for equality. Because computing the
5667 // expression IDs can be expensive, we only do this if the diagnostic is
5668 // enabled.
5669 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005670 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5671 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005672 // We only compute IDs for expressions if the warning is enabled, and
5673 // cache the sizeof arg's ID.
5674 if (SizeOfArgID == llvm::FoldingSetNodeID())
5675 SizeOfArg->Profile(SizeOfArgID, Context, true);
5676 llvm::FoldingSetNodeID DestID;
5677 Dest->Profile(DestID, Context, true);
5678 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005679 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5680 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005681 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005682 StringRef ReadableName = FnName->getName();
5683
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005684 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005685 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005686 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005687 if (!PointeeTy->isIncompleteType() &&
5688 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005689 ActionIdx = 2; // If the pointee's size is sizeof(char),
5690 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005691
5692 // If the function is defined as a builtin macro, do not show macro
5693 // expansion.
5694 SourceLocation SL = SizeOfArg->getExprLoc();
5695 SourceRange DSR = Dest->getSourceRange();
5696 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005697 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005698
5699 if (SM.isMacroArgExpansion(SL)) {
5700 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5701 SL = SM.getSpellingLoc(SL);
5702 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5703 SM.getSpellingLoc(DSR.getEnd()));
5704 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5705 SM.getSpellingLoc(SSR.getEnd()));
5706 }
5707
Anna Zaksd08d9152012-05-30 23:14:52 +00005708 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005709 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005710 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005711 << PointeeTy
5712 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005713 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005714 << SSR);
5715 DiagRuntimeBehavior(SL, SizeOfArg,
5716 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5717 << ActionIdx
5718 << SSR);
5719
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005720 break;
5721 }
5722 }
5723
5724 // Also check for cases where the sizeof argument is the exact same
5725 // type as the memory argument, and where it points to a user-defined
5726 // record type.
5727 if (SizeOfArgTy != QualType()) {
5728 if (PointeeTy->isRecordType() &&
5729 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5730 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5731 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5732 << FnName << SizeOfArgTy << ArgIdx
5733 << PointeeTy << Dest->getSourceRange()
5734 << LenExpr->getSourceRange());
5735 break;
5736 }
Nico Weberc5e73862011-06-14 16:14:58 +00005737 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005738 } else if (DestTy->isArrayType()) {
5739 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005740 }
Nico Weberc5e73862011-06-14 16:14:58 +00005741
Nico Weberc44b35e2015-03-21 17:37:46 +00005742 if (PointeeTy == QualType())
5743 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005744
Nico Weberc44b35e2015-03-21 17:37:46 +00005745 // Always complain about dynamic classes.
5746 bool IsContained;
5747 if (const CXXRecordDecl *ContainedRD =
5748 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005749
Nico Weberc44b35e2015-03-21 17:37:46 +00005750 unsigned OperationType = 0;
5751 // "overwritten" if we're warning about the destination for any call
5752 // but memcmp; otherwise a verb appropriate to the call.
5753 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5754 if (BId == Builtin::BImemcpy)
5755 OperationType = 1;
5756 else if(BId == Builtin::BImemmove)
5757 OperationType = 2;
5758 else if (BId == Builtin::BImemcmp)
5759 OperationType = 3;
5760 }
5761
John McCall31168b02011-06-15 23:02:42 +00005762 DiagRuntimeBehavior(
5763 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005764 PDiag(diag::warn_dyn_class_memaccess)
5765 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5766 << FnName << IsContained << ContainedRD << OperationType
5767 << Call->getCallee()->getSourceRange());
5768 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5769 BId != Builtin::BImemset)
5770 DiagRuntimeBehavior(
5771 Dest->getExprLoc(), Dest,
5772 PDiag(diag::warn_arc_object_memaccess)
5773 << ArgIdx << FnName << PointeeTy
5774 << Call->getCallee()->getSourceRange());
5775 else
5776 continue;
5777
5778 DiagRuntimeBehavior(
5779 Dest->getExprLoc(), Dest,
5780 PDiag(diag::note_bad_memaccess_silence)
5781 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5782 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005783 }
5784}
5785
Ted Kremenek6865f772011-08-18 20:55:45 +00005786// A little helper routine: ignore addition and subtraction of integer literals.
5787// This intentionally does not ignore all integer constant expressions because
5788// we don't want to remove sizeof().
5789static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5790 Ex = Ex->IgnoreParenCasts();
5791
5792 for (;;) {
5793 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5794 if (!BO || !BO->isAdditiveOp())
5795 break;
5796
5797 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5798 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5799
5800 if (isa<IntegerLiteral>(RHS))
5801 Ex = LHS;
5802 else if (isa<IntegerLiteral>(LHS))
5803 Ex = RHS;
5804 else
5805 break;
5806 }
5807
5808 return Ex;
5809}
5810
Anna Zaks13b08572012-08-08 21:42:23 +00005811static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5812 ASTContext &Context) {
5813 // Only handle constant-sized or VLAs, but not flexible members.
5814 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5815 // Only issue the FIXIT for arrays of size > 1.
5816 if (CAT->getSize().getSExtValue() <= 1)
5817 return false;
5818 } else if (!Ty->isVariableArrayType()) {
5819 return false;
5820 }
5821 return true;
5822}
5823
Ted Kremenek6865f772011-08-18 20:55:45 +00005824// Warn if the user has made the 'size' argument to strlcpy or strlcat
5825// be the size of the source, instead of the destination.
5826void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5827 IdentifierInfo *FnName) {
5828
5829 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005830 unsigned NumArgs = Call->getNumArgs();
5831 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005832 return;
5833
5834 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5835 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005836 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005837
5838 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5839 Call->getLocStart(), Call->getRParenLoc()))
5840 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005841
5842 // Look for 'strlcpy(dst, x, sizeof(x))'
5843 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5844 CompareWithSrc = Ex;
5845 else {
5846 // Look for 'strlcpy(dst, x, strlen(x))'
5847 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005848 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5849 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005850 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5851 }
5852 }
5853
5854 if (!CompareWithSrc)
5855 return;
5856
5857 // Determine if the argument to sizeof/strlen is equal to the source
5858 // argument. In principle there's all kinds of things you could do
5859 // here, for instance creating an == expression and evaluating it with
5860 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5861 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5862 if (!SrcArgDRE)
5863 return;
5864
5865 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5866 if (!CompareWithSrcDRE ||
5867 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5868 return;
5869
5870 const Expr *OriginalSizeArg = Call->getArg(2);
5871 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5872 << OriginalSizeArg->getSourceRange() << FnName;
5873
5874 // Output a FIXIT hint if the destination is an array (rather than a
5875 // pointer to an array). This could be enhanced to handle some
5876 // pointers if we know the actual size, like if DstArg is 'array+2'
5877 // we could say 'sizeof(array)-2'.
5878 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005879 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005880 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005881
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005882 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005883 llvm::raw_svector_ostream OS(sizeString);
5884 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005885 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005886 OS << ")";
5887
5888 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5889 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5890 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005891}
5892
Anna Zaks314cd092012-02-01 19:08:57 +00005893/// Check if two expressions refer to the same declaration.
5894static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5895 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5896 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5897 return D1->getDecl() == D2->getDecl();
5898 return false;
5899}
5900
5901static const Expr *getStrlenExprArg(const Expr *E) {
5902 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5903 const FunctionDecl *FD = CE->getDirectCallee();
5904 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005905 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005906 return CE->getArg(0)->IgnoreParenCasts();
5907 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005908 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005909}
5910
5911// Warn on anti-patterns as the 'size' argument to strncat.
5912// The correct size argument should look like following:
5913// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5914void Sema::CheckStrncatArguments(const CallExpr *CE,
5915 IdentifierInfo *FnName) {
5916 // Don't crash if the user has the wrong number of arguments.
5917 if (CE->getNumArgs() < 3)
5918 return;
5919 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5920 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5921 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5922
Nico Weber0e6daef2013-12-26 23:38:39 +00005923 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5924 CE->getRParenLoc()))
5925 return;
5926
Anna Zaks314cd092012-02-01 19:08:57 +00005927 // Identify common expressions, which are wrongly used as the size argument
5928 // to strncat and may lead to buffer overflows.
5929 unsigned PatternType = 0;
5930 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5931 // - sizeof(dst)
5932 if (referToTheSameDecl(SizeOfArg, DstArg))
5933 PatternType = 1;
5934 // - sizeof(src)
5935 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5936 PatternType = 2;
5937 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5938 if (BE->getOpcode() == BO_Sub) {
5939 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5940 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5941 // - sizeof(dst) - strlen(dst)
5942 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5943 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5944 PatternType = 1;
5945 // - sizeof(src) - (anything)
5946 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5947 PatternType = 2;
5948 }
5949 }
5950
5951 if (PatternType == 0)
5952 return;
5953
Anna Zaks5069aa32012-02-03 01:27:37 +00005954 // Generate the diagnostic.
5955 SourceLocation SL = LenArg->getLocStart();
5956 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005957 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005958
5959 // If the function is defined as a builtin macro, do not show macro expansion.
5960 if (SM.isMacroArgExpansion(SL)) {
5961 SL = SM.getSpellingLoc(SL);
5962 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5963 SM.getSpellingLoc(SR.getEnd()));
5964 }
5965
Anna Zaks13b08572012-08-08 21:42:23 +00005966 // Check if the destination is an array (rather than a pointer to an array).
5967 QualType DstTy = DstArg->getType();
5968 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5969 Context);
5970 if (!isKnownSizeArray) {
5971 if (PatternType == 1)
5972 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5973 else
5974 Diag(SL, diag::warn_strncat_src_size) << SR;
5975 return;
5976 }
5977
Anna Zaks314cd092012-02-01 19:08:57 +00005978 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005979 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005980 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005981 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005982
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005983 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005984 llvm::raw_svector_ostream OS(sizeString);
5985 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005986 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005987 OS << ") - ";
5988 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005989 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005990 OS << ") - 1";
5991
Anna Zaks5069aa32012-02-03 01:27:37 +00005992 Diag(SL, diag::note_strncat_wrong_size)
5993 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005994}
5995
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005996//===--- CHECK: Return Address of Stack Variable --------------------------===//
5997
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005998static const Expr *EvalVal(const Expr *E,
5999 SmallVectorImpl<const DeclRefExpr *> &refVars,
6000 const Decl *ParentDecl);
6001static const Expr *EvalAddr(const Expr *E,
6002 SmallVectorImpl<const DeclRefExpr *> &refVars,
6003 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006004
6005/// CheckReturnStackAddr - Check if a return statement returns the address
6006/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006007static void
6008CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6009 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006010
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006011 const Expr *stackE = nullptr;
6012 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006013
6014 // Perform checking for returned stack addresses, local blocks,
6015 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006016 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006017 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006018 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006019 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006020 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006021 }
6022
Craig Topperc3ec1492014-05-26 06:22:03 +00006023 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006024 return; // Nothing suspicious was found.
6025
6026 SourceLocation diagLoc;
6027 SourceRange diagRange;
6028 if (refVars.empty()) {
6029 diagLoc = stackE->getLocStart();
6030 diagRange = stackE->getSourceRange();
6031 } else {
6032 // We followed through a reference variable. 'stackE' contains the
6033 // problematic expression but we will warn at the return statement pointing
6034 // at the reference variable. We will later display the "trail" of
6035 // reference variables using notes.
6036 diagLoc = refVars[0]->getLocStart();
6037 diagRange = refVars[0]->getSourceRange();
6038 }
6039
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006040 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6041 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006042 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006043 << DR->getDecl()->getDeclName() << diagRange;
6044 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006045 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006046 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006047 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006048 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00006049 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6050 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006051 }
6052
6053 // Display the "trail" of reference variables that we followed until we
6054 // found the problematic expression using notes.
6055 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006056 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006057 // If this var binds to another reference var, show the range of the next
6058 // var, otherwise the var binds to the problematic expression, in which case
6059 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006060 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6061 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006062 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6063 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006064 }
6065}
6066
6067/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6068/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006069/// to a location on the stack, a local block, an address of a label, or a
6070/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006071/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006072/// encounter a subexpression that (1) clearly does not lead to one of the
6073/// above problematic expressions (2) is something we cannot determine leads to
6074/// a problematic expression based on such local checking.
6075///
6076/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6077/// the expression that they point to. Such variables are added to the
6078/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006079///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006080/// EvalAddr processes expressions that are pointers that are used as
6081/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006082/// At the base case of the recursion is a check for the above problematic
6083/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006084///
6085/// This implementation handles:
6086///
6087/// * pointer-to-pointer casts
6088/// * implicit conversions from array references to pointers
6089/// * taking the address of fields
6090/// * arbitrary interplay between "&" and "*" operators
6091/// * pointer arithmetic from an address of a stack variable
6092/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006093static const Expr *EvalAddr(const Expr *E,
6094 SmallVectorImpl<const DeclRefExpr *> &refVars,
6095 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006096 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006097 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006098
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006099 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006100 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006101 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006102 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006103 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006104
Peter Collingbourne91147592011-04-15 00:35:48 +00006105 E = E->IgnoreParens();
6106
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006107 // Our "symbolic interpreter" is just a dispatch off the currently
6108 // viewed AST node. We then recursively traverse the AST by calling
6109 // EvalAddr and EvalVal appropriately.
6110 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006111 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006112 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006113
Richard Smith40f08eb2014-01-30 22:05:38 +00006114 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006115 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006116 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006117
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006118 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006119 // If this is a reference variable, follow through to the expression that
6120 // it points to.
6121 if (V->hasLocalStorage() &&
6122 V->getType()->isReferenceType() && V->hasInit()) {
6123 // Add the reference variable to the "trail".
6124 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006125 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006126 }
6127
Craig Topperc3ec1492014-05-26 06:22:03 +00006128 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006129 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006130
Chris Lattner934edb22007-12-28 05:31:15 +00006131 case Stmt::UnaryOperatorClass: {
6132 // The only unary operator that make sense to handle here
6133 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006134 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006135
John McCalle3027922010-08-25 11:45:40 +00006136 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006137 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006138 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006139 }
Mike Stump11289f42009-09-09 15:08:12 +00006140
Chris Lattner934edb22007-12-28 05:31:15 +00006141 case Stmt::BinaryOperatorClass: {
6142 // Handle pointer arithmetic. All other binary operators are not valid
6143 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006144 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006145 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006146
John McCalle3027922010-08-25 11:45:40 +00006147 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006148 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006149
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006150 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006151
6152 // Determine which argument is the real pointer base. It could be
6153 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006154 if (!Base->getType()->isPointerType())
6155 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006156
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006157 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006158 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006159 }
Steve Naroff2752a172008-09-10 19:17:48 +00006160
Chris Lattner934edb22007-12-28 05:31:15 +00006161 // For conditional operators we need to see if either the LHS or RHS are
6162 // valid DeclRefExpr*s. If one of them is valid, we return it.
6163 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006164 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006165
Chris Lattner934edb22007-12-28 05:31:15 +00006166 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006167 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006168 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006169 // In C++, we can have a throw-expression, which has 'void' type.
6170 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006171 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006172 return LHS;
6173 }
Chris Lattner934edb22007-12-28 05:31:15 +00006174
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006175 // In C++, we can have a throw-expression, which has 'void' type.
6176 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006177 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006178
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006179 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006180 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006181
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006182 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006183 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006184 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006185 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006186
6187 case Stmt::AddrLabelExprClass:
6188 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006189
John McCall28fc7092011-11-10 05:35:25 +00006190 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006191 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6192 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006193
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006194 // For casts, we need to handle conversions from arrays to
6195 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006196 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006197 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006198 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006199 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006200 case Stmt::CXXStaticCastExprClass:
6201 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006202 case Stmt::CXXConstCastExprClass:
6203 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006204 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006205 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006206 case CK_LValueToRValue:
6207 case CK_NoOp:
6208 case CK_BaseToDerived:
6209 case CK_DerivedToBase:
6210 case CK_UncheckedDerivedToBase:
6211 case CK_Dynamic:
6212 case CK_CPointerToObjCPointerCast:
6213 case CK_BlockPointerToObjCPointerCast:
6214 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006215 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006216
6217 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006218 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006219
Richard Trieudadefde2014-07-02 04:39:38 +00006220 case CK_BitCast:
6221 if (SubExpr->getType()->isAnyPointerType() ||
6222 SubExpr->getType()->isBlockPointerType() ||
6223 SubExpr->getType()->isObjCQualifiedIdType())
6224 return EvalAddr(SubExpr, refVars, ParentDecl);
6225 else
6226 return nullptr;
6227
Eli Friedman8195ad72012-02-23 23:04:32 +00006228 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006229 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006230 }
Chris Lattner934edb22007-12-28 05:31:15 +00006231 }
Mike Stump11289f42009-09-09 15:08:12 +00006232
Douglas Gregorfe314812011-06-21 17:03:29 +00006233 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006234 if (const Expr *Result =
6235 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6236 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006237 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006238 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006239
Chris Lattner934edb22007-12-28 05:31:15 +00006240 // Everything else: we simply don't reason about them.
6241 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006242 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006243 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006244}
Mike Stump11289f42009-09-09 15:08:12 +00006245
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006246/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6247/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006248static const Expr *EvalVal(const Expr *E,
6249 SmallVectorImpl<const DeclRefExpr *> &refVars,
6250 const Decl *ParentDecl) {
6251 do {
6252 // We should only be called for evaluating non-pointer expressions, or
6253 // expressions with a pointer type that are not used as references but
6254 // instead
6255 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006256
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006257 // Our "symbolic interpreter" is just a dispatch off the currently
6258 // viewed AST node. We then recursively traverse the AST by calling
6259 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006260
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006261 E = E->IgnoreParens();
6262 switch (E->getStmtClass()) {
6263 case Stmt::ImplicitCastExprClass: {
6264 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6265 if (IE->getValueKind() == VK_LValue) {
6266 E = IE->getSubExpr();
6267 continue;
6268 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006269 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006270 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006271
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006272 case Stmt::ExprWithCleanupsClass:
6273 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6274 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006275
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006276 case Stmt::DeclRefExprClass: {
6277 // When we hit a DeclRefExpr we are looking at code that refers to a
6278 // variable's name. If it's not a reference variable we check if it has
6279 // local storage within the function, and if so, return the expression.
6280 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6281
6282 // If we leave the immediate function, the lifetime isn't about to end.
6283 if (DR->refersToEnclosingVariableOrCapture())
6284 return nullptr;
6285
6286 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6287 // Check if it refers to itself, e.g. "int& i = i;".
6288 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006289 return DR;
6290
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006291 if (V->hasLocalStorage()) {
6292 if (!V->getType()->isReferenceType())
6293 return DR;
6294
6295 // Reference variable, follow through to the expression that
6296 // it points to.
6297 if (V->hasInit()) {
6298 // Add the reference variable to the "trail".
6299 refVars.push_back(DR);
6300 return EvalVal(V->getInit(), refVars, V);
6301 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006302 }
6303 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006304
6305 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006306 }
Mike Stump11289f42009-09-09 15:08:12 +00006307
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006308 case Stmt::UnaryOperatorClass: {
6309 // The only unary operator that make sense to handle here
6310 // is Deref. All others don't resolve to a "name." This includes
6311 // handling all sorts of rvalues passed to a unary operator.
6312 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006313
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006314 if (U->getOpcode() == UO_Deref)
6315 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006316
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006317 return nullptr;
6318 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006319
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006320 case Stmt::ArraySubscriptExprClass: {
6321 // Array subscripts are potential references to data on the stack. We
6322 // retrieve the DeclRefExpr* for the array variable if it indeed
6323 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006324 const auto *ASE = cast<ArraySubscriptExpr>(E);
6325 if (ASE->isTypeDependent())
6326 return nullptr;
6327 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006328 }
Mike Stump11289f42009-09-09 15:08:12 +00006329
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006330 case Stmt::OMPArraySectionExprClass: {
6331 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6332 ParentDecl);
6333 }
Mike Stump11289f42009-09-09 15:08:12 +00006334
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006335 case Stmt::ConditionalOperatorClass: {
6336 // For conditional operators we need to see if either the LHS or RHS are
6337 // non-NULL Expr's. If one is non-NULL, we return it.
6338 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006339
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006340 // Handle the GNU extension for missing LHS.
6341 if (const Expr *LHSExpr = C->getLHS()) {
6342 // In C++, we can have a throw-expression, which has 'void' type.
6343 if (!LHSExpr->getType()->isVoidType())
6344 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6345 return LHS;
6346 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006347
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006348 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006349 if (C->getRHS()->getType()->isVoidType())
6350 return nullptr;
6351
6352 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006353 }
6354
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006355 // Accesses to members are potential references to data on the stack.
6356 case Stmt::MemberExprClass: {
6357 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006358
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006359 // Check for indirect access. We only want direct field accesses.
6360 if (M->isArrow())
6361 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006362
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006363 // Check whether the member type is itself a reference, in which case
6364 // we're not going to refer to the member, but to what the member refers
6365 // to.
6366 if (M->getMemberDecl()->getType()->isReferenceType())
6367 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006368
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006369 return EvalVal(M->getBase(), refVars, ParentDecl);
6370 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006371
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006372 case Stmt::MaterializeTemporaryExprClass:
6373 if (const Expr *Result =
6374 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6375 refVars, ParentDecl))
6376 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006377 return E;
6378
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006379 default:
6380 // Check that we don't return or take the address of a reference to a
6381 // temporary. This is only useful in C++.
6382 if (!E->isTypeDependent() && E->isRValue())
6383 return E;
6384
6385 // Everything else: we simply don't reason about them.
6386 return nullptr;
6387 }
6388 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006389}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006390
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006391void
6392Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6393 SourceLocation ReturnLoc,
6394 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006395 const AttrVec *Attrs,
6396 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006397 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6398
6399 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006400 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6401 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006402 CheckNonNullExpr(*this, RetValExp))
6403 Diag(ReturnLoc, diag::warn_null_ret)
6404 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006405
6406 // C++11 [basic.stc.dynamic.allocation]p4:
6407 // If an allocation function declared with a non-throwing
6408 // exception-specification fails to allocate storage, it shall return
6409 // a null pointer. Any other allocation function that fails to allocate
6410 // storage shall indicate failure only by throwing an exception [...]
6411 if (FD) {
6412 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6413 if (Op == OO_New || Op == OO_Array_New) {
6414 const FunctionProtoType *Proto
6415 = FD->getType()->castAs<FunctionProtoType>();
6416 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6417 CheckNonNullExpr(*this, RetValExp))
6418 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6419 << FD << getLangOpts().CPlusPlus11;
6420 }
6421 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006422}
6423
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006424//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6425
6426/// Check for comparisons of floating point operands using != and ==.
6427/// Issue a warning if these are no self-comparisons, as they are not likely
6428/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006429void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006430 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6431 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006432
6433 // Special case: check for x == x (which is OK).
6434 // Do not emit warnings for such cases.
6435 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6436 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6437 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006438 return;
Mike Stump11289f42009-09-09 15:08:12 +00006439
Ted Kremenekeda40e22007-11-29 00:59:04 +00006440 // Special case: check for comparisons against literals that can be exactly
6441 // represented by APFloat. In such cases, do not emit a warning. This
6442 // is a heuristic: often comparison against such literals are used to
6443 // detect if a value in a variable has not changed. This clearly can
6444 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006445 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6446 if (FLL->isExact())
6447 return;
6448 } else
6449 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6450 if (FLR->isExact())
6451 return;
Mike Stump11289f42009-09-09 15:08:12 +00006452
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006453 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006454 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006455 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006456 return;
Mike Stump11289f42009-09-09 15:08:12 +00006457
David Blaikie1f4ff152012-07-16 20:47:22 +00006458 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006459 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006460 return;
Mike Stump11289f42009-09-09 15:08:12 +00006461
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006462 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006463 Diag(Loc, diag::warn_floatingpoint_eq)
6464 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006465}
John McCallca01b222010-01-04 23:21:16 +00006466
John McCall70aa5392010-01-06 05:24:50 +00006467//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6468//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006469
John McCall70aa5392010-01-06 05:24:50 +00006470namespace {
John McCallca01b222010-01-04 23:21:16 +00006471
John McCall70aa5392010-01-06 05:24:50 +00006472/// Structure recording the 'active' range of an integer-valued
6473/// expression.
6474struct IntRange {
6475 /// The number of bits active in the int.
6476 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006477
John McCall70aa5392010-01-06 05:24:50 +00006478 /// True if the int is known not to have negative values.
6479 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006480
John McCall70aa5392010-01-06 05:24:50 +00006481 IntRange(unsigned Width, bool NonNegative)
6482 : Width(Width), NonNegative(NonNegative)
6483 {}
John McCallca01b222010-01-04 23:21:16 +00006484
John McCall817d4af2010-11-10 23:38:19 +00006485 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006486 static IntRange forBoolType() {
6487 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006488 }
6489
John McCall817d4af2010-11-10 23:38:19 +00006490 /// Returns the range of an opaque value of the given integral type.
6491 static IntRange forValueOfType(ASTContext &C, QualType T) {
6492 return forValueOfCanonicalType(C,
6493 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006494 }
6495
John McCall817d4af2010-11-10 23:38:19 +00006496 /// Returns the range of an opaque value of a canonical integral type.
6497 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006498 assert(T->isCanonicalUnqualified());
6499
6500 if (const VectorType *VT = dyn_cast<VectorType>(T))
6501 T = VT->getElementType().getTypePtr();
6502 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6503 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006504 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6505 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006506
David Majnemer6a426652013-06-07 22:07:20 +00006507 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006508 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006509 EnumDecl *Enum = ET->getDecl();
6510 if (!Enum->isCompleteDefinition())
6511 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006512
David Majnemer6a426652013-06-07 22:07:20 +00006513 unsigned NumPositive = Enum->getNumPositiveBits();
6514 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006515
David Majnemer6a426652013-06-07 22:07:20 +00006516 if (NumNegative == 0)
6517 return IntRange(NumPositive, true/*NonNegative*/);
6518 else
6519 return IntRange(std::max(NumPositive + 1, NumNegative),
6520 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006521 }
John McCall70aa5392010-01-06 05:24:50 +00006522
6523 const BuiltinType *BT = cast<BuiltinType>(T);
6524 assert(BT->isInteger());
6525
6526 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6527 }
6528
John McCall817d4af2010-11-10 23:38:19 +00006529 /// Returns the "target" range of a canonical integral type, i.e.
6530 /// the range of values expressible in the type.
6531 ///
6532 /// This matches forValueOfCanonicalType except that enums have the
6533 /// full range of their type, not the range of their enumerators.
6534 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6535 assert(T->isCanonicalUnqualified());
6536
6537 if (const VectorType *VT = dyn_cast<VectorType>(T))
6538 T = VT->getElementType().getTypePtr();
6539 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6540 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006541 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6542 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006543 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006544 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006545
6546 const BuiltinType *BT = cast<BuiltinType>(T);
6547 assert(BT->isInteger());
6548
6549 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6550 }
6551
6552 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006553 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006554 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006555 L.NonNegative && R.NonNegative);
6556 }
6557
John McCall817d4af2010-11-10 23:38:19 +00006558 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006559 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006560 return IntRange(std::min(L.Width, R.Width),
6561 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006562 }
6563};
6564
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006565IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006566 if (value.isSigned() && value.isNegative())
6567 return IntRange(value.getMinSignedBits(), false);
6568
6569 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006570 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006571
6572 // isNonNegative() just checks the sign bit without considering
6573 // signedness.
6574 return IntRange(value.getActiveBits(), true);
6575}
6576
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006577IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6578 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006579 if (result.isInt())
6580 return GetValueRange(C, result.getInt(), MaxWidth);
6581
6582 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006583 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6584 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6585 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6586 R = IntRange::join(R, El);
6587 }
John McCall70aa5392010-01-06 05:24:50 +00006588 return R;
6589 }
6590
6591 if (result.isComplexInt()) {
6592 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6593 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6594 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006595 }
6596
6597 // This can happen with lossless casts to intptr_t of "based" lvalues.
6598 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006599 // FIXME: The only reason we need to pass the type in here is to get
6600 // the sign right on this one case. It would be nice if APValue
6601 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006602 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006603 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006604}
John McCall70aa5392010-01-06 05:24:50 +00006605
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006606QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006607 QualType Ty = E->getType();
6608 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6609 Ty = AtomicRHS->getValueType();
6610 return Ty;
6611}
6612
John McCall70aa5392010-01-06 05:24:50 +00006613/// Pseudo-evaluate the given integer expression, estimating the
6614/// range of values it might take.
6615///
6616/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006617IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006618 E = E->IgnoreParens();
6619
6620 // Try a full evaluation first.
6621 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006622 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006623 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006624
6625 // I think we only want to look through implicit casts here; if the
6626 // user has an explicit widening cast, we should treat the value as
6627 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006628 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006629 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006630 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6631
Eli Friedmane6d33952013-07-08 20:20:06 +00006632 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006633
George Burgess IVdf1ed002016-01-13 01:52:39 +00006634 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6635 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00006636
John McCall70aa5392010-01-06 05:24:50 +00006637 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006638 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006639 return OutputTypeRange;
6640
6641 IntRange SubRange
6642 = GetExprRange(C, CE->getSubExpr(),
6643 std::min(MaxWidth, OutputTypeRange.Width));
6644
6645 // Bail out if the subexpr's range is as wide as the cast type.
6646 if (SubRange.Width >= OutputTypeRange.Width)
6647 return OutputTypeRange;
6648
6649 // Otherwise, we take the smaller width, and we're non-negative if
6650 // either the output type or the subexpr is.
6651 return IntRange(SubRange.Width,
6652 SubRange.NonNegative || OutputTypeRange.NonNegative);
6653 }
6654
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006655 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006656 // If we can fold the condition, just take that operand.
6657 bool CondResult;
6658 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6659 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6660 : CO->getFalseExpr(),
6661 MaxWidth);
6662
6663 // Otherwise, conservatively merge.
6664 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6665 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6666 return IntRange::join(L, R);
6667 }
6668
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006669 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006670 switch (BO->getOpcode()) {
6671
6672 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006673 case BO_LAnd:
6674 case BO_LOr:
6675 case BO_LT:
6676 case BO_GT:
6677 case BO_LE:
6678 case BO_GE:
6679 case BO_EQ:
6680 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006681 return IntRange::forBoolType();
6682
John McCallc3688382011-07-13 06:35:24 +00006683 // The type of the assignments is the type of the LHS, so the RHS
6684 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006685 case BO_MulAssign:
6686 case BO_DivAssign:
6687 case BO_RemAssign:
6688 case BO_AddAssign:
6689 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006690 case BO_XorAssign:
6691 case BO_OrAssign:
6692 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006693 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006694
John McCallc3688382011-07-13 06:35:24 +00006695 // Simple assignments just pass through the RHS, which will have
6696 // been coerced to the LHS type.
6697 case BO_Assign:
6698 // TODO: bitfields?
6699 return GetExprRange(C, BO->getRHS(), MaxWidth);
6700
John McCall70aa5392010-01-06 05:24:50 +00006701 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006702 case BO_PtrMemD:
6703 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006704 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006705
John McCall2ce81ad2010-01-06 22:07:33 +00006706 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006707 case BO_And:
6708 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006709 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6710 GetExprRange(C, BO->getRHS(), MaxWidth));
6711
John McCall70aa5392010-01-06 05:24:50 +00006712 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006713 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006714 // ...except that we want to treat '1 << (blah)' as logically
6715 // positive. It's an important idiom.
6716 if (IntegerLiteral *I
6717 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6718 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006719 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006720 return IntRange(R.Width, /*NonNegative*/ true);
6721 }
6722 }
6723 // fallthrough
6724
John McCalle3027922010-08-25 11:45:40 +00006725 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006726 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006727
John McCall2ce81ad2010-01-06 22:07:33 +00006728 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006729 case BO_Shr:
6730 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006731 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6732
6733 // If the shift amount is a positive constant, drop the width by
6734 // that much.
6735 llvm::APSInt shift;
6736 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6737 shift.isNonNegative()) {
6738 unsigned zext = shift.getZExtValue();
6739 if (zext >= L.Width)
6740 L.Width = (L.NonNegative ? 0 : 1);
6741 else
6742 L.Width -= zext;
6743 }
6744
6745 return L;
6746 }
6747
6748 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006749 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006750 return GetExprRange(C, BO->getRHS(), MaxWidth);
6751
John McCall2ce81ad2010-01-06 22:07:33 +00006752 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006753 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006754 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006755 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006756 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006757
John McCall51431812011-07-14 22:39:48 +00006758 // The width of a division result is mostly determined by the size
6759 // of the LHS.
6760 case BO_Div: {
6761 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006762 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006763 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6764
6765 // If the divisor is constant, use that.
6766 llvm::APSInt divisor;
6767 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6768 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6769 if (log2 >= L.Width)
6770 L.Width = (L.NonNegative ? 0 : 1);
6771 else
6772 L.Width = std::min(L.Width - log2, MaxWidth);
6773 return L;
6774 }
6775
6776 // Otherwise, just use the LHS's width.
6777 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6778 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6779 }
6780
6781 // The result of a remainder can't be larger than the result of
6782 // either side.
6783 case BO_Rem: {
6784 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006785 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006786 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6787 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6788
6789 IntRange meet = IntRange::meet(L, R);
6790 meet.Width = std::min(meet.Width, MaxWidth);
6791 return meet;
6792 }
6793
6794 // The default behavior is okay for these.
6795 case BO_Mul:
6796 case BO_Add:
6797 case BO_Xor:
6798 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006799 break;
6800 }
6801
John McCall51431812011-07-14 22:39:48 +00006802 // The default case is to treat the operation as if it were closed
6803 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006804 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6805 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6806 return IntRange::join(L, R);
6807 }
6808
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006809 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006810 switch (UO->getOpcode()) {
6811 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006812 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006813 return IntRange::forBoolType();
6814
6815 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006816 case UO_Deref:
6817 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006818 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006819
6820 default:
6821 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6822 }
6823 }
6824
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006825 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006826 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6827
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006828 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006829 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006830 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006831
Eli Friedmane6d33952013-07-08 20:20:06 +00006832 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006833}
John McCall263a48b2010-01-04 23:31:57 +00006834
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006835IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006836 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006837}
6838
John McCall263a48b2010-01-04 23:31:57 +00006839/// Checks whether the given value, which currently has the given
6840/// source semantics, has the same value when coerced through the
6841/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006842bool IsSameFloatAfterCast(const llvm::APFloat &value,
6843 const llvm::fltSemantics &Src,
6844 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006845 llvm::APFloat truncated = value;
6846
6847 bool ignored;
6848 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6849 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6850
6851 return truncated.bitwiseIsEqual(value);
6852}
6853
6854/// Checks whether the given value, which currently has the given
6855/// source semantics, has the same value when coerced through the
6856/// target semantics.
6857///
6858/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006859bool IsSameFloatAfterCast(const APValue &value,
6860 const llvm::fltSemantics &Src,
6861 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006862 if (value.isFloat())
6863 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6864
6865 if (value.isVector()) {
6866 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6867 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6868 return false;
6869 return true;
6870 }
6871
6872 assert(value.isComplexFloat());
6873 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6874 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6875}
6876
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006877void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006878
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006879bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00006880 // Suppress cases where we are comparing against an enum constant.
6881 if (const DeclRefExpr *DR =
6882 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6883 if (isa<EnumConstantDecl>(DR->getDecl()))
6884 return false;
6885
6886 // Suppress cases where the '0' value is expanded from a macro.
6887 if (E->getLocStart().isMacroID())
6888 return false;
6889
John McCallcc7e5bf2010-05-06 08:58:33 +00006890 llvm::APSInt Value;
6891 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6892}
6893
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006894bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00006895 // Strip off implicit integral promotions.
6896 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006897 if (ICE->getCastKind() != CK_IntegralCast &&
6898 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006899 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006900 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006901 }
6902
6903 return E->getType()->isEnumeralType();
6904}
6905
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006906void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006907 // Disable warning in template instantiations.
6908 if (!S.ActiveTemplateInstantiations.empty())
6909 return;
6910
John McCalle3027922010-08-25 11:45:40 +00006911 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006912 if (E->isValueDependent())
6913 return;
6914
John McCalle3027922010-08-25 11:45:40 +00006915 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006916 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006917 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006918 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006919 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006920 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006921 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006922 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006923 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006924 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006925 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006926 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006927 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006928 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006929 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006930 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6931 }
6932}
6933
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006934void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
6935 Expr *Constant, Expr *Other,
6936 llvm::APSInt Value,
6937 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006938 // Disable warning in template instantiations.
6939 if (!S.ActiveTemplateInstantiations.empty())
6940 return;
6941
Richard Trieu0f097742014-04-04 04:13:47 +00006942 // TODO: Investigate using GetExprRange() to get tighter bounds
6943 // on the bit ranges.
6944 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006945 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006946 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006947 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6948 unsigned OtherWidth = OtherRange.Width;
6949
6950 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6951
Richard Trieu560910c2012-11-14 22:50:24 +00006952 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006953 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006954 return;
6955
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006956 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006957 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006958
Richard Trieu0f097742014-04-04 04:13:47 +00006959 // Used for diagnostic printout.
6960 enum {
6961 LiteralConstant = 0,
6962 CXXBoolLiteralTrue,
6963 CXXBoolLiteralFalse
6964 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006965
Richard Trieu0f097742014-04-04 04:13:47 +00006966 if (!OtherIsBooleanType) {
6967 QualType ConstantT = Constant->getType();
6968 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006969
Richard Trieu0f097742014-04-04 04:13:47 +00006970 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6971 return;
6972 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6973 "comparison with non-integer type");
6974
6975 bool ConstantSigned = ConstantT->isSignedIntegerType();
6976 bool CommonSigned = CommonT->isSignedIntegerType();
6977
6978 bool EqualityOnly = false;
6979
6980 if (CommonSigned) {
6981 // The common type is signed, therefore no signed to unsigned conversion.
6982 if (!OtherRange.NonNegative) {
6983 // Check that the constant is representable in type OtherT.
6984 if (ConstantSigned) {
6985 if (OtherWidth >= Value.getMinSignedBits())
6986 return;
6987 } else { // !ConstantSigned
6988 if (OtherWidth >= Value.getActiveBits() + 1)
6989 return;
6990 }
6991 } else { // !OtherSigned
6992 // Check that the constant is representable in type OtherT.
6993 // Negative values are out of range.
6994 if (ConstantSigned) {
6995 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6996 return;
6997 } else { // !ConstantSigned
6998 if (OtherWidth >= Value.getActiveBits())
6999 return;
7000 }
Richard Trieu560910c2012-11-14 22:50:24 +00007001 }
Richard Trieu0f097742014-04-04 04:13:47 +00007002 } else { // !CommonSigned
7003 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007004 if (OtherWidth >= Value.getActiveBits())
7005 return;
Craig Toppercf360162014-06-18 05:13:11 +00007006 } else { // OtherSigned
7007 assert(!ConstantSigned &&
7008 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007009 // Check to see if the constant is representable in OtherT.
7010 if (OtherWidth > Value.getActiveBits())
7011 return;
7012 // Check to see if the constant is equivalent to a negative value
7013 // cast to CommonT.
7014 if (S.Context.getIntWidth(ConstantT) ==
7015 S.Context.getIntWidth(CommonT) &&
7016 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7017 return;
7018 // The constant value rests between values that OtherT can represent
7019 // after conversion. Relational comparison still works, but equality
7020 // comparisons will be tautological.
7021 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007022 }
7023 }
Richard Trieu0f097742014-04-04 04:13:47 +00007024
7025 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7026
7027 if (op == BO_EQ || op == BO_NE) {
7028 IsTrue = op == BO_NE;
7029 } else if (EqualityOnly) {
7030 return;
7031 } else if (RhsConstant) {
7032 if (op == BO_GT || op == BO_GE)
7033 IsTrue = !PositiveConstant;
7034 else // op == BO_LT || op == BO_LE
7035 IsTrue = PositiveConstant;
7036 } else {
7037 if (op == BO_LT || op == BO_LE)
7038 IsTrue = !PositiveConstant;
7039 else // op == BO_GT || op == BO_GE
7040 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007041 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007042 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007043 // Other isKnownToHaveBooleanValue
7044 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7045 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7046 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7047
7048 static const struct LinkedConditions {
7049 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7050 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7051 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7052 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7053 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7054 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7055
7056 } TruthTable = {
7057 // Constant on LHS. | Constant on RHS. |
7058 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7059 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7060 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7061 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7062 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7063 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7064 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7065 };
7066
7067 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7068
7069 enum ConstantValue ConstVal = Zero;
7070 if (Value.isUnsigned() || Value.isNonNegative()) {
7071 if (Value == 0) {
7072 LiteralOrBoolConstant =
7073 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7074 ConstVal = Zero;
7075 } else if (Value == 1) {
7076 LiteralOrBoolConstant =
7077 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7078 ConstVal = One;
7079 } else {
7080 LiteralOrBoolConstant = LiteralConstant;
7081 ConstVal = GT_One;
7082 }
7083 } else {
7084 ConstVal = LT_Zero;
7085 }
7086
7087 CompareBoolWithConstantResult CmpRes;
7088
7089 switch (op) {
7090 case BO_LT:
7091 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7092 break;
7093 case BO_GT:
7094 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7095 break;
7096 case BO_LE:
7097 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7098 break;
7099 case BO_GE:
7100 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7101 break;
7102 case BO_EQ:
7103 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7104 break;
7105 case BO_NE:
7106 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7107 break;
7108 default:
7109 CmpRes = Unkwn;
7110 break;
7111 }
7112
7113 if (CmpRes == AFals) {
7114 IsTrue = false;
7115 } else if (CmpRes == ATrue) {
7116 IsTrue = true;
7117 } else {
7118 return;
7119 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007120 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007121
7122 // If this is a comparison to an enum constant, include that
7123 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007124 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007125 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7126 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7127
7128 SmallString<64> PrettySourceValue;
7129 llvm::raw_svector_ostream OS(PrettySourceValue);
7130 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007131 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007132 else
7133 OS << Value;
7134
Richard Trieu0f097742014-04-04 04:13:47 +00007135 S.DiagRuntimeBehavior(
7136 E->getOperatorLoc(), E,
7137 S.PDiag(diag::warn_out_of_range_compare)
7138 << OS.str() << LiteralOrBoolConstant
7139 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7140 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007141}
7142
John McCallcc7e5bf2010-05-06 08:58:33 +00007143/// Analyze the operands of the given comparison. Implements the
7144/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007145void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007146 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7147 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007148}
John McCall263a48b2010-01-04 23:31:57 +00007149
John McCallca01b222010-01-04 23:21:16 +00007150/// \brief Implements -Wsign-compare.
7151///
Richard Trieu82402a02011-09-15 21:56:47 +00007152/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007153void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007154 // The type the comparison is being performed in.
7155 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007156
7157 // Only analyze comparison operators where both sides have been converted to
7158 // the same type.
7159 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7160 return AnalyzeImpConvsInComparison(S, E);
7161
7162 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007163 if (E->isValueDependent())
7164 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007165
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007166 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7167 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007168
7169 bool IsComparisonConstant = false;
7170
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007171 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007172 // of 'true' or 'false'.
7173 if (T->isIntegralType(S.Context)) {
7174 llvm::APSInt RHSValue;
7175 bool IsRHSIntegralLiteral =
7176 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7177 llvm::APSInt LHSValue;
7178 bool IsLHSIntegralLiteral =
7179 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7180 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7181 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7182 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7183 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7184 else
7185 IsComparisonConstant =
7186 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007187 } else if (!T->hasUnsignedIntegerRepresentation())
7188 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007189
John McCallcc7e5bf2010-05-06 08:58:33 +00007190 // We don't do anything special if this isn't an unsigned integral
7191 // comparison: we're only interested in integral comparisons, and
7192 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007193 //
7194 // We also don't care about value-dependent expressions or expressions
7195 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007196 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007197 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007198
John McCallcc7e5bf2010-05-06 08:58:33 +00007199 // Check to see if one of the (unmodified) operands is of different
7200 // signedness.
7201 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007202 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7203 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007204 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007205 signedOperand = LHS;
7206 unsignedOperand = RHS;
7207 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7208 signedOperand = RHS;
7209 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007210 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007211 CheckTrivialUnsignedComparison(S, E);
7212 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007213 }
7214
John McCallcc7e5bf2010-05-06 08:58:33 +00007215 // Otherwise, calculate the effective range of the signed operand.
7216 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007217
John McCallcc7e5bf2010-05-06 08:58:33 +00007218 // Go ahead and analyze implicit conversions in the operands. Note
7219 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007220 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7221 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007222
John McCallcc7e5bf2010-05-06 08:58:33 +00007223 // If the signed range is non-negative, -Wsign-compare won't fire,
7224 // but we should still check for comparisons which are always true
7225 // or false.
7226 if (signedRange.NonNegative)
7227 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007228
7229 // For (in)equality comparisons, if the unsigned operand is a
7230 // constant which cannot collide with a overflowed signed operand,
7231 // then reinterpreting the signed operand as unsigned will not
7232 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007233 if (E->isEqualityOp()) {
7234 unsigned comparisonWidth = S.Context.getIntWidth(T);
7235 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007236
John McCallcc7e5bf2010-05-06 08:58:33 +00007237 // We should never be unable to prove that the unsigned operand is
7238 // non-negative.
7239 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7240
7241 if (unsignedRange.Width < comparisonWidth)
7242 return;
7243 }
7244
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007245 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7246 S.PDiag(diag::warn_mixed_sign_comparison)
7247 << LHS->getType() << RHS->getType()
7248 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007249}
7250
John McCall1f425642010-11-11 03:21:53 +00007251/// Analyzes an attempt to assign the given value to a bitfield.
7252///
7253/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007254bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7255 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007256 assert(Bitfield->isBitField());
7257 if (Bitfield->isInvalidDecl())
7258 return false;
7259
John McCalldeebbcf2010-11-11 05:33:51 +00007260 // White-list bool bitfields.
7261 if (Bitfield->getType()->isBooleanType())
7262 return false;
7263
Douglas Gregor789adec2011-02-04 13:09:01 +00007264 // Ignore value- or type-dependent expressions.
7265 if (Bitfield->getBitWidth()->isValueDependent() ||
7266 Bitfield->getBitWidth()->isTypeDependent() ||
7267 Init->isValueDependent() ||
7268 Init->isTypeDependent())
7269 return false;
7270
John McCall1f425642010-11-11 03:21:53 +00007271 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7272
Richard Smith5fab0c92011-12-28 19:48:30 +00007273 llvm::APSInt Value;
7274 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007275 return false;
7276
John McCall1f425642010-11-11 03:21:53 +00007277 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007278 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007279
7280 if (OriginalWidth <= FieldWidth)
7281 return false;
7282
Eli Friedmanc267a322012-01-26 23:11:39 +00007283 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007284 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007285 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007286
Eli Friedmanc267a322012-01-26 23:11:39 +00007287 // Check whether the stored value is equal to the original value.
7288 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007289 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007290 return false;
7291
Eli Friedmanc267a322012-01-26 23:11:39 +00007292 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007293 // therefore don't strictly fit into a signed bitfield of width 1.
7294 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007295 return false;
7296
John McCall1f425642010-11-11 03:21:53 +00007297 std::string PrettyValue = Value.toString(10);
7298 std::string PrettyTrunc = TruncatedValue.toString(10);
7299
7300 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7301 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7302 << Init->getSourceRange();
7303
7304 return true;
7305}
7306
John McCalld2a53122010-11-09 23:24:47 +00007307/// Analyze the given simple or compound assignment for warning-worthy
7308/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007309void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007310 // Just recurse on the LHS.
7311 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7312
7313 // We want to recurse on the RHS as normal unless we're assigning to
7314 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007315 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007316 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007317 E->getOperatorLoc())) {
7318 // Recurse, ignoring any implicit conversions on the RHS.
7319 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7320 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007321 }
7322 }
7323
7324 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7325}
7326
John McCall263a48b2010-01-04 23:31:57 +00007327/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007328void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7329 SourceLocation CContext, unsigned diag,
7330 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007331 if (pruneControlFlow) {
7332 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7333 S.PDiag(diag)
7334 << SourceType << T << E->getSourceRange()
7335 << SourceRange(CContext));
7336 return;
7337 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007338 S.Diag(E->getExprLoc(), diag)
7339 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7340}
7341
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007342/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007343void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7344 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007345 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007346}
7347
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007348/// Diagnose an implicit cast from a literal expression. Does not warn when the
7349/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00007350void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
7351 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007352 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00007353 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007354 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007355 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7356 T->hasUnsignedIntegerRepresentation());
7357 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00007358 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007359 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00007360 return;
7361
Eli Friedman07185912013-08-29 23:44:43 +00007362 // FIXME: Force the precision of the source value down so we don't print
7363 // digits which are usually useless (we don't really care here if we
7364 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7365 // would automatically print the shortest representation, but it's a bit
7366 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007367 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007368 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7369 precision = (precision * 59 + 195) / 196;
7370 Value.toString(PrettySourceValue, precision);
7371
David Blaikie9b88cc02012-05-15 17:18:27 +00007372 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00007373 if (T->isSpecificBuiltinType(BuiltinType::Bool))
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007374 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007375 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007376 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007377
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007378 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00007379 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
7380 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00007381}
7382
John McCall18a2c2c2010-11-09 22:22:12 +00007383std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7384 if (!Range.Width) return "0";
7385
7386 llvm::APSInt ValueInRange = Value;
7387 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007388 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007389 return ValueInRange.toString(10);
7390}
7391
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007392bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007393 if (!isa<ImplicitCastExpr>(Ex))
7394 return false;
7395
7396 Expr *InnerE = Ex->IgnoreParenImpCasts();
7397 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7398 const Type *Source =
7399 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7400 if (Target->isDependentType())
7401 return false;
7402
7403 const BuiltinType *FloatCandidateBT =
7404 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7405 const Type *BoolCandidateType = ToBool ? Target : Source;
7406
7407 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7408 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7409}
7410
7411void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7412 SourceLocation CC) {
7413 unsigned NumArgs = TheCall->getNumArgs();
7414 for (unsigned i = 0; i < NumArgs; ++i) {
7415 Expr *CurrA = TheCall->getArg(i);
7416 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7417 continue;
7418
7419 bool IsSwapped = ((i > 0) &&
7420 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7421 IsSwapped |= ((i < (NumArgs - 1)) &&
7422 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7423 if (IsSwapped) {
7424 // Warn on this floating-point to bool conversion.
7425 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7426 CurrA->getType(), CC,
7427 diag::warn_impcast_floating_point_to_bool);
7428 }
7429 }
7430}
7431
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007432void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007433 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7434 E->getExprLoc()))
7435 return;
7436
Richard Trieu09d6b802016-01-08 23:35:06 +00007437 // Don't warn on functions which have return type nullptr_t.
7438 if (isa<CallExpr>(E))
7439 return;
7440
Richard Trieu5b993502014-10-15 03:42:06 +00007441 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7442 const Expr::NullPointerConstantKind NullKind =
7443 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7444 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7445 return;
7446
7447 // Return if target type is a safe conversion.
7448 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7449 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7450 return;
7451
7452 SourceLocation Loc = E->getSourceRange().getBegin();
7453
Richard Trieu0a5e1662016-02-13 00:58:53 +00007454 // Venture through the macro stacks to get to the source of macro arguments.
7455 // The new location is a better location than the complete location that was
7456 // passed in.
7457 while (S.SourceMgr.isMacroArgExpansion(Loc))
7458 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
7459
7460 while (S.SourceMgr.isMacroArgExpansion(CC))
7461 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
7462
Richard Trieu5b993502014-10-15 03:42:06 +00007463 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00007464 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
7465 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7466 Loc, S.SourceMgr, S.getLangOpts());
7467 if (MacroName == "NULL")
7468 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00007469 }
7470
7471 // Only warn if the null and context location are in the same macro expansion.
7472 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7473 return;
7474
7475 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7476 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7477 << FixItHint::CreateReplacement(Loc,
7478 S.getFixItZeroLiteralForType(T, Loc));
7479}
7480
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007481void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7482 ObjCArrayLiteral *ArrayLiteral);
7483void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7484 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00007485
7486/// Check a single element within a collection literal against the
7487/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007488void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7489 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007490 // Skip a bitcast to 'id' or qualified 'id'.
7491 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7492 if (ICE->getCastKind() == CK_BitCast &&
7493 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7494 Element = ICE->getSubExpr();
7495 }
7496
7497 QualType ElementType = Element->getType();
7498 ExprResult ElementResult(Element);
7499 if (ElementType->getAs<ObjCObjectPointerType>() &&
7500 S.CheckSingleAssignmentConstraints(TargetElementType,
7501 ElementResult,
7502 false, false)
7503 != Sema::Compatible) {
7504 S.Diag(Element->getLocStart(),
7505 diag::warn_objc_collection_literal_element)
7506 << ElementType << ElementKind << TargetElementType
7507 << Element->getSourceRange();
7508 }
7509
7510 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7511 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7512 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7513 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7514}
7515
7516/// Check an Objective-C array literal being converted to the given
7517/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007518void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7519 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007520 if (!S.NSArrayDecl)
7521 return;
7522
7523 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7524 if (!TargetObjCPtr)
7525 return;
7526
7527 if (TargetObjCPtr->isUnspecialized() ||
7528 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7529 != S.NSArrayDecl->getCanonicalDecl())
7530 return;
7531
7532 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7533 if (TypeArgs.size() != 1)
7534 return;
7535
7536 QualType TargetElementType = TypeArgs[0];
7537 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7538 checkObjCCollectionLiteralElement(S, TargetElementType,
7539 ArrayLiteral->getElement(I),
7540 0);
7541 }
7542}
7543
7544/// Check an Objective-C dictionary literal being converted to the given
7545/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007546void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7547 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007548 if (!S.NSDictionaryDecl)
7549 return;
7550
7551 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7552 if (!TargetObjCPtr)
7553 return;
7554
7555 if (TargetObjCPtr->isUnspecialized() ||
7556 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7557 != S.NSDictionaryDecl->getCanonicalDecl())
7558 return;
7559
7560 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7561 if (TypeArgs.size() != 2)
7562 return;
7563
7564 QualType TargetKeyType = TypeArgs[0];
7565 QualType TargetObjectType = TypeArgs[1];
7566 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7567 auto Element = DictionaryLiteral->getKeyValueElement(I);
7568 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7569 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7570 }
7571}
7572
Richard Trieufc404c72016-02-05 23:02:38 +00007573// Helper function to filter out cases for constant width constant conversion.
7574// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007575bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7576 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00007577 // If initializing from a constant, and the constant starts with '0',
7578 // then it is a binary, octal, or hexadecimal. Allow these constants
7579 // to fill all the bits, even if there is a sign change.
7580 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7581 const char FirstLiteralCharacter =
7582 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7583 if (FirstLiteralCharacter == '0')
7584 return false;
7585 }
7586
7587 // If the CC location points to a '{', and the type is char, then assume
7588 // assume it is an array initialization.
7589 if (CC.isValid() && T->isCharType()) {
7590 const char FirstContextCharacter =
7591 S.getSourceManager().getCharacterData(CC)[0];
7592 if (FirstContextCharacter == '{')
7593 return false;
7594 }
7595
7596 return true;
7597}
7598
John McCallcc7e5bf2010-05-06 08:58:33 +00007599void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007600 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007601 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007602
John McCallcc7e5bf2010-05-06 08:58:33 +00007603 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7604 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7605 if (Source == Target) return;
7606 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007607
Chandler Carruthc22845a2011-07-26 05:40:03 +00007608 // If the conversion context location is invalid don't complain. We also
7609 // don't want to emit a warning if the issue occurs from the expansion of
7610 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7611 // delay this check as long as possible. Once we detect we are in that
7612 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007613 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007614 return;
7615
Richard Trieu021baa32011-09-23 20:10:00 +00007616 // Diagnose implicit casts to bool.
7617 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7618 if (isa<StringLiteral>(E))
7619 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007620 // and expressions, for instance, assert(0 && "error here"), are
7621 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007622 return DiagnoseImpCast(S, E, T, CC,
7623 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007624 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7625 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7626 // This covers the literal expressions that evaluate to Objective-C
7627 // objects.
7628 return DiagnoseImpCast(S, E, T, CC,
7629 diag::warn_impcast_objective_c_literal_to_bool);
7630 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007631 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7632 // Warn on pointer to bool conversion that is always true.
7633 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7634 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007635 }
Richard Trieu021baa32011-09-23 20:10:00 +00007636 }
John McCall263a48b2010-01-04 23:31:57 +00007637
Douglas Gregor5054cb02015-07-07 03:58:22 +00007638 // Check implicit casts from Objective-C collection literals to specialized
7639 // collection types, e.g., NSArray<NSString *> *.
7640 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7641 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7642 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7643 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7644
John McCall263a48b2010-01-04 23:31:57 +00007645 // Strip vector types.
7646 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007647 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007648 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007649 return;
John McCallacf0ee52010-10-08 02:01:28 +00007650 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007651 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007652
7653 // If the vector cast is cast between two vectors of the same size, it is
7654 // a bitcast, not a conversion.
7655 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7656 return;
John McCall263a48b2010-01-04 23:31:57 +00007657
7658 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7659 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7660 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007661 if (auto VecTy = dyn_cast<VectorType>(Target))
7662 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007663
7664 // Strip complex types.
7665 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007666 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007667 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007668 return;
7669
John McCallacf0ee52010-10-08 02:01:28 +00007670 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007671 }
John McCall263a48b2010-01-04 23:31:57 +00007672
7673 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7674 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7675 }
7676
7677 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7678 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7679
7680 // If the source is floating point...
7681 if (SourceBT && SourceBT->isFloatingPoint()) {
7682 // ...and the target is floating point...
7683 if (TargetBT && TargetBT->isFloatingPoint()) {
7684 // ...then warn if we're dropping FP rank.
7685
7686 // Builtin FP kinds are ordered by increasing FP rank.
7687 if (SourceBT->getKind() > TargetBT->getKind()) {
7688 // Don't warn about float constants that are precisely
7689 // representable in the target type.
7690 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007691 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007692 // Value might be a float, a float vector, or a float complex.
7693 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007694 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7695 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007696 return;
7697 }
7698
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007699 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007700 return;
7701
John McCallacf0ee52010-10-08 02:01:28 +00007702 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007703 }
7704 // ... or possibly if we're increasing rank, too
7705 else if (TargetBT->getKind() > SourceBT->getKind()) {
7706 if (S.SourceMgr.isInSystemMacro(CC))
7707 return;
7708
7709 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007710 }
7711 return;
7712 }
7713
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007714 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007715 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007716 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007717 return;
7718
Chandler Carruth22c7a792011-02-17 11:05:49 +00007719 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007720 // We also want to warn on, e.g., "int i = -1.234"
7721 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7722 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7723 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7724
Chandler Carruth016ef402011-04-10 08:36:24 +00007725 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7726 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007727 } else {
7728 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7729 }
7730 }
John McCall263a48b2010-01-04 23:31:57 +00007731
Richard Smith54894fd2015-12-30 01:06:52 +00007732 // Detect the case where a call result is converted from floating-point to
7733 // to bool, and the final argument to the call is converted from bool, to
7734 // discover this typo:
7735 //
7736 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
7737 //
7738 // FIXME: This is an incredibly special case; is there some more general
7739 // way to detect this class of misplaced-parentheses bug?
7740 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007741 // Check last argument of function call to see if it is an
7742 // implicit cast from a type matching the type the result
7743 // is being cast to.
7744 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00007745 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007746 Expr *LastA = CEx->getArg(NumArgs - 1);
7747 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00007748 if (isa<ImplicitCastExpr>(LastA) &&
7749 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007750 // Warn on this floating-point to bool conversion
7751 DiagnoseImpCast(S, E, T, CC,
7752 diag::warn_impcast_floating_point_to_bool);
7753 }
7754 }
7755 }
John McCall263a48b2010-01-04 23:31:57 +00007756 return;
7757 }
7758
Richard Trieu5b993502014-10-15 03:42:06 +00007759 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007760
David Blaikie9366d2b2012-06-19 21:19:06 +00007761 if (!Source->isIntegerType() || !Target->isIntegerType())
7762 return;
7763
David Blaikie7555b6a2012-05-15 16:56:36 +00007764 // TODO: remove this early return once the false positives for constant->bool
7765 // in templates, macros, etc, are reduced or removed.
7766 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7767 return;
7768
John McCallcc7e5bf2010-05-06 08:58:33 +00007769 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007770 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007771
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007772 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007773 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007774 // TODO: this should happen for bitfield stores, too.
7775 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00007776 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007777 if (S.SourceMgr.isInSystemMacro(CC))
7778 return;
7779
John McCall18a2c2c2010-11-09 22:22:12 +00007780 std::string PrettySourceValue = Value.toString(10);
7781 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007782
Ted Kremenek33ba9952011-10-22 02:37:33 +00007783 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7784 S.PDiag(diag::warn_impcast_integer_precision_constant)
7785 << PrettySourceValue << PrettyTargetValue
7786 << E->getType() << T << E->getSourceRange()
7787 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007788 return;
7789 }
7790
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007791 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7792 if (S.SourceMgr.isInSystemMacro(CC))
7793 return;
7794
David Blaikie9455da02012-04-12 22:40:54 +00007795 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007796 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7797 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007798 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007799 }
7800
Richard Trieudcb55572016-01-29 23:51:16 +00007801 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
7802 SourceRange.NonNegative && Source->isSignedIntegerType()) {
7803 // Warn when doing a signed to signed conversion, warn if the positive
7804 // source value is exactly the width of the target type, which will
7805 // cause a negative value to be stored.
7806
7807 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00007808 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
7809 !S.SourceMgr.isInSystemMacro(CC)) {
7810 if (isSameWidthConstantConversion(S, E, T, CC)) {
7811 std::string PrettySourceValue = Value.toString(10);
7812 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00007813
Richard Trieufc404c72016-02-05 23:02:38 +00007814 S.DiagRuntimeBehavior(
7815 E->getExprLoc(), E,
7816 S.PDiag(diag::warn_impcast_integer_precision_constant)
7817 << PrettySourceValue << PrettyTargetValue << E->getType() << T
7818 << E->getSourceRange() << clang::SourceRange(CC));
7819 return;
Richard Trieudcb55572016-01-29 23:51:16 +00007820 }
7821 }
Richard Trieufc404c72016-02-05 23:02:38 +00007822
Richard Trieudcb55572016-01-29 23:51:16 +00007823 // Fall through for non-constants to give a sign conversion warning.
7824 }
7825
John McCallcc7e5bf2010-05-06 08:58:33 +00007826 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7827 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7828 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007829 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007830 return;
7831
John McCallcc7e5bf2010-05-06 08:58:33 +00007832 unsigned DiagID = diag::warn_impcast_integer_sign;
7833
7834 // Traditionally, gcc has warned about this under -Wsign-compare.
7835 // We also want to warn about it in -Wconversion.
7836 // So if -Wconversion is off, use a completely identical diagnostic
7837 // in the sign-compare group.
7838 // The conditional-checking code will
7839 if (ICContext) {
7840 DiagID = diag::warn_impcast_integer_sign_conditional;
7841 *ICContext = true;
7842 }
7843
John McCallacf0ee52010-10-08 02:01:28 +00007844 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007845 }
7846
Douglas Gregora78f1932011-02-22 02:45:07 +00007847 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007848 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7849 // type, to give us better diagnostics.
7850 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007851 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007852 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7853 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7854 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7855 SourceType = S.Context.getTypeDeclType(Enum);
7856 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7857 }
7858 }
7859
Douglas Gregora78f1932011-02-22 02:45:07 +00007860 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7861 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007862 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7863 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007864 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007865 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007866 return;
7867
Douglas Gregor364f7db2011-03-12 00:14:31 +00007868 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007869 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007870 }
John McCall263a48b2010-01-04 23:31:57 +00007871}
7872
David Blaikie18e9ac72012-05-15 21:57:38 +00007873void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7874 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007875
7876void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007877 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007878 E = E->IgnoreParenImpCasts();
7879
7880 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007881 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007882
John McCallacf0ee52010-10-08 02:01:28 +00007883 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007884 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007885 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007886}
7887
David Blaikie18e9ac72012-05-15 21:57:38 +00007888void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7889 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007890 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007891
7892 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007893 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7894 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007895
7896 // If -Wconversion would have warned about either of the candidates
7897 // for a signedness conversion to the context type...
7898 if (!Suspicious) return;
7899
7900 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007901 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007902 return;
7903
John McCallcc7e5bf2010-05-06 08:58:33 +00007904 // ...then check whether it would have warned about either of the
7905 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007906 if (E->getType() == T) return;
7907
7908 Suspicious = false;
7909 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7910 E->getType(), CC, &Suspicious);
7911 if (!Suspicious)
7912 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007913 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007914}
7915
Richard Trieu65724892014-11-15 06:37:39 +00007916/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7917/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007918void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00007919 if (S.getLangOpts().Bool)
7920 return;
7921 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7922}
7923
John McCallcc7e5bf2010-05-06 08:58:33 +00007924/// AnalyzeImplicitConversions - Find and report any interesting
7925/// implicit conversions in the given expression. There are a couple
7926/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007927void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007928 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007929 Expr *E = OrigE->IgnoreParenImpCasts();
7930
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007931 if (E->isTypeDependent() || E->isValueDependent())
7932 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007933
John McCallcc7e5bf2010-05-06 08:58:33 +00007934 // For conditional operators, we analyze the arguments as if they
7935 // were being fed directly into the output.
7936 if (isa<ConditionalOperator>(E)) {
7937 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007938 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007939 return;
7940 }
7941
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007942 // Check implicit argument conversions for function calls.
7943 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7944 CheckImplicitArgumentConversions(S, Call, CC);
7945
John McCallcc7e5bf2010-05-06 08:58:33 +00007946 // Go ahead and check any implicit conversions we might have skipped.
7947 // The non-canonical typecheck is just an optimization;
7948 // CheckImplicitConversion will filter out dead implicit conversions.
7949 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007950 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007951
7952 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00007953
7954 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
7955 // The bound subexpressions in a PseudoObjectExpr are not reachable
7956 // as transitive children.
7957 // FIXME: Use a more uniform representation for this.
7958 for (auto *SE : POE->semantics())
7959 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
7960 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007961 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00007962
John McCallcc7e5bf2010-05-06 08:58:33 +00007963 // Skip past explicit casts.
7964 if (isa<ExplicitCastExpr>(E)) {
7965 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007966 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007967 }
7968
John McCalld2a53122010-11-09 23:24:47 +00007969 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7970 // Do a somewhat different check with comparison operators.
7971 if (BO->isComparisonOp())
7972 return AnalyzeComparison(S, BO);
7973
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007974 // And with simple assignments.
7975 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007976 return AnalyzeAssignment(S, BO);
7977 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007978
7979 // These break the otherwise-useful invariant below. Fortunately,
7980 // we don't really need to recurse into them, because any internal
7981 // expressions should have been analyzed already when they were
7982 // built into statements.
7983 if (isa<StmtExpr>(E)) return;
7984
7985 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007986 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007987
7988 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007989 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007990 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007991 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007992 for (Stmt *SubStmt : E->children()) {
7993 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007994 if (!ChildExpr)
7995 continue;
7996
Richard Trieu955231d2014-01-25 01:10:35 +00007997 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007998 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007999 // Ignore checking string literals that are in logical and operators.
8000 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008001 continue;
8002 AnalyzeImplicitConversions(S, ChildExpr, CC);
8003 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008004
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008005 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008006 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8007 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008008 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008009
8010 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8011 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008012 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008013 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008014
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008015 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8016 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008017 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008018}
8019
8020} // end anonymous namespace
8021
Richard Trieuc1888e02014-06-28 23:25:37 +00008022// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8023// Returns true when emitting a warning about taking the address of a reference.
8024static bool CheckForReference(Sema &SemaRef, const Expr *E,
8025 PartialDiagnostic PD) {
8026 E = E->IgnoreParenImpCasts();
8027
8028 const FunctionDecl *FD = nullptr;
8029
8030 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8031 if (!DRE->getDecl()->getType()->isReferenceType())
8032 return false;
8033 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8034 if (!M->getMemberDecl()->getType()->isReferenceType())
8035 return false;
8036 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008037 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008038 return false;
8039 FD = Call->getDirectCallee();
8040 } else {
8041 return false;
8042 }
8043
8044 SemaRef.Diag(E->getExprLoc(), PD);
8045
8046 // If possible, point to location of function.
8047 if (FD) {
8048 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8049 }
8050
8051 return true;
8052}
8053
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008054// Returns true if the SourceLocation is expanded from any macro body.
8055// Returns false if the SourceLocation is invalid, is from not in a macro
8056// expansion, or is from expanded from a top-level macro argument.
8057static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8058 if (Loc.isInvalid())
8059 return false;
8060
8061 while (Loc.isMacroID()) {
8062 if (SM.isMacroBodyExpansion(Loc))
8063 return true;
8064 Loc = SM.getImmediateMacroCallerLoc(Loc);
8065 }
8066
8067 return false;
8068}
8069
Richard Trieu3bb8b562014-02-26 02:36:06 +00008070/// \brief Diagnose pointers that are always non-null.
8071/// \param E the expression containing the pointer
8072/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8073/// compared to a null pointer
8074/// \param IsEqual True when the comparison is equal to a null pointer
8075/// \param Range Extra SourceRange to highlight in the diagnostic
8076void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8077 Expr::NullPointerConstantKind NullKind,
8078 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008079 if (!E)
8080 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008081
8082 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008083 if (E->getExprLoc().isMacroID()) {
8084 const SourceManager &SM = getSourceManager();
8085 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8086 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008087 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008088 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008089 E = E->IgnoreImpCasts();
8090
8091 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8092
Richard Trieuf7432752014-06-06 21:39:26 +00008093 if (isa<CXXThisExpr>(E)) {
8094 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8095 : diag::warn_this_bool_conversion;
8096 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8097 return;
8098 }
8099
Richard Trieu3bb8b562014-02-26 02:36:06 +00008100 bool IsAddressOf = false;
8101
8102 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8103 if (UO->getOpcode() != UO_AddrOf)
8104 return;
8105 IsAddressOf = true;
8106 E = UO->getSubExpr();
8107 }
8108
Richard Trieuc1888e02014-06-28 23:25:37 +00008109 if (IsAddressOf) {
8110 unsigned DiagID = IsCompare
8111 ? diag::warn_address_of_reference_null_compare
8112 : diag::warn_address_of_reference_bool_conversion;
8113 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8114 << IsEqual;
8115 if (CheckForReference(*this, E, PD)) {
8116 return;
8117 }
8118 }
8119
George Burgess IV850269a2015-12-08 22:02:00 +00008120 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
8121 std::string Str;
8122 llvm::raw_string_ostream S(Str);
8123 E->printPretty(S, nullptr, getPrintingPolicy());
8124 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8125 : diag::warn_cast_nonnull_to_bool;
8126 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8127 << E->getSourceRange() << Range << IsEqual;
8128 };
8129
8130 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8131 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8132 if (auto *Callee = Call->getDirectCallee()) {
8133 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
8134 ComplainAboutNonnullParamOrCall(false);
8135 return;
8136 }
8137 }
8138 }
8139
Richard Trieu3bb8b562014-02-26 02:36:06 +00008140 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008141 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008142 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8143 D = R->getDecl();
8144 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8145 D = M->getMemberDecl();
8146 }
8147
8148 // Weak Decls can be null.
8149 if (!D || D->isWeak())
8150 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008151
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008152 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008153 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8154 if (getCurFunction() &&
8155 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8156 if (PV->hasAttr<NonNullAttr>()) {
8157 ComplainAboutNonnullParamOrCall(true);
8158 return;
8159 }
8160
8161 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8162 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
8163 assert(ParamIter != FD->param_end());
8164 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8165
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008166 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8167 if (!NonNull->args_size()) {
George Burgess IV850269a2015-12-08 22:02:00 +00008168 ComplainAboutNonnullParamOrCall(true);
8169 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008170 }
George Burgess IV850269a2015-12-08 22:02:00 +00008171
8172 for (unsigned ArgNo : NonNull->args()) {
8173 if (ArgNo == ParamNo) {
8174 ComplainAboutNonnullParamOrCall(true);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008175 return;
8176 }
George Burgess IV850269a2015-12-08 22:02:00 +00008177 }
8178 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008179 }
8180 }
George Burgess IV850269a2015-12-08 22:02:00 +00008181 }
8182
Richard Trieu3bb8b562014-02-26 02:36:06 +00008183 QualType T = D->getType();
8184 const bool IsArray = T->isArrayType();
8185 const bool IsFunction = T->isFunctionType();
8186
Richard Trieuc1888e02014-06-28 23:25:37 +00008187 // Address of function is used to silence the function warning.
8188 if (IsAddressOf && IsFunction) {
8189 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008190 }
8191
8192 // Found nothing.
8193 if (!IsAddressOf && !IsFunction && !IsArray)
8194 return;
8195
8196 // Pretty print the expression for the diagnostic.
8197 std::string Str;
8198 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008199 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008200
8201 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8202 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008203 enum {
8204 AddressOf,
8205 FunctionPointer,
8206 ArrayPointer
8207 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008208 if (IsAddressOf)
8209 DiagType = AddressOf;
8210 else if (IsFunction)
8211 DiagType = FunctionPointer;
8212 else if (IsArray)
8213 DiagType = ArrayPointer;
8214 else
8215 llvm_unreachable("Could not determine diagnostic.");
8216 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8217 << Range << IsEqual;
8218
8219 if (!IsFunction)
8220 return;
8221
8222 // Suggest '&' to silence the function warning.
8223 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8224 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8225
8226 // Check to see if '()' fixit should be emitted.
8227 QualType ReturnType;
8228 UnresolvedSet<4> NonTemplateOverloads;
8229 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8230 if (ReturnType.isNull())
8231 return;
8232
8233 if (IsCompare) {
8234 // There are two cases here. If there is null constant, the only suggest
8235 // for a pointer return type. If the null is 0, then suggest if the return
8236 // type is a pointer or an integer type.
8237 if (!ReturnType->isPointerType()) {
8238 if (NullKind == Expr::NPCK_ZeroExpression ||
8239 NullKind == Expr::NPCK_ZeroLiteral) {
8240 if (!ReturnType->isIntegerType())
8241 return;
8242 } else {
8243 return;
8244 }
8245 }
8246 } else { // !IsCompare
8247 // For function to bool, only suggest if the function pointer has bool
8248 // return type.
8249 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8250 return;
8251 }
8252 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008253 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008254}
8255
John McCallcc7e5bf2010-05-06 08:58:33 +00008256/// Diagnoses "dangerous" implicit conversions within the given
8257/// expression (which is a full expression). Implements -Wconversion
8258/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008259///
8260/// \param CC the "context" location of the implicit conversion, i.e.
8261/// the most location of the syntactic entity requiring the implicit
8262/// conversion
8263void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008264 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008265 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008266 return;
8267
8268 // Don't diagnose for value- or type-dependent expressions.
8269 if (E->isTypeDependent() || E->isValueDependent())
8270 return;
8271
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008272 // Check for array bounds violations in cases where the check isn't triggered
8273 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8274 // ArraySubscriptExpr is on the RHS of a variable initialization.
8275 CheckArrayAccess(E);
8276
John McCallacf0ee52010-10-08 02:01:28 +00008277 // This is not the right CC for (e.g.) a variable initialization.
8278 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008279}
8280
Richard Trieu65724892014-11-15 06:37:39 +00008281/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8282/// Input argument E is a logical expression.
8283void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8284 ::CheckBoolLikeConversion(*this, E, CC);
8285}
8286
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008287/// Diagnose when expression is an integer constant expression and its evaluation
8288/// results in integer overflow
8289void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008290 // Use a work list to deal with nested struct initializers.
8291 SmallVector<Expr *, 2> Exprs(1, E);
8292
8293 do {
8294 Expr *E = Exprs.pop_back_val();
8295
8296 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8297 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8298 continue;
8299 }
8300
8301 if (auto InitList = dyn_cast<InitListExpr>(E))
8302 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8303 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008304}
8305
Richard Smithc406cb72013-01-17 01:17:56 +00008306namespace {
8307/// \brief Visitor for expressions which looks for unsequenced operations on the
8308/// same object.
8309class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008310 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8311
Richard Smithc406cb72013-01-17 01:17:56 +00008312 /// \brief A tree of sequenced regions within an expression. Two regions are
8313 /// unsequenced if one is an ancestor or a descendent of the other. When we
8314 /// finish processing an expression with sequencing, such as a comma
8315 /// expression, we fold its tree nodes into its parent, since they are
8316 /// unsequenced with respect to nodes we will visit later.
8317 class SequenceTree {
8318 struct Value {
8319 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8320 unsigned Parent : 31;
8321 bool Merged : 1;
8322 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008323 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008324
8325 public:
8326 /// \brief A region within an expression which may be sequenced with respect
8327 /// to some other region.
8328 class Seq {
8329 explicit Seq(unsigned N) : Index(N) {}
8330 unsigned Index;
8331 friend class SequenceTree;
8332 public:
8333 Seq() : Index(0) {}
8334 };
8335
8336 SequenceTree() { Values.push_back(Value(0)); }
8337 Seq root() const { return Seq(0); }
8338
8339 /// \brief Create a new sequence of operations, which is an unsequenced
8340 /// subset of \p Parent. This sequence of operations is sequenced with
8341 /// respect to other children of \p Parent.
8342 Seq allocate(Seq Parent) {
8343 Values.push_back(Value(Parent.Index));
8344 return Seq(Values.size() - 1);
8345 }
8346
8347 /// \brief Merge a sequence of operations into its parent.
8348 void merge(Seq S) {
8349 Values[S.Index].Merged = true;
8350 }
8351
8352 /// \brief Determine whether two operations are unsequenced. This operation
8353 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8354 /// should have been merged into its parent as appropriate.
8355 bool isUnsequenced(Seq Cur, Seq Old) {
8356 unsigned C = representative(Cur.Index);
8357 unsigned Target = representative(Old.Index);
8358 while (C >= Target) {
8359 if (C == Target)
8360 return true;
8361 C = Values[C].Parent;
8362 }
8363 return false;
8364 }
8365
8366 private:
8367 /// \brief Pick a representative for a sequence.
8368 unsigned representative(unsigned K) {
8369 if (Values[K].Merged)
8370 // Perform path compression as we go.
8371 return Values[K].Parent = representative(Values[K].Parent);
8372 return K;
8373 }
8374 };
8375
8376 /// An object for which we can track unsequenced uses.
8377 typedef NamedDecl *Object;
8378
8379 /// Different flavors of object usage which we track. We only track the
8380 /// least-sequenced usage of each kind.
8381 enum UsageKind {
8382 /// A read of an object. Multiple unsequenced reads are OK.
8383 UK_Use,
8384 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008385 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008386 UK_ModAsValue,
8387 /// A modification of an object which is not sequenced before the value
8388 /// computation of the expression, such as n++.
8389 UK_ModAsSideEffect,
8390
8391 UK_Count = UK_ModAsSideEffect + 1
8392 };
8393
8394 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008395 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008396 Expr *Use;
8397 SequenceTree::Seq Seq;
8398 };
8399
8400 struct UsageInfo {
8401 UsageInfo() : Diagnosed(false) {}
8402 Usage Uses[UK_Count];
8403 /// Have we issued a diagnostic for this variable already?
8404 bool Diagnosed;
8405 };
8406 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8407
8408 Sema &SemaRef;
8409 /// Sequenced regions within the expression.
8410 SequenceTree Tree;
8411 /// Declaration modifications and references which we have seen.
8412 UsageInfoMap UsageMap;
8413 /// The region we are currently within.
8414 SequenceTree::Seq Region;
8415 /// Filled in with declarations which were modified as a side-effect
8416 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008417 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008418 /// Expressions to check later. We defer checking these to reduce
8419 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008420 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008421
8422 /// RAII object wrapping the visitation of a sequenced subexpression of an
8423 /// expression. At the end of this process, the side-effects of the evaluation
8424 /// become sequenced with respect to the value computation of the result, so
8425 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8426 /// UK_ModAsValue.
8427 struct SequencedSubexpression {
8428 SequencedSubexpression(SequenceChecker &Self)
8429 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8430 Self.ModAsSideEffect = &ModAsSideEffect;
8431 }
8432 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00008433 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8434 MI != ME; ++MI) {
8435 UsageInfo &U = Self.UsageMap[MI->first];
8436 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8437 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8438 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00008439 }
8440 Self.ModAsSideEffect = OldModAsSideEffect;
8441 }
8442
8443 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008444 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8445 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008446 };
8447
Richard Smith40238f02013-06-20 22:21:56 +00008448 /// RAII object wrapping the visitation of a subexpression which we might
8449 /// choose to evaluate as a constant. If any subexpression is evaluated and
8450 /// found to be non-constant, this allows us to suppress the evaluation of
8451 /// the outer expression.
8452 class EvaluationTracker {
8453 public:
8454 EvaluationTracker(SequenceChecker &Self)
8455 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8456 Self.EvalTracker = this;
8457 }
8458 ~EvaluationTracker() {
8459 Self.EvalTracker = Prev;
8460 if (Prev)
8461 Prev->EvalOK &= EvalOK;
8462 }
8463
8464 bool evaluate(const Expr *E, bool &Result) {
8465 if (!EvalOK || E->isValueDependent())
8466 return false;
8467 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8468 return EvalOK;
8469 }
8470
8471 private:
8472 SequenceChecker &Self;
8473 EvaluationTracker *Prev;
8474 bool EvalOK;
8475 } *EvalTracker;
8476
Richard Smithc406cb72013-01-17 01:17:56 +00008477 /// \brief Find the object which is produced by the specified expression,
8478 /// if any.
8479 Object getObject(Expr *E, bool Mod) const {
8480 E = E->IgnoreParenCasts();
8481 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8482 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8483 return getObject(UO->getSubExpr(), Mod);
8484 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8485 if (BO->getOpcode() == BO_Comma)
8486 return getObject(BO->getRHS(), Mod);
8487 if (Mod && BO->isAssignmentOp())
8488 return getObject(BO->getLHS(), Mod);
8489 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8490 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8491 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8492 return ME->getMemberDecl();
8493 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8494 // FIXME: If this is a reference, map through to its value.
8495 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008496 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008497 }
8498
8499 /// \brief Note that an object was modified or used by an expression.
8500 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8501 Usage &U = UI.Uses[UK];
8502 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8503 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8504 ModAsSideEffect->push_back(std::make_pair(O, U));
8505 U.Use = Ref;
8506 U.Seq = Region;
8507 }
8508 }
8509 /// \brief Check whether a modification or use conflicts with a prior usage.
8510 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8511 bool IsModMod) {
8512 if (UI.Diagnosed)
8513 return;
8514
8515 const Usage &U = UI.Uses[OtherKind];
8516 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8517 return;
8518
8519 Expr *Mod = U.Use;
8520 Expr *ModOrUse = Ref;
8521 if (OtherKind == UK_Use)
8522 std::swap(Mod, ModOrUse);
8523
8524 SemaRef.Diag(Mod->getExprLoc(),
8525 IsModMod ? diag::warn_unsequenced_mod_mod
8526 : diag::warn_unsequenced_mod_use)
8527 << O << SourceRange(ModOrUse->getExprLoc());
8528 UI.Diagnosed = true;
8529 }
8530
8531 void notePreUse(Object O, Expr *Use) {
8532 UsageInfo &U = UsageMap[O];
8533 // Uses conflict with other modifications.
8534 checkUsage(O, U, Use, UK_ModAsValue, false);
8535 }
8536 void notePostUse(Object O, Expr *Use) {
8537 UsageInfo &U = UsageMap[O];
8538 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8539 addUsage(U, O, Use, UK_Use);
8540 }
8541
8542 void notePreMod(Object O, Expr *Mod) {
8543 UsageInfo &U = UsageMap[O];
8544 // Modifications conflict with other modifications and with uses.
8545 checkUsage(O, U, Mod, UK_ModAsValue, true);
8546 checkUsage(O, U, Mod, UK_Use, false);
8547 }
8548 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8549 UsageInfo &U = UsageMap[O];
8550 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8551 addUsage(U, O, Use, UK);
8552 }
8553
8554public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008555 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008556 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8557 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008558 Visit(E);
8559 }
8560
8561 void VisitStmt(Stmt *S) {
8562 // Skip all statements which aren't expressions for now.
8563 }
8564
8565 void VisitExpr(Expr *E) {
8566 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008567 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008568 }
8569
8570 void VisitCastExpr(CastExpr *E) {
8571 Object O = Object();
8572 if (E->getCastKind() == CK_LValueToRValue)
8573 O = getObject(E->getSubExpr(), false);
8574
8575 if (O)
8576 notePreUse(O, E);
8577 VisitExpr(E);
8578 if (O)
8579 notePostUse(O, E);
8580 }
8581
8582 void VisitBinComma(BinaryOperator *BO) {
8583 // C++11 [expr.comma]p1:
8584 // Every value computation and side effect associated with the left
8585 // expression is sequenced before every value computation and side
8586 // effect associated with the right expression.
8587 SequenceTree::Seq LHS = Tree.allocate(Region);
8588 SequenceTree::Seq RHS = Tree.allocate(Region);
8589 SequenceTree::Seq OldRegion = Region;
8590
8591 {
8592 SequencedSubexpression SeqLHS(*this);
8593 Region = LHS;
8594 Visit(BO->getLHS());
8595 }
8596
8597 Region = RHS;
8598 Visit(BO->getRHS());
8599
8600 Region = OldRegion;
8601
8602 // Forget that LHS and RHS are sequenced. They are both unsequenced
8603 // with respect to other stuff.
8604 Tree.merge(LHS);
8605 Tree.merge(RHS);
8606 }
8607
8608 void VisitBinAssign(BinaryOperator *BO) {
8609 // The modification is sequenced after the value computation of the LHS
8610 // and RHS, so check it before inspecting the operands and update the
8611 // map afterwards.
8612 Object O = getObject(BO->getLHS(), true);
8613 if (!O)
8614 return VisitExpr(BO);
8615
8616 notePreMod(O, BO);
8617
8618 // C++11 [expr.ass]p7:
8619 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8620 // only once.
8621 //
8622 // Therefore, for a compound assignment operator, O is considered used
8623 // everywhere except within the evaluation of E1 itself.
8624 if (isa<CompoundAssignOperator>(BO))
8625 notePreUse(O, BO);
8626
8627 Visit(BO->getLHS());
8628
8629 if (isa<CompoundAssignOperator>(BO))
8630 notePostUse(O, BO);
8631
8632 Visit(BO->getRHS());
8633
Richard Smith83e37bee2013-06-26 23:16:51 +00008634 // C++11 [expr.ass]p1:
8635 // the assignment is sequenced [...] before the value computation of the
8636 // assignment expression.
8637 // C11 6.5.16/3 has no such rule.
8638 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8639 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008640 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008641
Richard Smithc406cb72013-01-17 01:17:56 +00008642 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8643 VisitBinAssign(CAO);
8644 }
8645
8646 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8647 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8648 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8649 Object O = getObject(UO->getSubExpr(), true);
8650 if (!O)
8651 return VisitExpr(UO);
8652
8653 notePreMod(O, UO);
8654 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008655 // C++11 [expr.pre.incr]p1:
8656 // the expression ++x is equivalent to x+=1
8657 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8658 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008659 }
8660
8661 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8662 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8663 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8664 Object O = getObject(UO->getSubExpr(), true);
8665 if (!O)
8666 return VisitExpr(UO);
8667
8668 notePreMod(O, UO);
8669 Visit(UO->getSubExpr());
8670 notePostMod(O, UO, UK_ModAsSideEffect);
8671 }
8672
8673 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8674 void VisitBinLOr(BinaryOperator *BO) {
8675 // The side-effects of the LHS of an '&&' are sequenced before the
8676 // value computation of the RHS, and hence before the value computation
8677 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8678 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008679 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008680 {
8681 SequencedSubexpression Sequenced(*this);
8682 Visit(BO->getLHS());
8683 }
8684
8685 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008686 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008687 if (!Result)
8688 Visit(BO->getRHS());
8689 } else {
8690 // Check for unsequenced operations in the RHS, treating it as an
8691 // entirely separate evaluation.
8692 //
8693 // FIXME: If there are operations in the RHS which are unsequenced
8694 // with respect to operations outside the RHS, and those operations
8695 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008696 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008697 }
Richard Smithc406cb72013-01-17 01:17:56 +00008698 }
8699 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008700 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008701 {
8702 SequencedSubexpression Sequenced(*this);
8703 Visit(BO->getLHS());
8704 }
8705
8706 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008707 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008708 if (Result)
8709 Visit(BO->getRHS());
8710 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008711 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008712 }
Richard Smithc406cb72013-01-17 01:17:56 +00008713 }
8714
8715 // Only visit the condition, unless we can be sure which subexpression will
8716 // be chosen.
8717 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008718 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008719 {
8720 SequencedSubexpression Sequenced(*this);
8721 Visit(CO->getCond());
8722 }
Richard Smithc406cb72013-01-17 01:17:56 +00008723
8724 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008725 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008726 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008727 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008728 WorkList.push_back(CO->getTrueExpr());
8729 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008730 }
Richard Smithc406cb72013-01-17 01:17:56 +00008731 }
8732
Richard Smithe3dbfe02013-06-30 10:40:20 +00008733 void VisitCallExpr(CallExpr *CE) {
8734 // C++11 [intro.execution]p15:
8735 // When calling a function [...], every value computation and side effect
8736 // associated with any argument expression, or with the postfix expression
8737 // designating the called function, is sequenced before execution of every
8738 // expression or statement in the body of the function [and thus before
8739 // the value computation of its result].
8740 SequencedSubexpression Sequenced(*this);
8741 Base::VisitCallExpr(CE);
8742
8743 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8744 }
8745
Richard Smithc406cb72013-01-17 01:17:56 +00008746 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008747 // This is a call, so all subexpressions are sequenced before the result.
8748 SequencedSubexpression Sequenced(*this);
8749
Richard Smithc406cb72013-01-17 01:17:56 +00008750 if (!CCE->isListInitialization())
8751 return VisitExpr(CCE);
8752
8753 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008754 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008755 SequenceTree::Seq Parent = Region;
8756 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8757 E = CCE->arg_end();
8758 I != E; ++I) {
8759 Region = Tree.allocate(Parent);
8760 Elts.push_back(Region);
8761 Visit(*I);
8762 }
8763
8764 // Forget that the initializers are sequenced.
8765 Region = Parent;
8766 for (unsigned I = 0; I < Elts.size(); ++I)
8767 Tree.merge(Elts[I]);
8768 }
8769
8770 void VisitInitListExpr(InitListExpr *ILE) {
8771 if (!SemaRef.getLangOpts().CPlusPlus11)
8772 return VisitExpr(ILE);
8773
8774 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008775 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008776 SequenceTree::Seq Parent = Region;
8777 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8778 Expr *E = ILE->getInit(I);
8779 if (!E) continue;
8780 Region = Tree.allocate(Parent);
8781 Elts.push_back(Region);
8782 Visit(E);
8783 }
8784
8785 // Forget that the initializers are sequenced.
8786 Region = Parent;
8787 for (unsigned I = 0; I < Elts.size(); ++I)
8788 Tree.merge(Elts[I]);
8789 }
8790};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008791} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00008792
8793void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008794 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008795 WorkList.push_back(E);
8796 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008797 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008798 SequenceChecker(*this, Item, WorkList);
8799 }
Richard Smithc406cb72013-01-17 01:17:56 +00008800}
8801
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008802void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8803 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008804 CheckImplicitConversions(E, CheckLoc);
8805 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008806 if (!IsConstexpr && !E->isValueDependent())
8807 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008808}
8809
John McCall1f425642010-11-11 03:21:53 +00008810void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8811 FieldDecl *BitField,
8812 Expr *Init) {
8813 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8814}
8815
David Majnemer61a5bbf2015-04-07 22:08:51 +00008816static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8817 SourceLocation Loc) {
8818 if (!PType->isVariablyModifiedType())
8819 return;
8820 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8821 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8822 return;
8823 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008824 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8825 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8826 return;
8827 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008828 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8829 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8830 return;
8831 }
8832
8833 const ArrayType *AT = S.Context.getAsArrayType(PType);
8834 if (!AT)
8835 return;
8836
8837 if (AT->getSizeModifier() != ArrayType::Star) {
8838 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8839 return;
8840 }
8841
8842 S.Diag(Loc, diag::err_array_star_in_function_definition);
8843}
8844
Mike Stump0c2ec772010-01-21 03:59:47 +00008845/// CheckParmsForFunctionDef - Check that the parameters of the given
8846/// function are appropriate for the definition of a function. This
8847/// takes care of any checks that cannot be performed on the
8848/// declaration itself, e.g., that the types of each of the function
8849/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008850bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8851 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008852 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008853 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008854 for (; P != PEnd; ++P) {
8855 ParmVarDecl *Param = *P;
8856
Mike Stump0c2ec772010-01-21 03:59:47 +00008857 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8858 // function declarator that is part of a function definition of
8859 // that function shall not have incomplete type.
8860 //
8861 // This is also C++ [dcl.fct]p6.
8862 if (!Param->isInvalidDecl() &&
8863 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008864 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008865 Param->setInvalidDecl();
8866 HasInvalidParm = true;
8867 }
8868
8869 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8870 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008871 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008872 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008873 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008874 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008875 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008876
8877 // C99 6.7.5.3p12:
8878 // If the function declarator is not part of a definition of that
8879 // function, parameters may have incomplete type and may use the [*]
8880 // notation in their sequences of declarator specifiers to specify
8881 // variable length array types.
8882 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008883 // FIXME: This diagnostic should point the '[*]' if source-location
8884 // information is added for it.
8885 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008886
8887 // MSVC destroys objects passed by value in the callee. Therefore a
8888 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008889 // object's destructor. However, we don't perform any direct access check
8890 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008891 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8892 .getCXXABI()
8893 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008894 if (!Param->isInvalidDecl()) {
8895 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8896 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8897 if (!ClassDecl->isInvalidDecl() &&
8898 !ClassDecl->hasIrrelevantDestructor() &&
8899 !ClassDecl->isDependentContext()) {
8900 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8901 MarkFunctionReferenced(Param->getLocation(), Destructor);
8902 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8903 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008904 }
8905 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008906 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008907
8908 // Parameters with the pass_object_size attribute only need to be marked
8909 // constant at function definitions. Because we lack information about
8910 // whether we're on a declaration or definition when we're instantiating the
8911 // attribute, we need to check for constness here.
8912 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
8913 if (!Param->getType().isConstQualified())
8914 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
8915 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00008916 }
8917
8918 return HasInvalidParm;
8919}
John McCall2b5c1b22010-08-12 21:44:57 +00008920
8921/// CheckCastAlign - Implements -Wcast-align, which warns when a
8922/// pointer cast increases the alignment requirements.
8923void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8924 // This is actually a lot of work to potentially be doing on every
8925 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008926 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008927 return;
8928
8929 // Ignore dependent types.
8930 if (T->isDependentType() || Op->getType()->isDependentType())
8931 return;
8932
8933 // Require that the destination be a pointer type.
8934 const PointerType *DestPtr = T->getAs<PointerType>();
8935 if (!DestPtr) return;
8936
8937 // If the destination has alignment 1, we're done.
8938 QualType DestPointee = DestPtr->getPointeeType();
8939 if (DestPointee->isIncompleteType()) return;
8940 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8941 if (DestAlign.isOne()) return;
8942
8943 // Require that the source be a pointer type.
8944 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8945 if (!SrcPtr) return;
8946 QualType SrcPointee = SrcPtr->getPointeeType();
8947
8948 // Whitelist casts from cv void*. We already implicitly
8949 // whitelisted casts to cv void*, since they have alignment 1.
8950 // Also whitelist casts involving incomplete types, which implicitly
8951 // includes 'void'.
8952 if (SrcPointee->isIncompleteType()) return;
8953
8954 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8955 if (SrcAlign >= DestAlign) return;
8956
8957 Diag(TRange.getBegin(), diag::warn_cast_align)
8958 << Op->getType() << T
8959 << static_cast<unsigned>(SrcAlign.getQuantity())
8960 << static_cast<unsigned>(DestAlign.getQuantity())
8961 << TRange << Op->getSourceRange();
8962}
8963
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008964static const Type* getElementType(const Expr *BaseExpr) {
8965 const Type* EltType = BaseExpr->getType().getTypePtr();
8966 if (EltType->isAnyPointerType())
8967 return EltType->getPointeeType().getTypePtr();
8968 else if (EltType->isArrayType())
8969 return EltType->getBaseElementTypeUnsafe();
8970 return EltType;
8971}
8972
Chandler Carruth28389f02011-08-05 09:10:50 +00008973/// \brief Check whether this array fits the idiom of a size-one tail padded
8974/// array member of a struct.
8975///
8976/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8977/// commonly used to emulate flexible arrays in C89 code.
8978static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8979 const NamedDecl *ND) {
8980 if (Size != 1 || !ND) return false;
8981
8982 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8983 if (!FD) return false;
8984
8985 // Don't consider sizes resulting from macro expansions or template argument
8986 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008987
8988 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008989 while (TInfo) {
8990 TypeLoc TL = TInfo->getTypeLoc();
8991 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008992 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8993 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008994 TInfo = TDL->getTypeSourceInfo();
8995 continue;
8996 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008997 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8998 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008999 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9000 return false;
9001 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009002 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009003 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009004
9005 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009006 if (!RD) return false;
9007 if (RD->isUnion()) return false;
9008 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9009 if (!CRD->isStandardLayout()) return false;
9010 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009011
Benjamin Kramer8c543672011-08-06 03:04:42 +00009012 // See if this is the last field decl in the record.
9013 const Decl *D = FD;
9014 while ((D = D->getNextDeclInContext()))
9015 if (isa<FieldDecl>(D))
9016 return false;
9017 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009018}
9019
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009020void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009021 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009022 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009023 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009024 if (IndexExpr->isValueDependent())
9025 return;
9026
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00009027 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009028 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009029 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009030 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009031 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009032 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009033
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009034 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009035 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009036 return;
Richard Smith13f67182011-12-16 19:31:14 +00009037 if (IndexNegated)
9038 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009039
Craig Topperc3ec1492014-05-26 06:22:03 +00009040 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009041 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9042 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009043 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009044 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009045
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009046 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009047 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009048 if (!size.isStrictlyPositive())
9049 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009050
9051 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00009052 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009053 // Make sure we're comparing apples to apples when comparing index to size
9054 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9055 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009056 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009057 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009058 if (ptrarith_typesize != array_typesize) {
9059 // There's a cast to a different size type involved
9060 uint64_t ratio = array_typesize / ptrarith_typesize;
9061 // TODO: Be smarter about handling cases where array_typesize is not a
9062 // multiple of ptrarith_typesize
9063 if (ptrarith_typesize * ratio == array_typesize)
9064 size *= llvm::APInt(size.getBitWidth(), ratio);
9065 }
9066 }
9067
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009068 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009069 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009070 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009071 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009072
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009073 // For array subscripting the index must be less than size, but for pointer
9074 // arithmetic also allow the index (offset) to be equal to size since
9075 // computing the next address after the end of the array is legal and
9076 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009077 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009078 return;
9079
9080 // Also don't warn for arrays of size 1 which are members of some
9081 // structure. These are often used to approximate flexible arrays in C89
9082 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009083 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009084 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009085
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009086 // Suppress the warning if the subscript expression (as identified by the
9087 // ']' location) and the index expression are both from macro expansions
9088 // within a system header.
9089 if (ASE) {
9090 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9091 ASE->getRBracketLoc());
9092 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9093 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9094 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009095 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009096 return;
9097 }
9098 }
9099
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009100 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009101 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009102 DiagID = diag::warn_array_index_exceeds_bounds;
9103
9104 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9105 PDiag(DiagID) << index.toString(10, true)
9106 << size.toString(10, true)
9107 << (unsigned)size.getLimitedValue(~0U)
9108 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009109 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009110 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009111 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009112 DiagID = diag::warn_ptr_arith_precedes_bounds;
9113 if (index.isNegative()) index = -index;
9114 }
9115
9116 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9117 PDiag(DiagID) << index.toString(10, true)
9118 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009119 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009120
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009121 if (!ND) {
9122 // Try harder to find a NamedDecl to point at in the note.
9123 while (const ArraySubscriptExpr *ASE =
9124 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9125 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9126 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9127 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9128 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9129 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9130 }
9131
Chandler Carruth1af88f12011-02-17 21:10:52 +00009132 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009133 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9134 PDiag(diag::note_array_index_out_of_bounds)
9135 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009136}
9137
Ted Kremenekdf26df72011-03-01 18:41:00 +00009138void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009139 int AllowOnePastEnd = 0;
9140 while (expr) {
9141 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009142 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009143 case Stmt::ArraySubscriptExprClass: {
9144 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009145 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009146 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009147 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009148 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009149 case Stmt::OMPArraySectionExprClass: {
9150 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9151 if (ASE->getLowerBound())
9152 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9153 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9154 return;
9155 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009156 case Stmt::UnaryOperatorClass: {
9157 // Only unwrap the * and & unary operators
9158 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9159 expr = UO->getSubExpr();
9160 switch (UO->getOpcode()) {
9161 case UO_AddrOf:
9162 AllowOnePastEnd++;
9163 break;
9164 case UO_Deref:
9165 AllowOnePastEnd--;
9166 break;
9167 default:
9168 return;
9169 }
9170 break;
9171 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009172 case Stmt::ConditionalOperatorClass: {
9173 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9174 if (const Expr *lhs = cond->getLHS())
9175 CheckArrayAccess(lhs);
9176 if (const Expr *rhs = cond->getRHS())
9177 CheckArrayAccess(rhs);
9178 return;
9179 }
9180 default:
9181 return;
9182 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009183 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009184}
John McCall31168b02011-06-15 23:02:42 +00009185
9186//===--- CHECK: Objective-C retain cycles ----------------------------------//
9187
9188namespace {
9189 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009190 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009191 VarDecl *Variable;
9192 SourceRange Range;
9193 SourceLocation Loc;
9194 bool Indirect;
9195
9196 void setLocsFrom(Expr *e) {
9197 Loc = e->getExprLoc();
9198 Range = e->getSourceRange();
9199 }
9200 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009201} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009202
9203/// Consider whether capturing the given variable can possibly lead to
9204/// a retain cycle.
9205static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009206 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009207 // lifetime. In MRR, it's captured strongly if the variable is
9208 // __block and has an appropriate type.
9209 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9210 return false;
9211
9212 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009213 if (ref)
9214 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009215 return true;
9216}
9217
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009218static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009219 while (true) {
9220 e = e->IgnoreParens();
9221 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9222 switch (cast->getCastKind()) {
9223 case CK_BitCast:
9224 case CK_LValueBitCast:
9225 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009226 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009227 e = cast->getSubExpr();
9228 continue;
9229
John McCall31168b02011-06-15 23:02:42 +00009230 default:
9231 return false;
9232 }
9233 }
9234
9235 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9236 ObjCIvarDecl *ivar = ref->getDecl();
9237 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9238 return false;
9239
9240 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009241 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009242 return false;
9243
9244 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9245 owner.Indirect = true;
9246 return true;
9247 }
9248
9249 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9250 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9251 if (!var) return false;
9252 return considerVariable(var, ref, owner);
9253 }
9254
John McCall31168b02011-06-15 23:02:42 +00009255 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9256 if (member->isArrow()) return false;
9257
9258 // Don't count this as an indirect ownership.
9259 e = member->getBase();
9260 continue;
9261 }
9262
John McCallfe96e0b2011-11-06 09:01:30 +00009263 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9264 // Only pay attention to pseudo-objects on property references.
9265 ObjCPropertyRefExpr *pre
9266 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9267 ->IgnoreParens());
9268 if (!pre) return false;
9269 if (pre->isImplicitProperty()) return false;
9270 ObjCPropertyDecl *property = pre->getExplicitProperty();
9271 if (!property->isRetaining() &&
9272 !(property->getPropertyIvarDecl() &&
9273 property->getPropertyIvarDecl()->getType()
9274 .getObjCLifetime() == Qualifiers::OCL_Strong))
9275 return false;
9276
9277 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009278 if (pre->isSuperReceiver()) {
9279 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9280 if (!owner.Variable)
9281 return false;
9282 owner.Loc = pre->getLocation();
9283 owner.Range = pre->getSourceRange();
9284 return true;
9285 }
John McCallfe96e0b2011-11-06 09:01:30 +00009286 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9287 ->getSourceExpr());
9288 continue;
9289 }
9290
John McCall31168b02011-06-15 23:02:42 +00009291 // Array ivars?
9292
9293 return false;
9294 }
9295}
9296
9297namespace {
9298 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9299 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9300 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009301 Context(Context), Variable(variable), Capturer(nullptr),
9302 VarWillBeReased(false) {}
9303 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009304 VarDecl *Variable;
9305 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009306 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009307
9308 void VisitDeclRefExpr(DeclRefExpr *ref) {
9309 if (ref->getDecl() == Variable && !Capturer)
9310 Capturer = ref;
9311 }
9312
John McCall31168b02011-06-15 23:02:42 +00009313 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9314 if (Capturer) return;
9315 Visit(ref->getBase());
9316 if (Capturer && ref->isFreeIvar())
9317 Capturer = ref;
9318 }
9319
9320 void VisitBlockExpr(BlockExpr *block) {
9321 // Look inside nested blocks
9322 if (block->getBlockDecl()->capturesVariable(Variable))
9323 Visit(block->getBlockDecl()->getBody());
9324 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009325
9326 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9327 if (Capturer) return;
9328 if (OVE->getSourceExpr())
9329 Visit(OVE->getSourceExpr());
9330 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009331 void VisitBinaryOperator(BinaryOperator *BinOp) {
9332 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9333 return;
9334 Expr *LHS = BinOp->getLHS();
9335 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9336 if (DRE->getDecl() != Variable)
9337 return;
9338 if (Expr *RHS = BinOp->getRHS()) {
9339 RHS = RHS->IgnoreParenCasts();
9340 llvm::APSInt Value;
9341 VarWillBeReased =
9342 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9343 }
9344 }
9345 }
John McCall31168b02011-06-15 23:02:42 +00009346 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009347} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009348
9349/// Check whether the given argument is a block which captures a
9350/// variable.
9351static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9352 assert(owner.Variable && owner.Loc.isValid());
9353
9354 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009355
9356 // Look through [^{...} copy] and Block_copy(^{...}).
9357 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9358 Selector Cmd = ME->getSelector();
9359 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9360 e = ME->getInstanceReceiver();
9361 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009362 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009363 e = e->IgnoreParenCasts();
9364 }
9365 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9366 if (CE->getNumArgs() == 1) {
9367 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009368 if (Fn) {
9369 const IdentifierInfo *FnI = Fn->getIdentifier();
9370 if (FnI && FnI->isStr("_Block_copy")) {
9371 e = CE->getArg(0)->IgnoreParenCasts();
9372 }
9373 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009374 }
9375 }
9376
John McCall31168b02011-06-15 23:02:42 +00009377 BlockExpr *block = dyn_cast<BlockExpr>(e);
9378 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009379 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009380
9381 FindCaptureVisitor visitor(S.Context, owner.Variable);
9382 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009383 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009384}
9385
9386static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9387 RetainCycleOwner &owner) {
9388 assert(capturer);
9389 assert(owner.Variable && owner.Loc.isValid());
9390
9391 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9392 << owner.Variable << capturer->getSourceRange();
9393 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9394 << owner.Indirect << owner.Range;
9395}
9396
9397/// Check for a keyword selector that starts with the word 'add' or
9398/// 'set'.
9399static bool isSetterLikeSelector(Selector sel) {
9400 if (sel.isUnarySelector()) return false;
9401
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009402 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009403 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009404 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009405 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009406 else if (str.startswith("add")) {
9407 // Specially whitelist 'addOperationWithBlock:'.
9408 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9409 return false;
9410 str = str.substr(3);
9411 }
John McCall31168b02011-06-15 23:02:42 +00009412 else
9413 return false;
9414
9415 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009416 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009417}
9418
Benjamin Kramer3a743452015-03-09 15:03:32 +00009419static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9420 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009421 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9422 Message->getReceiverInterface(),
9423 NSAPI::ClassId_NSMutableArray);
9424 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009425 return None;
9426 }
9427
9428 Selector Sel = Message->getSelector();
9429
9430 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9431 S.NSAPIObj->getNSArrayMethodKind(Sel);
9432 if (!MKOpt) {
9433 return None;
9434 }
9435
9436 NSAPI::NSArrayMethodKind MK = *MKOpt;
9437
9438 switch (MK) {
9439 case NSAPI::NSMutableArr_addObject:
9440 case NSAPI::NSMutableArr_insertObjectAtIndex:
9441 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9442 return 0;
9443 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9444 return 1;
9445
9446 default:
9447 return None;
9448 }
9449
9450 return None;
9451}
9452
9453static
9454Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9455 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009456 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9457 Message->getReceiverInterface(),
9458 NSAPI::ClassId_NSMutableDictionary);
9459 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009460 return None;
9461 }
9462
9463 Selector Sel = Message->getSelector();
9464
9465 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9466 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9467 if (!MKOpt) {
9468 return None;
9469 }
9470
9471 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9472
9473 switch (MK) {
9474 case NSAPI::NSMutableDict_setObjectForKey:
9475 case NSAPI::NSMutableDict_setValueForKey:
9476 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9477 return 0;
9478
9479 default:
9480 return None;
9481 }
9482
9483 return None;
9484}
9485
9486static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009487 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9488 Message->getReceiverInterface(),
9489 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009490
Alex Denisov5dfac812015-08-06 04:51:14 +00009491 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9492 Message->getReceiverInterface(),
9493 NSAPI::ClassId_NSMutableOrderedSet);
9494 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009495 return None;
9496 }
9497
9498 Selector Sel = Message->getSelector();
9499
9500 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9501 if (!MKOpt) {
9502 return None;
9503 }
9504
9505 NSAPI::NSSetMethodKind MK = *MKOpt;
9506
9507 switch (MK) {
9508 case NSAPI::NSMutableSet_addObject:
9509 case NSAPI::NSOrderedSet_setObjectAtIndex:
9510 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9511 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9512 return 0;
9513 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9514 return 1;
9515 }
9516
9517 return None;
9518}
9519
9520void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9521 if (!Message->isInstanceMessage()) {
9522 return;
9523 }
9524
9525 Optional<int> ArgOpt;
9526
9527 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9528 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9529 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9530 return;
9531 }
9532
9533 int ArgIndex = *ArgOpt;
9534
Alex Denisove1d882c2015-03-04 17:55:52 +00009535 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9536 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9537 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9538 }
9539
Alex Denisov5dfac812015-08-06 04:51:14 +00009540 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009541 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009542 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009543 Diag(Message->getSourceRange().getBegin(),
9544 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009545 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009546 }
9547 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009548 } else {
9549 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9550
9551 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9552 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9553 }
9554
9555 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9556 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9557 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9558 ValueDecl *Decl = ReceiverRE->getDecl();
9559 Diag(Message->getSourceRange().getBegin(),
9560 diag::warn_objc_circular_container)
9561 << Decl->getName() << Decl->getName();
9562 if (!ArgRE->isObjCSelfExpr()) {
9563 Diag(Decl->getLocation(),
9564 diag::note_objc_circular_container_declared_here)
9565 << Decl->getName();
9566 }
9567 }
9568 }
9569 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9570 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9571 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9572 ObjCIvarDecl *Decl = IvarRE->getDecl();
9573 Diag(Message->getSourceRange().getBegin(),
9574 diag::warn_objc_circular_container)
9575 << Decl->getName() << Decl->getName();
9576 Diag(Decl->getLocation(),
9577 diag::note_objc_circular_container_declared_here)
9578 << Decl->getName();
9579 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009580 }
9581 }
9582 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009583}
9584
John McCall31168b02011-06-15 23:02:42 +00009585/// Check a message send to see if it's likely to cause a retain cycle.
9586void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9587 // Only check instance methods whose selector looks like a setter.
9588 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9589 return;
9590
9591 // Try to find a variable that the receiver is strongly owned by.
9592 RetainCycleOwner owner;
9593 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009594 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009595 return;
9596 } else {
9597 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9598 owner.Variable = getCurMethodDecl()->getSelfDecl();
9599 owner.Loc = msg->getSuperLoc();
9600 owner.Range = msg->getSuperLoc();
9601 }
9602
9603 // Check whether the receiver is captured by any of the arguments.
9604 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9605 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9606 return diagnoseRetainCycle(*this, capturer, owner);
9607}
9608
9609/// Check a property assign to see if it's likely to cause a retain cycle.
9610void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9611 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009612 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009613 return;
9614
9615 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9616 diagnoseRetainCycle(*this, capturer, owner);
9617}
9618
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009619void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9620 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009621 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009622 return;
9623
9624 // Because we don't have an expression for the variable, we have to set the
9625 // location explicitly here.
9626 Owner.Loc = Var->getLocation();
9627 Owner.Range = Var->getSourceRange();
9628
9629 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9630 diagnoseRetainCycle(*this, Capturer, Owner);
9631}
9632
Ted Kremenek9304da92012-12-21 08:04:28 +00009633static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9634 Expr *RHS, bool isProperty) {
9635 // Check if RHS is an Objective-C object literal, which also can get
9636 // immediately zapped in a weak reference. Note that we explicitly
9637 // allow ObjCStringLiterals, since those are designed to never really die.
9638 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009639
Ted Kremenek64873352012-12-21 22:46:35 +00009640 // This enum needs to match with the 'select' in
9641 // warn_objc_arc_literal_assign (off-by-1).
9642 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9643 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9644 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009645
9646 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009647 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009648 << (isProperty ? 0 : 1)
9649 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009650
9651 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009652}
9653
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009654static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9655 Qualifiers::ObjCLifetime LT,
9656 Expr *RHS, bool isProperty) {
9657 // Strip off any implicit cast added to get to the one ARC-specific.
9658 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9659 if (cast->getCastKind() == CK_ARCConsumeObject) {
9660 S.Diag(Loc, diag::warn_arc_retained_assign)
9661 << (LT == Qualifiers::OCL_ExplicitNone)
9662 << (isProperty ? 0 : 1)
9663 << RHS->getSourceRange();
9664 return true;
9665 }
9666 RHS = cast->getSubExpr();
9667 }
9668
9669 if (LT == Qualifiers::OCL_Weak &&
9670 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9671 return true;
9672
9673 return false;
9674}
9675
Ted Kremenekb36234d2012-12-21 08:04:20 +00009676bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9677 QualType LHS, Expr *RHS) {
9678 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9679
9680 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9681 return false;
9682
9683 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9684 return true;
9685
9686 return false;
9687}
9688
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009689void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9690 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009691 QualType LHSType;
9692 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009693 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009694 ObjCPropertyRefExpr *PRE
9695 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9696 if (PRE && !PRE->isImplicitProperty()) {
9697 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9698 if (PD)
9699 LHSType = PD->getType();
9700 }
9701
9702 if (LHSType.isNull())
9703 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009704
9705 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9706
9707 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009708 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009709 getCurFunction()->markSafeWeakUse(LHS);
9710 }
9711
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009712 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9713 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009714
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009715 // FIXME. Check for other life times.
9716 if (LT != Qualifiers::OCL_None)
9717 return;
9718
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009719 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009720 if (PRE->isImplicitProperty())
9721 return;
9722 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9723 if (!PD)
9724 return;
9725
Bill Wendling44426052012-12-20 19:22:21 +00009726 unsigned Attributes = PD->getPropertyAttributes();
9727 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009728 // when 'assign' attribute was not explicitly specified
9729 // by user, ignore it and rely on property type itself
9730 // for lifetime info.
9731 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9732 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9733 LHSType->isObjCRetainableType())
9734 return;
9735
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009736 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009737 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009738 Diag(Loc, diag::warn_arc_retained_property_assign)
9739 << RHS->getSourceRange();
9740 return;
9741 }
9742 RHS = cast->getSubExpr();
9743 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009744 }
Bill Wendling44426052012-12-20 19:22:21 +00009745 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009746 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9747 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009748 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009749 }
9750}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009751
9752//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9753
9754namespace {
9755bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9756 SourceLocation StmtLoc,
9757 const NullStmt *Body) {
9758 // Do not warn if the body is a macro that expands to nothing, e.g:
9759 //
9760 // #define CALL(x)
9761 // if (condition)
9762 // CALL(0);
9763 //
9764 if (Body->hasLeadingEmptyMacro())
9765 return false;
9766
9767 // Get line numbers of statement and body.
9768 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009769 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009770 &StmtLineInvalid);
9771 if (StmtLineInvalid)
9772 return false;
9773
9774 bool BodyLineInvalid;
9775 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9776 &BodyLineInvalid);
9777 if (BodyLineInvalid)
9778 return false;
9779
9780 // Warn if null statement and body are on the same line.
9781 if (StmtLine != BodyLine)
9782 return false;
9783
9784 return true;
9785}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009786} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009787
9788void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9789 const Stmt *Body,
9790 unsigned DiagID) {
9791 // Since this is a syntactic check, don't emit diagnostic for template
9792 // instantiations, this just adds noise.
9793 if (CurrentInstantiationScope)
9794 return;
9795
9796 // The body should be a null statement.
9797 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9798 if (!NBody)
9799 return;
9800
9801 // Do the usual checks.
9802 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9803 return;
9804
9805 Diag(NBody->getSemiLoc(), DiagID);
9806 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9807}
9808
9809void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9810 const Stmt *PossibleBody) {
9811 assert(!CurrentInstantiationScope); // Ensured by caller
9812
9813 SourceLocation StmtLoc;
9814 const Stmt *Body;
9815 unsigned DiagID;
9816 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9817 StmtLoc = FS->getRParenLoc();
9818 Body = FS->getBody();
9819 DiagID = diag::warn_empty_for_body;
9820 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9821 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9822 Body = WS->getBody();
9823 DiagID = diag::warn_empty_while_body;
9824 } else
9825 return; // Neither `for' nor `while'.
9826
9827 // The body should be a null statement.
9828 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9829 if (!NBody)
9830 return;
9831
9832 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009833 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009834 return;
9835
9836 // Do the usual checks.
9837 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9838 return;
9839
9840 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9841 // noise level low, emit diagnostics only if for/while is followed by a
9842 // CompoundStmt, e.g.:
9843 // for (int i = 0; i < n; i++);
9844 // {
9845 // a(i);
9846 // }
9847 // or if for/while is followed by a statement with more indentation
9848 // than for/while itself:
9849 // for (int i = 0; i < n; i++);
9850 // a(i);
9851 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9852 if (!ProbableTypo) {
9853 bool BodyColInvalid;
9854 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9855 PossibleBody->getLocStart(),
9856 &BodyColInvalid);
9857 if (BodyColInvalid)
9858 return;
9859
9860 bool StmtColInvalid;
9861 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9862 S->getLocStart(),
9863 &StmtColInvalid);
9864 if (StmtColInvalid)
9865 return;
9866
9867 if (BodyCol > StmtCol)
9868 ProbableTypo = true;
9869 }
9870
9871 if (ProbableTypo) {
9872 Diag(NBody->getSemiLoc(), DiagID);
9873 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9874 }
9875}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009876
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009877//===--- CHECK: Warn on self move with std::move. -------------------------===//
9878
9879/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9880void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9881 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009882 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9883 return;
9884
9885 if (!ActiveTemplateInstantiations.empty())
9886 return;
9887
9888 // Strip parens and casts away.
9889 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9890 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9891
9892 // Check for a call expression
9893 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9894 if (!CE || CE->getNumArgs() != 1)
9895 return;
9896
9897 // Check for a call to std::move
9898 const FunctionDecl *FD = CE->getDirectCallee();
9899 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9900 !FD->getIdentifier()->isStr("move"))
9901 return;
9902
9903 // Get argument from std::move
9904 RHSExpr = CE->getArg(0);
9905
9906 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9907 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9908
9909 // Two DeclRefExpr's, check that the decls are the same.
9910 if (LHSDeclRef && RHSDeclRef) {
9911 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9912 return;
9913 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9914 RHSDeclRef->getDecl()->getCanonicalDecl())
9915 return;
9916
9917 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9918 << LHSExpr->getSourceRange()
9919 << RHSExpr->getSourceRange();
9920 return;
9921 }
9922
9923 // Member variables require a different approach to check for self moves.
9924 // MemberExpr's are the same if every nested MemberExpr refers to the same
9925 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9926 // the base Expr's are CXXThisExpr's.
9927 const Expr *LHSBase = LHSExpr;
9928 const Expr *RHSBase = RHSExpr;
9929 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9930 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9931 if (!LHSME || !RHSME)
9932 return;
9933
9934 while (LHSME && RHSME) {
9935 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9936 RHSME->getMemberDecl()->getCanonicalDecl())
9937 return;
9938
9939 LHSBase = LHSME->getBase();
9940 RHSBase = RHSME->getBase();
9941 LHSME = dyn_cast<MemberExpr>(LHSBase);
9942 RHSME = dyn_cast<MemberExpr>(RHSBase);
9943 }
9944
9945 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9946 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9947 if (LHSDeclRef && RHSDeclRef) {
9948 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9949 return;
9950 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9951 RHSDeclRef->getDecl()->getCanonicalDecl())
9952 return;
9953
9954 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9955 << LHSExpr->getSourceRange()
9956 << RHSExpr->getSourceRange();
9957 return;
9958 }
9959
9960 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9961 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9962 << LHSExpr->getSourceRange()
9963 << RHSExpr->getSourceRange();
9964}
9965
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009966//===--- Layout compatibility ----------------------------------------------//
9967
9968namespace {
9969
9970bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9971
9972/// \brief Check if two enumeration types are layout-compatible.
9973bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9974 // C++11 [dcl.enum] p8:
9975 // Two enumeration types are layout-compatible if they have the same
9976 // underlying type.
9977 return ED1->isComplete() && ED2->isComplete() &&
9978 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9979}
9980
9981/// \brief Check if two fields are layout-compatible.
9982bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9983 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9984 return false;
9985
9986 if (Field1->isBitField() != Field2->isBitField())
9987 return false;
9988
9989 if (Field1->isBitField()) {
9990 // Make sure that the bit-fields are the same length.
9991 unsigned Bits1 = Field1->getBitWidthValue(C);
9992 unsigned Bits2 = Field2->getBitWidthValue(C);
9993
9994 if (Bits1 != Bits2)
9995 return false;
9996 }
9997
9998 return true;
9999}
10000
10001/// \brief Check if two standard-layout structs are layout-compatible.
10002/// (C++11 [class.mem] p17)
10003bool isLayoutCompatibleStruct(ASTContext &C,
10004 RecordDecl *RD1,
10005 RecordDecl *RD2) {
10006 // If both records are C++ classes, check that base classes match.
10007 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10008 // If one of records is a CXXRecordDecl we are in C++ mode,
10009 // thus the other one is a CXXRecordDecl, too.
10010 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10011 // Check number of base classes.
10012 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10013 return false;
10014
10015 // Check the base classes.
10016 for (CXXRecordDecl::base_class_const_iterator
10017 Base1 = D1CXX->bases_begin(),
10018 BaseEnd1 = D1CXX->bases_end(),
10019 Base2 = D2CXX->bases_begin();
10020 Base1 != BaseEnd1;
10021 ++Base1, ++Base2) {
10022 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10023 return false;
10024 }
10025 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10026 // If only RD2 is a C++ class, it should have zero base classes.
10027 if (D2CXX->getNumBases() > 0)
10028 return false;
10029 }
10030
10031 // Check the fields.
10032 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10033 Field2End = RD2->field_end(),
10034 Field1 = RD1->field_begin(),
10035 Field1End = RD1->field_end();
10036 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10037 if (!isLayoutCompatible(C, *Field1, *Field2))
10038 return false;
10039 }
10040 if (Field1 != Field1End || Field2 != Field2End)
10041 return false;
10042
10043 return true;
10044}
10045
10046/// \brief Check if two standard-layout unions are layout-compatible.
10047/// (C++11 [class.mem] p18)
10048bool isLayoutCompatibleUnion(ASTContext &C,
10049 RecordDecl *RD1,
10050 RecordDecl *RD2) {
10051 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010052 for (auto *Field2 : RD2->fields())
10053 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010054
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010055 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010056 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10057 I = UnmatchedFields.begin(),
10058 E = UnmatchedFields.end();
10059
10060 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010061 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010062 bool Result = UnmatchedFields.erase(*I);
10063 (void) Result;
10064 assert(Result);
10065 break;
10066 }
10067 }
10068 if (I == E)
10069 return false;
10070 }
10071
10072 return UnmatchedFields.empty();
10073}
10074
10075bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10076 if (RD1->isUnion() != RD2->isUnion())
10077 return false;
10078
10079 if (RD1->isUnion())
10080 return isLayoutCompatibleUnion(C, RD1, RD2);
10081 else
10082 return isLayoutCompatibleStruct(C, RD1, RD2);
10083}
10084
10085/// \brief Check if two types are layout-compatible in C++11 sense.
10086bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10087 if (T1.isNull() || T2.isNull())
10088 return false;
10089
10090 // C++11 [basic.types] p11:
10091 // If two types T1 and T2 are the same type, then T1 and T2 are
10092 // layout-compatible types.
10093 if (C.hasSameType(T1, T2))
10094 return true;
10095
10096 T1 = T1.getCanonicalType().getUnqualifiedType();
10097 T2 = T2.getCanonicalType().getUnqualifiedType();
10098
10099 const Type::TypeClass TC1 = T1->getTypeClass();
10100 const Type::TypeClass TC2 = T2->getTypeClass();
10101
10102 if (TC1 != TC2)
10103 return false;
10104
10105 if (TC1 == Type::Enum) {
10106 return isLayoutCompatible(C,
10107 cast<EnumType>(T1)->getDecl(),
10108 cast<EnumType>(T2)->getDecl());
10109 } else if (TC1 == Type::Record) {
10110 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10111 return false;
10112
10113 return isLayoutCompatible(C,
10114 cast<RecordType>(T1)->getDecl(),
10115 cast<RecordType>(T2)->getDecl());
10116 }
10117
10118 return false;
10119}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010120} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010121
10122//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10123
10124namespace {
10125/// \brief Given a type tag expression find the type tag itself.
10126///
10127/// \param TypeExpr Type tag expression, as it appears in user's code.
10128///
10129/// \param VD Declaration of an identifier that appears in a type tag.
10130///
10131/// \param MagicValue Type tag magic value.
10132bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10133 const ValueDecl **VD, uint64_t *MagicValue) {
10134 while(true) {
10135 if (!TypeExpr)
10136 return false;
10137
10138 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10139
10140 switch (TypeExpr->getStmtClass()) {
10141 case Stmt::UnaryOperatorClass: {
10142 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10143 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10144 TypeExpr = UO->getSubExpr();
10145 continue;
10146 }
10147 return false;
10148 }
10149
10150 case Stmt::DeclRefExprClass: {
10151 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10152 *VD = DRE->getDecl();
10153 return true;
10154 }
10155
10156 case Stmt::IntegerLiteralClass: {
10157 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10158 llvm::APInt MagicValueAPInt = IL->getValue();
10159 if (MagicValueAPInt.getActiveBits() <= 64) {
10160 *MagicValue = MagicValueAPInt.getZExtValue();
10161 return true;
10162 } else
10163 return false;
10164 }
10165
10166 case Stmt::BinaryConditionalOperatorClass:
10167 case Stmt::ConditionalOperatorClass: {
10168 const AbstractConditionalOperator *ACO =
10169 cast<AbstractConditionalOperator>(TypeExpr);
10170 bool Result;
10171 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10172 if (Result)
10173 TypeExpr = ACO->getTrueExpr();
10174 else
10175 TypeExpr = ACO->getFalseExpr();
10176 continue;
10177 }
10178 return false;
10179 }
10180
10181 case Stmt::BinaryOperatorClass: {
10182 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10183 if (BO->getOpcode() == BO_Comma) {
10184 TypeExpr = BO->getRHS();
10185 continue;
10186 }
10187 return false;
10188 }
10189
10190 default:
10191 return false;
10192 }
10193 }
10194}
10195
10196/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10197///
10198/// \param TypeExpr Expression that specifies a type tag.
10199///
10200/// \param MagicValues Registered magic values.
10201///
10202/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10203/// kind.
10204///
10205/// \param TypeInfo Information about the corresponding C type.
10206///
10207/// \returns true if the corresponding C type was found.
10208bool GetMatchingCType(
10209 const IdentifierInfo *ArgumentKind,
10210 const Expr *TypeExpr, const ASTContext &Ctx,
10211 const llvm::DenseMap<Sema::TypeTagMagicValue,
10212 Sema::TypeTagData> *MagicValues,
10213 bool &FoundWrongKind,
10214 Sema::TypeTagData &TypeInfo) {
10215 FoundWrongKind = false;
10216
10217 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010218 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010219
10220 uint64_t MagicValue;
10221
10222 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10223 return false;
10224
10225 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010226 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010227 if (I->getArgumentKind() != ArgumentKind) {
10228 FoundWrongKind = true;
10229 return false;
10230 }
10231 TypeInfo.Type = I->getMatchingCType();
10232 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10233 TypeInfo.MustBeNull = I->getMustBeNull();
10234 return true;
10235 }
10236 return false;
10237 }
10238
10239 if (!MagicValues)
10240 return false;
10241
10242 llvm::DenseMap<Sema::TypeTagMagicValue,
10243 Sema::TypeTagData>::const_iterator I =
10244 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10245 if (I == MagicValues->end())
10246 return false;
10247
10248 TypeInfo = I->second;
10249 return true;
10250}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010251} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010252
10253void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10254 uint64_t MagicValue, QualType Type,
10255 bool LayoutCompatible,
10256 bool MustBeNull) {
10257 if (!TypeTagForDatatypeMagicValues)
10258 TypeTagForDatatypeMagicValues.reset(
10259 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10260
10261 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10262 (*TypeTagForDatatypeMagicValues)[Magic] =
10263 TypeTagData(Type, LayoutCompatible, MustBeNull);
10264}
10265
10266namespace {
10267bool IsSameCharType(QualType T1, QualType T2) {
10268 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10269 if (!BT1)
10270 return false;
10271
10272 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10273 if (!BT2)
10274 return false;
10275
10276 BuiltinType::Kind T1Kind = BT1->getKind();
10277 BuiltinType::Kind T2Kind = BT2->getKind();
10278
10279 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10280 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10281 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10282 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10283}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010284} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010285
10286void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10287 const Expr * const *ExprArgs) {
10288 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10289 bool IsPointerAttr = Attr->getIsPointer();
10290
10291 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10292 bool FoundWrongKind;
10293 TypeTagData TypeInfo;
10294 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10295 TypeTagForDatatypeMagicValues.get(),
10296 FoundWrongKind, TypeInfo)) {
10297 if (FoundWrongKind)
10298 Diag(TypeTagExpr->getExprLoc(),
10299 diag::warn_type_tag_for_datatype_wrong_kind)
10300 << TypeTagExpr->getSourceRange();
10301 return;
10302 }
10303
10304 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10305 if (IsPointerAttr) {
10306 // Skip implicit cast of pointer to `void *' (as a function argument).
10307 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010308 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010309 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010310 ArgumentExpr = ICE->getSubExpr();
10311 }
10312 QualType ArgumentType = ArgumentExpr->getType();
10313
10314 // Passing a `void*' pointer shouldn't trigger a warning.
10315 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10316 return;
10317
10318 if (TypeInfo.MustBeNull) {
10319 // Type tag with matching void type requires a null pointer.
10320 if (!ArgumentExpr->isNullPointerConstant(Context,
10321 Expr::NPC_ValueDependentIsNotNull)) {
10322 Diag(ArgumentExpr->getExprLoc(),
10323 diag::warn_type_safety_null_pointer_required)
10324 << ArgumentKind->getName()
10325 << ArgumentExpr->getSourceRange()
10326 << TypeTagExpr->getSourceRange();
10327 }
10328 return;
10329 }
10330
10331 QualType RequiredType = TypeInfo.Type;
10332 if (IsPointerAttr)
10333 RequiredType = Context.getPointerType(RequiredType);
10334
10335 bool mismatch = false;
10336 if (!TypeInfo.LayoutCompatible) {
10337 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10338
10339 // C++11 [basic.fundamental] p1:
10340 // Plain char, signed char, and unsigned char are three distinct types.
10341 //
10342 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10343 // char' depending on the current char signedness mode.
10344 if (mismatch)
10345 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10346 RequiredType->getPointeeType())) ||
10347 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10348 mismatch = false;
10349 } else
10350 if (IsPointerAttr)
10351 mismatch = !isLayoutCompatible(Context,
10352 ArgumentType->getPointeeType(),
10353 RequiredType->getPointeeType());
10354 else
10355 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10356
10357 if (mismatch)
10358 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010359 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010360 << TypeInfo.LayoutCompatible << RequiredType
10361 << ArgumentExpr->getSourceRange()
10362 << TypeTagExpr->getSourceRange();
10363}