blob: 37474b9edb0f7b85ca196a107f49ef3f5a2ec58a [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"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000039#include "llvm/Support/Format.h"
40#include "llvm/Support/Locale.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000041#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000043#include <limits>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000044
Chris Lattnerb87b1b32007-08-10 20:18:51 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000047
Chris Lattnera26fb342009-02-18 17:49:48 +000048SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
49 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000050 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
51 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000052}
53
John McCallbebede42011-02-26 05:39:39 +000054/// Checks that a call expression's argument count is the desired number.
55/// This is useful when doing custom type-checking. Returns true on error.
56static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
57 unsigned argCount = call->getNumArgs();
58 if (argCount == desiredArgCount) return false;
59
60 if (argCount < desiredArgCount)
61 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
62 << 0 /*function call*/ << desiredArgCount << argCount
63 << call->getSourceRange();
64
65 // Highlight all the excess arguments.
66 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
67 call->getArg(argCount - 1)->getLocEnd());
68
69 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
70 << 0 /*function call*/ << desiredArgCount << argCount
71 << call->getArg(1)->getSourceRange();
72}
73
Julien Lerouge4a5b4442012-04-28 17:39:16 +000074/// Check that the first argument to __builtin_annotation is an integer
75/// and the second argument is a non-wide string literal.
76static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
77 if (checkArgCount(S, TheCall, 2))
78 return true;
79
80 // First argument should be an integer.
81 Expr *ValArg = TheCall->getArg(0);
82 QualType Ty = ValArg->getType();
83 if (!Ty->isIntegerType()) {
84 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
85 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000086 return true;
87 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000088
89 // Second argument should be a constant string.
90 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
91 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
92 if (!Literal || !Literal->isAscii()) {
93 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
94 << StrArg->getSourceRange();
95 return true;
96 }
97
98 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000099 return false;
100}
101
Richard Smith6cbd65d2013-07-11 02:27:57 +0000102/// Check that the argument to __builtin_addressof is a glvalue, and set the
103/// result type to the corresponding pointer type.
104static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
105 if (checkArgCount(S, TheCall, 1))
106 return true;
107
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000108 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000109 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
110 if (ResultType.isNull())
111 return true;
112
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000113 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000114 TheCall->setType(ResultType);
115 return false;
116}
117
John McCall03107a42015-10-29 20:48:01 +0000118static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
119 if (checkArgCount(S, TheCall, 3))
120 return true;
121
122 // First two arguments should be integers.
123 for (unsigned I = 0; I < 2; ++I) {
124 Expr *Arg = TheCall->getArg(I);
125 QualType Ty = Arg->getType();
126 if (!Ty->isIntegerType()) {
127 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
128 << Ty << Arg->getSourceRange();
129 return true;
130 }
131 }
132
133 // Third argument should be a pointer to a non-const integer.
134 // IRGen correctly handles volatile, restrict, and address spaces, and
135 // the other qualifiers aren't possible.
136 {
137 Expr *Arg = TheCall->getArg(2);
138 QualType Ty = Arg->getType();
139 const auto *PtrTy = Ty->getAs<PointerType>();
140 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
141 !PtrTy->getPointeeType().isConstQualified())) {
142 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
143 << Ty << Arg->getSourceRange();
144 return true;
145 }
146 }
147
148 return false;
149}
150
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000151static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
152 CallExpr *TheCall, unsigned SizeIdx,
153 unsigned DstSizeIdx) {
154 if (TheCall->getNumArgs() <= SizeIdx ||
155 TheCall->getNumArgs() <= DstSizeIdx)
156 return;
157
158 const Expr *SizeArg = TheCall->getArg(SizeIdx);
159 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
160
161 llvm::APSInt Size, DstSize;
162
163 // find out if both sizes are known at compile time
164 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
165 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
166 return;
167
168 if (Size.ule(DstSize))
169 return;
170
171 // confirmed overflow so generate the diagnostic.
172 IdentifierInfo *FnName = FDecl->getIdentifier();
173 SourceLocation SL = TheCall->getLocStart();
174 SourceRange SR = TheCall->getSourceRange();
175
176 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
177}
178
Peter Collingbournef7706832014-12-12 23:41:25 +0000179static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
180 if (checkArgCount(S, BuiltinCall, 2))
181 return true;
182
183 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
184 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
185 Expr *Call = BuiltinCall->getArg(0);
186 Expr *Chain = BuiltinCall->getArg(1);
187
188 if (Call->getStmtClass() != Stmt::CallExprClass) {
189 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
190 << Call->getSourceRange();
191 return true;
192 }
193
194 auto CE = cast<CallExpr>(Call);
195 if (CE->getCallee()->getType()->isBlockPointerType()) {
196 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
197 << Call->getSourceRange();
198 return true;
199 }
200
201 const Decl *TargetDecl = CE->getCalleeDecl();
202 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
203 if (FD->getBuiltinID()) {
204 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
205 << Call->getSourceRange();
206 return true;
207 }
208
209 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
210 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
211 << Call->getSourceRange();
212 return true;
213 }
214
215 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
216 if (ChainResult.isInvalid())
217 return true;
218 if (!ChainResult.get()->getType()->isPointerType()) {
219 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
220 << Chain->getSourceRange();
221 return true;
222 }
223
David Majnemerced8bdf2015-02-25 17:36:15 +0000224 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000225 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
226 QualType BuiltinTy = S.Context.getFunctionType(
227 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
228 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
229
230 Builtin =
231 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
232
233 BuiltinCall->setType(CE->getType());
234 BuiltinCall->setValueKind(CE->getValueKind());
235 BuiltinCall->setObjectKind(CE->getObjectKind());
236 BuiltinCall->setCallee(Builtin);
237 BuiltinCall->setArg(1, ChainResult.get());
238
239 return false;
240}
241
Reid Kleckner1d59f992015-01-22 01:36:17 +0000242static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
243 Scope::ScopeFlags NeededScopeFlags,
244 unsigned DiagID) {
245 // Scopes aren't available during instantiation. Fortunately, builtin
246 // functions cannot be template args so they cannot be formed through template
247 // instantiation. Therefore checking once during the parse is sufficient.
248 if (!SemaRef.ActiveTemplateInstantiations.empty())
249 return false;
250
251 Scope *S = SemaRef.getCurScope();
252 while (S && !S->isSEHExceptScope())
253 S = S->getParent();
254 if (!S || !(S->getFlags() & NeededScopeFlags)) {
255 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
256 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
257 << DRE->getDecl()->getIdentifier();
258 return true;
259 }
260
261 return false;
262}
263
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000264/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000265static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000266 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000267}
268
269/// Returns true if pipe element type is different from the pointer.
270static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
271 const Expr *Arg0 = Call->getArg(0);
272 // First argument type should always be pipe.
273 if (!Arg0->getType()->isPipeType()) {
274 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000275 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000276 return true;
277 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000278 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000279 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
280 // Validates the access qualifier is compatible with the call.
281 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
282 // read_only and write_only, and assumed to be read_only if no qualifier is
283 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000284 switch (Call->getDirectCallee()->getBuiltinID()) {
285 case Builtin::BIread_pipe:
286 case Builtin::BIreserve_read_pipe:
287 case Builtin::BIcommit_read_pipe:
288 case Builtin::BIwork_group_reserve_read_pipe:
289 case Builtin::BIsub_group_reserve_read_pipe:
290 case Builtin::BIwork_group_commit_read_pipe:
291 case Builtin::BIsub_group_commit_read_pipe:
292 if (!(!AccessQual || AccessQual->isReadOnly())) {
293 S.Diag(Arg0->getLocStart(),
294 diag::err_opencl_builtin_pipe_invalid_access_modifier)
295 << "read_only" << Arg0->getSourceRange();
296 return true;
297 }
298 break;
299 case Builtin::BIwrite_pipe:
300 case Builtin::BIreserve_write_pipe:
301 case Builtin::BIcommit_write_pipe:
302 case Builtin::BIwork_group_reserve_write_pipe:
303 case Builtin::BIsub_group_reserve_write_pipe:
304 case Builtin::BIwork_group_commit_write_pipe:
305 case Builtin::BIsub_group_commit_write_pipe:
306 if (!(AccessQual && AccessQual->isWriteOnly())) {
307 S.Diag(Arg0->getLocStart(),
308 diag::err_opencl_builtin_pipe_invalid_access_modifier)
309 << "write_only" << Arg0->getSourceRange();
310 return true;
311 }
312 break;
313 default:
314 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000315 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000316 return false;
317}
318
319/// Returns true if pipe element type is different from the pointer.
320static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
321 const Expr *Arg0 = Call->getArg(0);
322 const Expr *ArgIdx = Call->getArg(Idx);
323 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000324 const QualType EltTy = PipeTy->getElementType();
325 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000326 // The Idx argument should be a pointer and the type of the pointer and
327 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000328 if (!ArgTy ||
329 !S.Context.hasSameType(
330 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000331 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000332 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000333 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000334 return true;
335 }
336 return false;
337}
338
339// \brief Performs semantic analysis for the read/write_pipe call.
340// \param S Reference to the semantic analyzer.
341// \param Call A pointer to the builtin call.
342// \return True if a semantic error has been found, false otherwise.
343static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000344 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
345 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000346 switch (Call->getNumArgs()) {
347 case 2: {
348 if (checkOpenCLPipeArg(S, Call))
349 return true;
350 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000351 // read/write_pipe(pipe T, T*).
352 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000353 if (checkOpenCLPipePacketType(S, Call, 1))
354 return true;
355 } break;
356
357 case 4: {
358 if (checkOpenCLPipeArg(S, Call))
359 return true;
360 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000361 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
362 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000363 if (!Call->getArg(1)->getType()->isReserveIDT()) {
364 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000365 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000366 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000367 return true;
368 }
369
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000370 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000371 const Expr *Arg2 = Call->getArg(2);
372 if (!Arg2->getType()->isIntegerType() &&
373 !Arg2->getType()->isUnsignedIntegerType()) {
374 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000375 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000376 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000377 return true;
378 }
379
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000380 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000381 if (checkOpenCLPipePacketType(S, Call, 3))
382 return true;
383 } break;
384 default:
385 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000386 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000387 return true;
388 }
389
390 return false;
391}
392
393// \brief Performs a semantic analysis on the {work_group_/sub_group_
394// /_}reserve_{read/write}_pipe
395// \param S Reference to the semantic analyzer.
396// \param Call The call to the builtin function to be analyzed.
397// \return True if a semantic error was found, false otherwise.
398static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
399 if (checkArgCount(S, Call, 2))
400 return true;
401
402 if (checkOpenCLPipeArg(S, Call))
403 return true;
404
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000405 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000406 if (!Call->getArg(1)->getType()->isIntegerType() &&
407 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
408 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000409 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000410 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000411 return true;
412 }
413
414 return false;
415}
416
417// \brief Performs a semantic analysis on {work_group_/sub_group_
418// /_}commit_{read/write}_pipe
419// \param S Reference to the semantic analyzer.
420// \param Call The call to the builtin function to be analyzed.
421// \return True if a semantic error was found, false otherwise.
422static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
423 if (checkArgCount(S, Call, 2))
424 return true;
425
426 if (checkOpenCLPipeArg(S, Call))
427 return true;
428
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000429 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000430 if (!Call->getArg(1)->getType()->isReserveIDT()) {
431 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000432 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000433 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000434 return true;
435 }
436
437 return false;
438}
439
440// \brief Performs a semantic analysis on the call to built-in Pipe
441// Query Functions.
442// \param S Reference to the semantic analyzer.
443// \param Call The call to the builtin function to be analyzed.
444// \return True if a semantic error was found, false otherwise.
445static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
446 if (checkArgCount(S, Call, 1))
447 return true;
448
449 if (!Call->getArg(0)->getType()->isPipeType()) {
450 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000451 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000452 return true;
453 }
454
455 return false;
456}
457
Yaxun Liuf7449a12016-05-20 19:54:38 +0000458// \brief Performs semantic analysis for the to_global/local/private call.
459// \param S Reference to the semantic analyzer.
460// \param BuiltinID ID of the builtin function.
461// \param Call A pointer to the builtin call.
462// \return True if a semantic error has been found, false otherwise.
463static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
464 CallExpr *Call) {
465 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
466 if (S.getLangOpts().OpenCLVersion < 200) {
467 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_requires_version)
468 << Call->getDirectCallee() << "2.0" << 1 << Call->getSourceRange();
469 return true;
470 }
471
472 if (Call->getNumArgs() != 1) {
473 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
474 << Call->getDirectCallee() << Call->getSourceRange();
475 return true;
476 }
477
478 auto RT = Call->getArg(0)->getType();
479 if (!RT->isPointerType() || RT->getPointeeType()
480 .getAddressSpace() == LangAS::opencl_constant) {
481 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
482 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
483 return true;
484 }
485
486 RT = RT->getPointeeType();
487 auto Qual = RT.getQualifiers();
488 switch (BuiltinID) {
489 case Builtin::BIto_global:
490 Qual.setAddressSpace(LangAS::opencl_global);
491 break;
492 case Builtin::BIto_local:
493 Qual.setAddressSpace(LangAS::opencl_local);
494 break;
495 default:
496 Qual.removeAddressSpace();
497 }
498 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
499 RT.getUnqualifiedType(), Qual)));
500
501 return false;
502}
503
John McCalldadc5752010-08-24 06:29:42 +0000504ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000505Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
506 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000507 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000508
Chris Lattner3be167f2010-10-01 23:23:24 +0000509 // Find out if any arguments are required to be integer constant expressions.
510 unsigned ICEArguments = 0;
511 ASTContext::GetBuiltinTypeError Error;
512 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
513 if (Error != ASTContext::GE_None)
514 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
515
516 // If any arguments are required to be ICE's, check and diagnose.
517 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
518 // Skip arguments not required to be ICE's.
519 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
520
521 llvm::APSInt Result;
522 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
523 return true;
524 ICEArguments &= ~(1 << ArgNo);
525 }
526
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000527 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000528 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000529 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000530 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000531 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000532 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000533 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000534 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000535 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000536 if (SemaBuiltinVAStart(TheCall))
537 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000538 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000539 case Builtin::BI__va_start: {
540 switch (Context.getTargetInfo().getTriple().getArch()) {
541 case llvm::Triple::arm:
542 case llvm::Triple::thumb:
543 if (SemaBuiltinVAStartARM(TheCall))
544 return ExprError();
545 break;
546 default:
547 if (SemaBuiltinVAStart(TheCall))
548 return ExprError();
549 break;
550 }
551 break;
552 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000553 case Builtin::BI__builtin_isgreater:
554 case Builtin::BI__builtin_isgreaterequal:
555 case Builtin::BI__builtin_isless:
556 case Builtin::BI__builtin_islessequal:
557 case Builtin::BI__builtin_islessgreater:
558 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000559 if (SemaBuiltinUnorderedCompare(TheCall))
560 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000561 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000562 case Builtin::BI__builtin_fpclassify:
563 if (SemaBuiltinFPClassification(TheCall, 6))
564 return ExprError();
565 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000566 case Builtin::BI__builtin_isfinite:
567 case Builtin::BI__builtin_isinf:
568 case Builtin::BI__builtin_isinf_sign:
569 case Builtin::BI__builtin_isnan:
570 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000571 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000572 return ExprError();
573 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000574 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000575 return SemaBuiltinShuffleVector(TheCall);
576 // TheCall will be freed by the smart pointer here, but that's fine, since
577 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000578 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000579 if (SemaBuiltinPrefetch(TheCall))
580 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000581 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000582 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000583 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000584 if (SemaBuiltinAssume(TheCall))
585 return ExprError();
586 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000587 case Builtin::BI__builtin_assume_aligned:
588 if (SemaBuiltinAssumeAligned(TheCall))
589 return ExprError();
590 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000591 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000592 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000593 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000594 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000595 case Builtin::BI__builtin_longjmp:
596 if (SemaBuiltinLongjmp(TheCall))
597 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000598 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000599 case Builtin::BI__builtin_setjmp:
600 if (SemaBuiltinSetjmp(TheCall))
601 return ExprError();
602 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000603 case Builtin::BI_setjmp:
604 case Builtin::BI_setjmpex:
605 if (checkArgCount(*this, TheCall, 1))
606 return true;
607 break;
John McCallbebede42011-02-26 05:39:39 +0000608
609 case Builtin::BI__builtin_classify_type:
610 if (checkArgCount(*this, TheCall, 1)) return true;
611 TheCall->setType(Context.IntTy);
612 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000613 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000614 if (checkArgCount(*this, TheCall, 1)) return true;
615 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000616 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000617 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000618 case Builtin::BI__sync_fetch_and_add_1:
619 case Builtin::BI__sync_fetch_and_add_2:
620 case Builtin::BI__sync_fetch_and_add_4:
621 case Builtin::BI__sync_fetch_and_add_8:
622 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000623 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000624 case Builtin::BI__sync_fetch_and_sub_1:
625 case Builtin::BI__sync_fetch_and_sub_2:
626 case Builtin::BI__sync_fetch_and_sub_4:
627 case Builtin::BI__sync_fetch_and_sub_8:
628 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000629 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000630 case Builtin::BI__sync_fetch_and_or_1:
631 case Builtin::BI__sync_fetch_and_or_2:
632 case Builtin::BI__sync_fetch_and_or_4:
633 case Builtin::BI__sync_fetch_and_or_8:
634 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000635 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000636 case Builtin::BI__sync_fetch_and_and_1:
637 case Builtin::BI__sync_fetch_and_and_2:
638 case Builtin::BI__sync_fetch_and_and_4:
639 case Builtin::BI__sync_fetch_and_and_8:
640 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000641 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000642 case Builtin::BI__sync_fetch_and_xor_1:
643 case Builtin::BI__sync_fetch_and_xor_2:
644 case Builtin::BI__sync_fetch_and_xor_4:
645 case Builtin::BI__sync_fetch_and_xor_8:
646 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000647 case Builtin::BI__sync_fetch_and_nand:
648 case Builtin::BI__sync_fetch_and_nand_1:
649 case Builtin::BI__sync_fetch_and_nand_2:
650 case Builtin::BI__sync_fetch_and_nand_4:
651 case Builtin::BI__sync_fetch_and_nand_8:
652 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000653 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000654 case Builtin::BI__sync_add_and_fetch_1:
655 case Builtin::BI__sync_add_and_fetch_2:
656 case Builtin::BI__sync_add_and_fetch_4:
657 case Builtin::BI__sync_add_and_fetch_8:
658 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000659 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000660 case Builtin::BI__sync_sub_and_fetch_1:
661 case Builtin::BI__sync_sub_and_fetch_2:
662 case Builtin::BI__sync_sub_and_fetch_4:
663 case Builtin::BI__sync_sub_and_fetch_8:
664 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000665 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000666 case Builtin::BI__sync_and_and_fetch_1:
667 case Builtin::BI__sync_and_and_fetch_2:
668 case Builtin::BI__sync_and_and_fetch_4:
669 case Builtin::BI__sync_and_and_fetch_8:
670 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000671 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000672 case Builtin::BI__sync_or_and_fetch_1:
673 case Builtin::BI__sync_or_and_fetch_2:
674 case Builtin::BI__sync_or_and_fetch_4:
675 case Builtin::BI__sync_or_and_fetch_8:
676 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000677 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000678 case Builtin::BI__sync_xor_and_fetch_1:
679 case Builtin::BI__sync_xor_and_fetch_2:
680 case Builtin::BI__sync_xor_and_fetch_4:
681 case Builtin::BI__sync_xor_and_fetch_8:
682 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000683 case Builtin::BI__sync_nand_and_fetch:
684 case Builtin::BI__sync_nand_and_fetch_1:
685 case Builtin::BI__sync_nand_and_fetch_2:
686 case Builtin::BI__sync_nand_and_fetch_4:
687 case Builtin::BI__sync_nand_and_fetch_8:
688 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000689 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000690 case Builtin::BI__sync_val_compare_and_swap_1:
691 case Builtin::BI__sync_val_compare_and_swap_2:
692 case Builtin::BI__sync_val_compare_and_swap_4:
693 case Builtin::BI__sync_val_compare_and_swap_8:
694 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000695 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000696 case Builtin::BI__sync_bool_compare_and_swap_1:
697 case Builtin::BI__sync_bool_compare_and_swap_2:
698 case Builtin::BI__sync_bool_compare_and_swap_4:
699 case Builtin::BI__sync_bool_compare_and_swap_8:
700 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000701 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000702 case Builtin::BI__sync_lock_test_and_set_1:
703 case Builtin::BI__sync_lock_test_and_set_2:
704 case Builtin::BI__sync_lock_test_and_set_4:
705 case Builtin::BI__sync_lock_test_and_set_8:
706 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000707 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000708 case Builtin::BI__sync_lock_release_1:
709 case Builtin::BI__sync_lock_release_2:
710 case Builtin::BI__sync_lock_release_4:
711 case Builtin::BI__sync_lock_release_8:
712 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000713 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000714 case Builtin::BI__sync_swap_1:
715 case Builtin::BI__sync_swap_2:
716 case Builtin::BI__sync_swap_4:
717 case Builtin::BI__sync_swap_8:
718 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000719 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000720 case Builtin::BI__builtin_nontemporal_load:
721 case Builtin::BI__builtin_nontemporal_store:
722 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000723#define BUILTIN(ID, TYPE, ATTRS)
724#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
725 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000726 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000727#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000728 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000729 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000730 return ExprError();
731 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000732 case Builtin::BI__builtin_addressof:
733 if (SemaBuiltinAddressof(*this, TheCall))
734 return ExprError();
735 break;
John McCall03107a42015-10-29 20:48:01 +0000736 case Builtin::BI__builtin_add_overflow:
737 case Builtin::BI__builtin_sub_overflow:
738 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000739 if (SemaBuiltinOverflow(*this, TheCall))
740 return ExprError();
741 break;
Richard Smith760520b2014-06-03 23:27:44 +0000742 case Builtin::BI__builtin_operator_new:
743 case Builtin::BI__builtin_operator_delete:
744 if (!getLangOpts().CPlusPlus) {
745 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
746 << (BuiltinID == Builtin::BI__builtin_operator_new
747 ? "__builtin_operator_new"
748 : "__builtin_operator_delete")
749 << "C++";
750 return ExprError();
751 }
752 // CodeGen assumes it can find the global new and delete to call,
753 // so ensure that they are declared.
754 DeclareGlobalNewDelete();
755 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000756
757 // check secure string manipulation functions where overflows
758 // are detectable at compile time
759 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000760 case Builtin::BI__builtin___memmove_chk:
761 case Builtin::BI__builtin___memset_chk:
762 case Builtin::BI__builtin___strlcat_chk:
763 case Builtin::BI__builtin___strlcpy_chk:
764 case Builtin::BI__builtin___strncat_chk:
765 case Builtin::BI__builtin___strncpy_chk:
766 case Builtin::BI__builtin___stpncpy_chk:
767 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
768 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000769 case Builtin::BI__builtin___memccpy_chk:
770 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
771 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000772 case Builtin::BI__builtin___snprintf_chk:
773 case Builtin::BI__builtin___vsnprintf_chk:
774 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
775 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000776 case Builtin::BI__builtin_call_with_static_chain:
777 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
778 return ExprError();
779 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000780 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000781 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000782 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
783 diag::err_seh___except_block))
784 return ExprError();
785 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000786 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000787 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000788 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
789 diag::err_seh___except_filter))
790 return ExprError();
791 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +0000792 case Builtin::BI__GetExceptionInfo:
793 if (checkArgCount(*this, TheCall, 1))
794 return ExprError();
795
796 if (CheckCXXThrowOperand(
797 TheCall->getLocStart(),
798 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
799 TheCall))
800 return ExprError();
801
802 TheCall->setType(Context.VoidPtrTy);
803 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000804 case Builtin::BIread_pipe:
805 case Builtin::BIwrite_pipe:
806 // Since those two functions are declared with var args, we need a semantic
807 // check for the argument.
808 if (SemaBuiltinRWPipe(*this, TheCall))
809 return ExprError();
810 break;
811 case Builtin::BIreserve_read_pipe:
812 case Builtin::BIreserve_write_pipe:
813 case Builtin::BIwork_group_reserve_read_pipe:
814 case Builtin::BIwork_group_reserve_write_pipe:
815 case Builtin::BIsub_group_reserve_read_pipe:
816 case Builtin::BIsub_group_reserve_write_pipe:
817 if (SemaBuiltinReserveRWPipe(*this, TheCall))
818 return ExprError();
819 // Since return type of reserve_read/write_pipe built-in function is
820 // reserve_id_t, which is not defined in the builtin def file , we used int
821 // as return type and need to override the return type of these functions.
822 TheCall->setType(Context.OCLReserveIDTy);
823 break;
824 case Builtin::BIcommit_read_pipe:
825 case Builtin::BIcommit_write_pipe:
826 case Builtin::BIwork_group_commit_read_pipe:
827 case Builtin::BIwork_group_commit_write_pipe:
828 case Builtin::BIsub_group_commit_read_pipe:
829 case Builtin::BIsub_group_commit_write_pipe:
830 if (SemaBuiltinCommitRWPipe(*this, TheCall))
831 return ExprError();
832 break;
833 case Builtin::BIget_pipe_num_packets:
834 case Builtin::BIget_pipe_max_packets:
835 if (SemaBuiltinPipePackets(*this, TheCall))
836 return ExprError();
837 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +0000838 case Builtin::BIto_global:
839 case Builtin::BIto_local:
840 case Builtin::BIto_private:
841 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
842 return ExprError();
843 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000844 }
Richard Smith760520b2014-06-03 23:27:44 +0000845
Nate Begeman4904e322010-06-08 02:47:44 +0000846 // Since the target specific builtins for each arch overlap, only check those
847 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +0000848 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000849 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000850 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000851 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000852 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000853 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000854 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
855 return ExprError();
856 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000857 case llvm::Triple::aarch64:
858 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000859 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000860 return ExprError();
861 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000862 case llvm::Triple::mips:
863 case llvm::Triple::mipsel:
864 case llvm::Triple::mips64:
865 case llvm::Triple::mips64el:
866 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
867 return ExprError();
868 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000869 case llvm::Triple::systemz:
870 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
871 return ExprError();
872 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000873 case llvm::Triple::x86:
874 case llvm::Triple::x86_64:
875 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
876 return ExprError();
877 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000878 case llvm::Triple::ppc:
879 case llvm::Triple::ppc64:
880 case llvm::Triple::ppc64le:
881 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
882 return ExprError();
883 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000884 default:
885 break;
886 }
887 }
888
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000889 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000890}
891
Nate Begeman91e1fea2010-06-14 05:21:25 +0000892// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000893static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000894 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000895 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000896 switch (Type.getEltType()) {
897 case NeonTypeFlags::Int8:
898 case NeonTypeFlags::Poly8:
899 return shift ? 7 : (8 << IsQuad) - 1;
900 case NeonTypeFlags::Int16:
901 case NeonTypeFlags::Poly16:
902 return shift ? 15 : (4 << IsQuad) - 1;
903 case NeonTypeFlags::Int32:
904 return shift ? 31 : (2 << IsQuad) - 1;
905 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000906 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000907 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000908 case NeonTypeFlags::Poly128:
909 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000910 case NeonTypeFlags::Float16:
911 assert(!shift && "cannot shift float types!");
912 return (4 << IsQuad) - 1;
913 case NeonTypeFlags::Float32:
914 assert(!shift && "cannot shift float types!");
915 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000916 case NeonTypeFlags::Float64:
917 assert(!shift && "cannot shift float types!");
918 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000919 }
David Blaikie8a40f702012-01-17 06:56:22 +0000920 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000921}
922
Bob Wilsone4d77232011-11-08 05:04:11 +0000923/// getNeonEltType - Return the QualType corresponding to the elements of
924/// the vector type specified by the NeonTypeFlags. This is used to check
925/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000926static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000927 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000928 switch (Flags.getEltType()) {
929 case NeonTypeFlags::Int8:
930 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
931 case NeonTypeFlags::Int16:
932 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
933 case NeonTypeFlags::Int32:
934 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
935 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000936 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000937 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
938 else
939 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
940 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000941 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000942 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000943 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000944 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000945 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000946 if (IsInt64Long)
947 return Context.UnsignedLongTy;
948 else
949 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000950 case NeonTypeFlags::Poly128:
951 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000952 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000953 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000954 case NeonTypeFlags::Float32:
955 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000956 case NeonTypeFlags::Float64:
957 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000958 }
David Blaikie8a40f702012-01-17 06:56:22 +0000959 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000960}
961
Tim Northover12670412014-02-19 10:37:05 +0000962bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000963 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000964 uint64_t mask = 0;
965 unsigned TV = 0;
966 int PtrArgNum = -1;
967 bool HasConstPtr = false;
968 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000969#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000970#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000971#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000972 }
973
974 // For NEON intrinsics which are overloaded on vector element type, validate
975 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000976 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000977 if (mask) {
978 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
979 return true;
980
981 TV = Result.getLimitedValue(64);
982 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
983 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000984 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000985 }
986
987 if (PtrArgNum >= 0) {
988 // Check that pointer arguments have the specified type.
989 Expr *Arg = TheCall->getArg(PtrArgNum);
990 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
991 Arg = ICE->getSubExpr();
992 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
993 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000994
Tim Northovera2ee4332014-03-29 15:09:45 +0000995 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000996 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000997 bool IsInt64Long =
998 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
999 QualType EltTy =
1000 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001001 if (HasConstPtr)
1002 EltTy = EltTy.withConst();
1003 QualType LHSTy = Context.getPointerType(EltTy);
1004 AssignConvertType ConvTy;
1005 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1006 if (RHS.isInvalid())
1007 return true;
1008 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1009 RHS.get(), AA_Assigning))
1010 return true;
1011 }
1012
1013 // For NEON intrinsics which take an immediate value as part of the
1014 // instruction, range check them here.
1015 unsigned i = 0, l = 0, u = 0;
1016 switch (BuiltinID) {
1017 default:
1018 return false;
Tim Northover12670412014-02-19 10:37:05 +00001019#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001020#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001021#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001022 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001023
Richard Sandiford28940af2014-04-16 08:47:51 +00001024 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001025}
1026
Tim Northovera2ee4332014-03-29 15:09:45 +00001027bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1028 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001029 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001030 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001031 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001032 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001033 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001034 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1035 BuiltinID == AArch64::BI__builtin_arm_strex ||
1036 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001037 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001038 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001039 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1040 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1041 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001042
1043 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1044
1045 // Ensure that we have the proper number of arguments.
1046 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1047 return true;
1048
1049 // Inspect the pointer argument of the atomic builtin. This should always be
1050 // a pointer type, whose element is an integral scalar or pointer type.
1051 // Because it is a pointer type, we don't have to worry about any implicit
1052 // casts here.
1053 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1054 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1055 if (PointerArgRes.isInvalid())
1056 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001057 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001058
1059 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1060 if (!pointerType) {
1061 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1062 << PointerArg->getType() << PointerArg->getSourceRange();
1063 return true;
1064 }
1065
1066 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1067 // task is to insert the appropriate casts into the AST. First work out just
1068 // what the appropriate type is.
1069 QualType ValType = pointerType->getPointeeType();
1070 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1071 if (IsLdrex)
1072 AddrType.addConst();
1073
1074 // Issue a warning if the cast is dodgy.
1075 CastKind CastNeeded = CK_NoOp;
1076 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1077 CastNeeded = CK_BitCast;
1078 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1079 << PointerArg->getType()
1080 << Context.getPointerType(AddrType)
1081 << AA_Passing << PointerArg->getSourceRange();
1082 }
1083
1084 // Finally, do the cast and replace the argument with the corrected version.
1085 AddrType = Context.getPointerType(AddrType);
1086 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1087 if (PointerArgRes.isInvalid())
1088 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001089 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001090
1091 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1092
1093 // In general, we allow ints, floats and pointers to be loaded and stored.
1094 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1095 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1096 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1097 << PointerArg->getType() << PointerArg->getSourceRange();
1098 return true;
1099 }
1100
1101 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001102 if (Context.getTypeSize(ValType) > MaxWidth) {
1103 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001104 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1105 << PointerArg->getType() << PointerArg->getSourceRange();
1106 return true;
1107 }
1108
1109 switch (ValType.getObjCLifetime()) {
1110 case Qualifiers::OCL_None:
1111 case Qualifiers::OCL_ExplicitNone:
1112 // okay
1113 break;
1114
1115 case Qualifiers::OCL_Weak:
1116 case Qualifiers::OCL_Strong:
1117 case Qualifiers::OCL_Autoreleasing:
1118 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1119 << ValType << PointerArg->getSourceRange();
1120 return true;
1121 }
1122
Tim Northover6aacd492013-07-16 09:47:53 +00001123 if (IsLdrex) {
1124 TheCall->setType(ValType);
1125 return false;
1126 }
1127
1128 // Initialize the argument to be stored.
1129 ExprResult ValArg = TheCall->getArg(0);
1130 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1131 Context, ValType, /*consume*/ false);
1132 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1133 if (ValArg.isInvalid())
1134 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001135 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001136
1137 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1138 // but the custom checker bypasses all default analysis.
1139 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001140 return false;
1141}
1142
Nate Begeman4904e322010-06-08 02:47:44 +00001143bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001144 llvm::APSInt Result;
1145
Tim Northover6aacd492013-07-16 09:47:53 +00001146 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001147 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1148 BuiltinID == ARM::BI__builtin_arm_strex ||
1149 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001150 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001151 }
1152
Yi Kong26d104a2014-08-13 19:18:14 +00001153 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1154 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1155 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1156 }
1157
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001158 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1159 BuiltinID == ARM::BI__builtin_arm_wsr64)
1160 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1161
1162 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1163 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1164 BuiltinID == ARM::BI__builtin_arm_wsr ||
1165 BuiltinID == ARM::BI__builtin_arm_wsrp)
1166 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1167
Tim Northover12670412014-02-19 10:37:05 +00001168 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1169 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001170
Yi Kong4efadfb2014-07-03 16:01:25 +00001171 // For intrinsics which take an immediate value as part of the instruction,
1172 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001173 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001174 switch (BuiltinID) {
1175 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001176 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1177 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001178 case ARM::BI__builtin_arm_vcvtr_f:
1179 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001180 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001181 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001182 case ARM::BI__builtin_arm_isb:
1183 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001184 }
Nate Begemand773fe62010-06-13 04:47:52 +00001185
Nate Begemanf568b072010-08-03 21:32:34 +00001186 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001187 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001188}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001189
Tim Northover573cbee2014-05-24 12:52:07 +00001190bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001191 CallExpr *TheCall) {
1192 llvm::APSInt Result;
1193
Tim Northover573cbee2014-05-24 12:52:07 +00001194 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001195 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1196 BuiltinID == AArch64::BI__builtin_arm_strex ||
1197 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001198 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1199 }
1200
Yi Konga5548432014-08-13 19:18:20 +00001201 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1202 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1203 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1204 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1205 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1206 }
1207
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001208 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1209 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001210 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001211
1212 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1213 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1214 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1215 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1216 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1217
Tim Northovera2ee4332014-03-29 15:09:45 +00001218 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1219 return true;
1220
Yi Kong19a29ac2014-07-17 10:52:06 +00001221 // For intrinsics which take an immediate value as part of the instruction,
1222 // range check them here.
1223 unsigned i = 0, l = 0, u = 0;
1224 switch (BuiltinID) {
1225 default: return false;
1226 case AArch64::BI__builtin_arm_dmb:
1227 case AArch64::BI__builtin_arm_dsb:
1228 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1229 }
1230
Yi Kong19a29ac2014-07-17 10:52:06 +00001231 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001232}
1233
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001234bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1235 unsigned i = 0, l = 0, u = 0;
1236 switch (BuiltinID) {
1237 default: return false;
1238 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1239 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001240 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1241 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1242 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1243 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1244 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001245 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001246
Richard Sandiford28940af2014-04-16 08:47:51 +00001247 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001248}
1249
Kit Bartone50adcb2015-03-30 19:40:59 +00001250bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1251 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001252 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1253 BuiltinID == PPC::BI__builtin_divdeu ||
1254 BuiltinID == PPC::BI__builtin_bpermd;
1255 bool IsTarget64Bit = Context.getTargetInfo()
1256 .getTypeWidth(Context
1257 .getTargetInfo()
1258 .getIntPtrType()) == 64;
1259 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1260 BuiltinID == PPC::BI__builtin_divweu ||
1261 BuiltinID == PPC::BI__builtin_divde ||
1262 BuiltinID == PPC::BI__builtin_divdeu;
1263
1264 if (Is64BitBltin && !IsTarget64Bit)
1265 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1266 << TheCall->getSourceRange();
1267
1268 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1269 (BuiltinID == PPC::BI__builtin_bpermd &&
1270 !Context.getTargetInfo().hasFeature("bpermd")))
1271 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1272 << TheCall->getSourceRange();
1273
Kit Bartone50adcb2015-03-30 19:40:59 +00001274 switch (BuiltinID) {
1275 default: return false;
1276 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1277 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1278 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1279 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1280 case PPC::BI__builtin_tbegin:
1281 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1282 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1283 case PPC::BI__builtin_tabortwc:
1284 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1285 case PPC::BI__builtin_tabortwci:
1286 case PPC::BI__builtin_tabortdci:
1287 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1288 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1289 }
1290 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1291}
1292
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001293bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1294 CallExpr *TheCall) {
1295 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1296 Expr *Arg = TheCall->getArg(0);
1297 llvm::APSInt AbortCode(32);
1298 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1299 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1300 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1301 << Arg->getSourceRange();
1302 }
1303
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001304 // For intrinsics which take an immediate value as part of the instruction,
1305 // range check them here.
1306 unsigned i = 0, l = 0, u = 0;
1307 switch (BuiltinID) {
1308 default: return false;
1309 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1310 case SystemZ::BI__builtin_s390_verimb:
1311 case SystemZ::BI__builtin_s390_verimh:
1312 case SystemZ::BI__builtin_s390_verimf:
1313 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1314 case SystemZ::BI__builtin_s390_vfaeb:
1315 case SystemZ::BI__builtin_s390_vfaeh:
1316 case SystemZ::BI__builtin_s390_vfaef:
1317 case SystemZ::BI__builtin_s390_vfaebs:
1318 case SystemZ::BI__builtin_s390_vfaehs:
1319 case SystemZ::BI__builtin_s390_vfaefs:
1320 case SystemZ::BI__builtin_s390_vfaezb:
1321 case SystemZ::BI__builtin_s390_vfaezh:
1322 case SystemZ::BI__builtin_s390_vfaezf:
1323 case SystemZ::BI__builtin_s390_vfaezbs:
1324 case SystemZ::BI__builtin_s390_vfaezhs:
1325 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1326 case SystemZ::BI__builtin_s390_vfidb:
1327 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1328 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1329 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1330 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1331 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1332 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1333 case SystemZ::BI__builtin_s390_vstrcb:
1334 case SystemZ::BI__builtin_s390_vstrch:
1335 case SystemZ::BI__builtin_s390_vstrcf:
1336 case SystemZ::BI__builtin_s390_vstrczb:
1337 case SystemZ::BI__builtin_s390_vstrczh:
1338 case SystemZ::BI__builtin_s390_vstrczf:
1339 case SystemZ::BI__builtin_s390_vstrcbs:
1340 case SystemZ::BI__builtin_s390_vstrchs:
1341 case SystemZ::BI__builtin_s390_vstrcfs:
1342 case SystemZ::BI__builtin_s390_vstrczbs:
1343 case SystemZ::BI__builtin_s390_vstrczhs:
1344 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1345 }
1346 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001347}
1348
Craig Topper5ba2c502015-11-07 08:08:31 +00001349/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1350/// This checks that the target supports __builtin_cpu_supports and
1351/// that the string argument is constant and valid.
1352static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1353 Expr *Arg = TheCall->getArg(0);
1354
1355 // Check if the argument is a string literal.
1356 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1357 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1358 << Arg->getSourceRange();
1359
1360 // Check the contents of the string.
1361 StringRef Feature =
1362 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1363 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1364 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1365 << Arg->getSourceRange();
1366 return false;
1367}
1368
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001369bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topper39c87102016-05-18 03:18:12 +00001370 int i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001371 switch (BuiltinID) {
Richard Trieucc3949d2016-02-18 22:34:54 +00001372 default:
1373 return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001374 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001375 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001376 case X86::BI__builtin_ms_va_start:
1377 return SemaBuiltinMSVAStart(TheCall);
Craig Topper39c87102016-05-18 03:18:12 +00001378 case X86::BI__builtin_ia32_extractf64x4_mask:
1379 case X86::BI__builtin_ia32_extracti64x4_mask:
1380 case X86::BI__builtin_ia32_extractf32x8_mask:
1381 case X86::BI__builtin_ia32_extracti32x8_mask:
1382 case X86::BI__builtin_ia32_extractf64x2_256_mask:
1383 case X86::BI__builtin_ia32_extracti64x2_256_mask:
1384 case X86::BI__builtin_ia32_extractf32x4_256_mask:
1385 case X86::BI__builtin_ia32_extracti32x4_256_mask:
1386 i = 1; l = 0; u = 1;
1387 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00001388 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00001389 case X86::BI__builtin_ia32_extractf32x4_mask:
1390 case X86::BI__builtin_ia32_extracti32x4_mask:
1391 case X86::BI__builtin_ia32_vpermilpd_mask:
1392 case X86::BI__builtin_ia32_vpermilps_mask:
1393 case X86::BI__builtin_ia32_extractf64x2_512_mask:
1394 case X86::BI__builtin_ia32_extracti64x2_512_mask:
1395 i = 1; l = 0; u = 3;
1396 break;
1397 case X86::BI__builtin_ia32_insertf32x8_mask:
1398 case X86::BI__builtin_ia32_inserti32x8_mask:
1399 case X86::BI__builtin_ia32_insertf64x4_mask:
1400 case X86::BI__builtin_ia32_inserti64x4_mask:
1401 case X86::BI__builtin_ia32_insertf64x2_256_mask:
1402 case X86::BI__builtin_ia32_inserti64x2_256_mask:
1403 case X86::BI__builtin_ia32_insertf32x4_256_mask:
1404 case X86::BI__builtin_ia32_inserti32x4_256_mask:
1405 i = 2; l = 0; u = 1;
Richard Trieucc3949d2016-02-18 22:34:54 +00001406 break;
1407 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00001408 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1409 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1410 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1411 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
1412 case X86::BI__builtin_ia32_shufpd128_mask:
1413 case X86::BI__builtin_ia32_insertf64x2_512_mask:
1414 case X86::BI__builtin_ia32_inserti64x2_512_mask:
1415 case X86::BI__builtin_ia32_insertf32x4_mask:
1416 case X86::BI__builtin_ia32_inserti32x4_mask:
1417 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001418 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001419 case X86::BI__builtin_ia32_vpermil2pd:
1420 case X86::BI__builtin_ia32_vpermil2pd256:
1421 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001422 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00001423 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001424 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001425 case X86::BI__builtin_ia32_cmpb128_mask:
1426 case X86::BI__builtin_ia32_cmpw128_mask:
1427 case X86::BI__builtin_ia32_cmpd128_mask:
1428 case X86::BI__builtin_ia32_cmpq128_mask:
1429 case X86::BI__builtin_ia32_cmpb256_mask:
1430 case X86::BI__builtin_ia32_cmpw256_mask:
1431 case X86::BI__builtin_ia32_cmpd256_mask:
1432 case X86::BI__builtin_ia32_cmpq256_mask:
1433 case X86::BI__builtin_ia32_cmpb512_mask:
1434 case X86::BI__builtin_ia32_cmpw512_mask:
1435 case X86::BI__builtin_ia32_cmpd512_mask:
1436 case X86::BI__builtin_ia32_cmpq512_mask:
1437 case X86::BI__builtin_ia32_ucmpb128_mask:
1438 case X86::BI__builtin_ia32_ucmpw128_mask:
1439 case X86::BI__builtin_ia32_ucmpd128_mask:
1440 case X86::BI__builtin_ia32_ucmpq128_mask:
1441 case X86::BI__builtin_ia32_ucmpb256_mask:
1442 case X86::BI__builtin_ia32_ucmpw256_mask:
1443 case X86::BI__builtin_ia32_ucmpd256_mask:
1444 case X86::BI__builtin_ia32_ucmpq256_mask:
1445 case X86::BI__builtin_ia32_ucmpb512_mask:
1446 case X86::BI__builtin_ia32_ucmpw512_mask:
1447 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001448 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001449 case X86::BI__builtin_ia32_vpcomub:
1450 case X86::BI__builtin_ia32_vpcomuw:
1451 case X86::BI__builtin_ia32_vpcomud:
1452 case X86::BI__builtin_ia32_vpcomuq:
1453 case X86::BI__builtin_ia32_vpcomb:
1454 case X86::BI__builtin_ia32_vpcomw:
1455 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001456 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00001457 i = 2; l = 0; u = 7;
1458 break;
1459 case X86::BI__builtin_ia32_roundps:
1460 case X86::BI__builtin_ia32_roundpd:
1461 case X86::BI__builtin_ia32_roundps256:
1462 case X86::BI__builtin_ia32_roundpd256:
1463 case X86::BI__builtin_ia32_vpermilpd256_mask:
1464 case X86::BI__builtin_ia32_vpermilps256_mask:
1465 i = 1; l = 0; u = 15;
1466 break;
1467 case X86::BI__builtin_ia32_roundss:
1468 case X86::BI__builtin_ia32_roundsd:
1469 case X86::BI__builtin_ia32_rangepd128_mask:
1470 case X86::BI__builtin_ia32_rangepd256_mask:
1471 case X86::BI__builtin_ia32_rangepd512_mask:
1472 case X86::BI__builtin_ia32_rangeps128_mask:
1473 case X86::BI__builtin_ia32_rangeps256_mask:
1474 case X86::BI__builtin_ia32_rangeps512_mask:
1475 case X86::BI__builtin_ia32_getmantsd_round_mask:
1476 case X86::BI__builtin_ia32_getmantss_round_mask:
1477 case X86::BI__builtin_ia32_shufpd256_mask:
1478 i = 2; l = 0; u = 15;
1479 break;
1480 case X86::BI__builtin_ia32_cmpps:
1481 case X86::BI__builtin_ia32_cmpss:
1482 case X86::BI__builtin_ia32_cmppd:
1483 case X86::BI__builtin_ia32_cmpsd:
1484 case X86::BI__builtin_ia32_cmpps256:
1485 case X86::BI__builtin_ia32_cmppd256:
1486 case X86::BI__builtin_ia32_cmpps128_mask:
1487 case X86::BI__builtin_ia32_cmppd128_mask:
1488 case X86::BI__builtin_ia32_cmpps256_mask:
1489 case X86::BI__builtin_ia32_cmppd256_mask:
1490 case X86::BI__builtin_ia32_cmpps512_mask:
1491 case X86::BI__builtin_ia32_cmppd512_mask:
1492 case X86::BI__builtin_ia32_cmpsd_mask:
1493 case X86::BI__builtin_ia32_cmpss_mask:
1494 i = 2; l = 0; u = 31;
1495 break;
1496 case X86::BI__builtin_ia32_xabort:
1497 i = 0; l = -128; u = 255;
1498 break;
1499 case X86::BI__builtin_ia32_pshufw:
1500 case X86::BI__builtin_ia32_aeskeygenassist128:
1501 i = 1; l = -128; u = 255;
1502 break;
1503 case X86::BI__builtin_ia32_vcvtps2ph:
1504 case X86::BI__builtin_ia32_vcvtps2ph256:
1505 case X86::BI__builtin_ia32_vcvtps2ph512:
1506 case X86::BI__builtin_ia32_rndscaleps_128_mask:
1507 case X86::BI__builtin_ia32_rndscalepd_128_mask:
1508 case X86::BI__builtin_ia32_rndscaleps_256_mask:
1509 case X86::BI__builtin_ia32_rndscalepd_256_mask:
1510 case X86::BI__builtin_ia32_rndscaleps_mask:
1511 case X86::BI__builtin_ia32_rndscalepd_mask:
1512 case X86::BI__builtin_ia32_reducepd128_mask:
1513 case X86::BI__builtin_ia32_reducepd256_mask:
1514 case X86::BI__builtin_ia32_reducepd512_mask:
1515 case X86::BI__builtin_ia32_reduceps128_mask:
1516 case X86::BI__builtin_ia32_reduceps256_mask:
1517 case X86::BI__builtin_ia32_reduceps512_mask:
1518 case X86::BI__builtin_ia32_prold512_mask:
1519 case X86::BI__builtin_ia32_prolq512_mask:
1520 case X86::BI__builtin_ia32_prold128_mask:
1521 case X86::BI__builtin_ia32_prold256_mask:
1522 case X86::BI__builtin_ia32_prolq128_mask:
1523 case X86::BI__builtin_ia32_prolq256_mask:
1524 case X86::BI__builtin_ia32_prord128_mask:
1525 case X86::BI__builtin_ia32_prord256_mask:
1526 case X86::BI__builtin_ia32_prorq128_mask:
1527 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001528 case X86::BI__builtin_ia32_psllwi512_mask:
1529 case X86::BI__builtin_ia32_psllwi128_mask:
1530 case X86::BI__builtin_ia32_psllwi256_mask:
1531 case X86::BI__builtin_ia32_psrldi128_mask:
1532 case X86::BI__builtin_ia32_psrldi256_mask:
1533 case X86::BI__builtin_ia32_psrldi512_mask:
1534 case X86::BI__builtin_ia32_psrlqi128_mask:
1535 case X86::BI__builtin_ia32_psrlqi256_mask:
1536 case X86::BI__builtin_ia32_psrlqi512_mask:
1537 case X86::BI__builtin_ia32_psrawi512_mask:
1538 case X86::BI__builtin_ia32_psrawi128_mask:
1539 case X86::BI__builtin_ia32_psrawi256_mask:
1540 case X86::BI__builtin_ia32_psrlwi512_mask:
1541 case X86::BI__builtin_ia32_psrlwi128_mask:
1542 case X86::BI__builtin_ia32_psrlwi256_mask:
1543 case X86::BI__builtin_ia32_vpermilpd512_mask:
1544 case X86::BI__builtin_ia32_vpermilps512_mask:
1545 case X86::BI__builtin_ia32_psradi128_mask:
1546 case X86::BI__builtin_ia32_psradi256_mask:
1547 case X86::BI__builtin_ia32_psradi512_mask:
1548 case X86::BI__builtin_ia32_psraqi128_mask:
1549 case X86::BI__builtin_ia32_psraqi256_mask:
1550 case X86::BI__builtin_ia32_psraqi512_mask:
1551 case X86::BI__builtin_ia32_pslldi128_mask:
1552 case X86::BI__builtin_ia32_pslldi256_mask:
1553 case X86::BI__builtin_ia32_pslldi512_mask:
1554 case X86::BI__builtin_ia32_psllqi128_mask:
1555 case X86::BI__builtin_ia32_psllqi256_mask:
1556 case X86::BI__builtin_ia32_psllqi512_mask:
1557 case X86::BI__builtin_ia32_permdf512_mask:
1558 case X86::BI__builtin_ia32_permdi512_mask:
1559 case X86::BI__builtin_ia32_permdf256_mask:
1560 case X86::BI__builtin_ia32_permdi256_mask:
1561 case X86::BI__builtin_ia32_fpclasspd128_mask:
1562 case X86::BI__builtin_ia32_fpclasspd256_mask:
1563 case X86::BI__builtin_ia32_fpclassps128_mask:
1564 case X86::BI__builtin_ia32_fpclassps256_mask:
1565 case X86::BI__builtin_ia32_fpclassps512_mask:
1566 case X86::BI__builtin_ia32_fpclasspd512_mask:
1567 case X86::BI__builtin_ia32_fpclasssd_mask:
1568 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001569 i = 1; l = 0; u = 255;
1570 break;
1571 case X86::BI__builtin_ia32_palignr:
1572 case X86::BI__builtin_ia32_insertps128:
1573 case X86::BI__builtin_ia32_dpps:
1574 case X86::BI__builtin_ia32_dppd:
1575 case X86::BI__builtin_ia32_dpps256:
1576 case X86::BI__builtin_ia32_mpsadbw128:
1577 case X86::BI__builtin_ia32_mpsadbw256:
1578 case X86::BI__builtin_ia32_pcmpistrm128:
1579 case X86::BI__builtin_ia32_pcmpistri128:
1580 case X86::BI__builtin_ia32_pcmpistria128:
1581 case X86::BI__builtin_ia32_pcmpistric128:
1582 case X86::BI__builtin_ia32_pcmpistrio128:
1583 case X86::BI__builtin_ia32_pcmpistris128:
1584 case X86::BI__builtin_ia32_pcmpistriz128:
1585 case X86::BI__builtin_ia32_pclmulqdq128:
1586 case X86::BI__builtin_ia32_vperm2f128_pd256:
1587 case X86::BI__builtin_ia32_vperm2f128_ps256:
1588 case X86::BI__builtin_ia32_vperm2f128_si256:
1589 case X86::BI__builtin_ia32_permti256:
1590 i = 2; l = -128; u = 255;
1591 break;
1592 case X86::BI__builtin_ia32_palignr128:
1593 case X86::BI__builtin_ia32_palignr256:
1594 case X86::BI__builtin_ia32_palignr128_mask:
1595 case X86::BI__builtin_ia32_palignr256_mask:
1596 case X86::BI__builtin_ia32_palignr512_mask:
1597 case X86::BI__builtin_ia32_alignq512_mask:
1598 case X86::BI__builtin_ia32_alignd512_mask:
1599 case X86::BI__builtin_ia32_alignd128_mask:
1600 case X86::BI__builtin_ia32_alignd256_mask:
1601 case X86::BI__builtin_ia32_alignq128_mask:
1602 case X86::BI__builtin_ia32_alignq256_mask:
1603 case X86::BI__builtin_ia32_vcomisd:
1604 case X86::BI__builtin_ia32_vcomiss:
1605 case X86::BI__builtin_ia32_shuf_f32x4_mask:
1606 case X86::BI__builtin_ia32_shuf_f64x2_mask:
1607 case X86::BI__builtin_ia32_shuf_i32x4_mask:
1608 case X86::BI__builtin_ia32_shuf_i64x2_mask:
1609 case X86::BI__builtin_ia32_shufpd512_mask:
1610 case X86::BI__builtin_ia32_shufps128_mask:
1611 case X86::BI__builtin_ia32_shufps256_mask:
1612 case X86::BI__builtin_ia32_shufps512_mask:
1613 case X86::BI__builtin_ia32_dbpsadbw128_mask:
1614 case X86::BI__builtin_ia32_dbpsadbw256_mask:
1615 case X86::BI__builtin_ia32_dbpsadbw512_mask:
1616 i = 2; l = 0; u = 255;
1617 break;
1618 case X86::BI__builtin_ia32_fixupimmpd512_mask:
1619 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1620 case X86::BI__builtin_ia32_fixupimmps512_mask:
1621 case X86::BI__builtin_ia32_fixupimmps512_maskz:
1622 case X86::BI__builtin_ia32_fixupimmsd_mask:
1623 case X86::BI__builtin_ia32_fixupimmsd_maskz:
1624 case X86::BI__builtin_ia32_fixupimmss_mask:
1625 case X86::BI__builtin_ia32_fixupimmss_maskz:
1626 case X86::BI__builtin_ia32_fixupimmpd128_mask:
1627 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
1628 case X86::BI__builtin_ia32_fixupimmpd256_mask:
1629 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
1630 case X86::BI__builtin_ia32_fixupimmps128_mask:
1631 case X86::BI__builtin_ia32_fixupimmps128_maskz:
1632 case X86::BI__builtin_ia32_fixupimmps256_mask:
1633 case X86::BI__builtin_ia32_fixupimmps256_maskz:
1634 case X86::BI__builtin_ia32_pternlogd512_mask:
1635 case X86::BI__builtin_ia32_pternlogd512_maskz:
1636 case X86::BI__builtin_ia32_pternlogq512_mask:
1637 case X86::BI__builtin_ia32_pternlogq512_maskz:
1638 case X86::BI__builtin_ia32_pternlogd128_mask:
1639 case X86::BI__builtin_ia32_pternlogd128_maskz:
1640 case X86::BI__builtin_ia32_pternlogd256_mask:
1641 case X86::BI__builtin_ia32_pternlogd256_maskz:
1642 case X86::BI__builtin_ia32_pternlogq128_mask:
1643 case X86::BI__builtin_ia32_pternlogq128_maskz:
1644 case X86::BI__builtin_ia32_pternlogq256_mask:
1645 case X86::BI__builtin_ia32_pternlogq256_maskz:
1646 i = 3; l = 0; u = 255;
1647 break;
1648 case X86::BI__builtin_ia32_pcmpestrm128:
1649 case X86::BI__builtin_ia32_pcmpestri128:
1650 case X86::BI__builtin_ia32_pcmpestria128:
1651 case X86::BI__builtin_ia32_pcmpestric128:
1652 case X86::BI__builtin_ia32_pcmpestrio128:
1653 case X86::BI__builtin_ia32_pcmpestris128:
1654 case X86::BI__builtin_ia32_pcmpestriz128:
1655 i = 4; l = -128; u = 255;
1656 break;
1657 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1658 case X86::BI__builtin_ia32_rndscaless_round_mask:
1659 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00001660 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001661 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001662 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001663}
1664
Richard Smith55ce3522012-06-25 20:30:08 +00001665/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1666/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1667/// Returns true when the format fits the function and the FormatStringInfo has
1668/// been populated.
1669bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1670 FormatStringInfo *FSI) {
1671 FSI->HasVAListArg = Format->getFirstArg() == 0;
1672 FSI->FormatIdx = Format->getFormatIdx() - 1;
1673 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001674
Richard Smith55ce3522012-06-25 20:30:08 +00001675 // The way the format attribute works in GCC, the implicit this argument
1676 // of member functions is counted. However, it doesn't appear in our own
1677 // lists, so decrement format_idx in that case.
1678 if (IsCXXMember) {
1679 if(FSI->FormatIdx == 0)
1680 return false;
1681 --FSI->FormatIdx;
1682 if (FSI->FirstDataArg != 0)
1683 --FSI->FirstDataArg;
1684 }
1685 return true;
1686}
Mike Stump11289f42009-09-09 15:08:12 +00001687
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001688/// Checks if a the given expression evaluates to null.
1689///
1690/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001691static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001692 // If the expression has non-null type, it doesn't evaluate to null.
1693 if (auto nullability
1694 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1695 if (*nullability == NullabilityKind::NonNull)
1696 return false;
1697 }
1698
Ted Kremeneka146db32014-01-17 06:24:47 +00001699 // As a special case, transparent unions initialized with zero are
1700 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001701 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001702 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1703 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001704 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001705 if (const InitListExpr *ILE =
1706 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001707 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001708 }
1709
1710 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001711 return (!Expr->isValueDependent() &&
1712 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1713 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001714}
1715
1716static void CheckNonNullArgument(Sema &S,
1717 const Expr *ArgExpr,
1718 SourceLocation CallSiteLoc) {
1719 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001720 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1721 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001722}
1723
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001724bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1725 FormatStringInfo FSI;
1726 if ((GetFormatStringType(Format) == FST_NSString) &&
1727 getFormatStringInfo(Format, false, &FSI)) {
1728 Idx = FSI.FormatIdx;
1729 return true;
1730 }
1731 return false;
1732}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001733/// \brief Diagnose use of %s directive in an NSString which is being passed
1734/// as formatting string to formatting method.
1735static void
1736DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1737 const NamedDecl *FDecl,
1738 Expr **Args,
1739 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001740 unsigned Idx = 0;
1741 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001742 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1743 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001744 Idx = 2;
1745 Format = true;
1746 }
1747 else
1748 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1749 if (S.GetFormatNSStringIdx(I, Idx)) {
1750 Format = true;
1751 break;
1752 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001753 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001754 if (!Format || NumArgs <= Idx)
1755 return;
1756 const Expr *FormatExpr = Args[Idx];
1757 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1758 FormatExpr = CSCE->getSubExpr();
1759 const StringLiteral *FormatString;
1760 if (const ObjCStringLiteral *OSL =
1761 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1762 FormatString = OSL->getString();
1763 else
1764 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1765 if (!FormatString)
1766 return;
1767 if (S.FormatStringHasSArg(FormatString)) {
1768 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1769 << "%s" << 1 << 1;
1770 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1771 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001772 }
1773}
1774
Douglas Gregorb4866e82015-06-19 18:13:19 +00001775/// Determine whether the given type has a non-null nullability annotation.
1776static bool isNonNullType(ASTContext &ctx, QualType type) {
1777 if (auto nullability = type->getNullability(ctx))
1778 return *nullability == NullabilityKind::NonNull;
1779
1780 return false;
1781}
1782
Ted Kremenek2bc73332014-01-17 06:24:43 +00001783static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001784 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001785 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001786 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001787 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001788 assert((FDecl || Proto) && "Need a function declaration or prototype");
1789
Ted Kremenek9aedc152014-01-17 06:24:56 +00001790 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001791 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001792 if (FDecl) {
1793 // Handle the nonnull attribute on the function/method declaration itself.
1794 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1795 if (!NonNull->args_size()) {
1796 // Easy case: all pointer arguments are nonnull.
1797 for (const auto *Arg : Args)
1798 if (S.isValidPointerAttrType(Arg->getType()))
1799 CheckNonNullArgument(S, Arg, CallSiteLoc);
1800 return;
1801 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001802
Douglas Gregorb4866e82015-06-19 18:13:19 +00001803 for (unsigned Val : NonNull->args()) {
1804 if (Val >= Args.size())
1805 continue;
1806 if (NonNullArgs.empty())
1807 NonNullArgs.resize(Args.size());
1808 NonNullArgs.set(Val);
1809 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001810 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001811 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001812
Douglas Gregorb4866e82015-06-19 18:13:19 +00001813 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1814 // Handle the nonnull attribute on the parameters of the
1815 // function/method.
1816 ArrayRef<ParmVarDecl*> parms;
1817 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1818 parms = FD->parameters();
1819 else
1820 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1821
1822 unsigned ParamIndex = 0;
1823 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1824 I != E; ++I, ++ParamIndex) {
1825 const ParmVarDecl *PVD = *I;
1826 if (PVD->hasAttr<NonNullAttr>() ||
1827 isNonNullType(S.Context, PVD->getType())) {
1828 if (NonNullArgs.empty())
1829 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001830
Douglas Gregorb4866e82015-06-19 18:13:19 +00001831 NonNullArgs.set(ParamIndex);
1832 }
1833 }
1834 } else {
1835 // If we have a non-function, non-method declaration but no
1836 // function prototype, try to dig out the function prototype.
1837 if (!Proto) {
1838 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1839 QualType type = VD->getType().getNonReferenceType();
1840 if (auto pointerType = type->getAs<PointerType>())
1841 type = pointerType->getPointeeType();
1842 else if (auto blockType = type->getAs<BlockPointerType>())
1843 type = blockType->getPointeeType();
1844 // FIXME: data member pointers?
1845
1846 // Dig out the function prototype, if there is one.
1847 Proto = type->getAs<FunctionProtoType>();
1848 }
1849 }
1850
1851 // Fill in non-null argument information from the nullability
1852 // information on the parameter types (if we have them).
1853 if (Proto) {
1854 unsigned Index = 0;
1855 for (auto paramType : Proto->getParamTypes()) {
1856 if (isNonNullType(S.Context, paramType)) {
1857 if (NonNullArgs.empty())
1858 NonNullArgs.resize(Args.size());
1859
1860 NonNullArgs.set(Index);
1861 }
1862
1863 ++Index;
1864 }
1865 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001866 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001867
Douglas Gregorb4866e82015-06-19 18:13:19 +00001868 // Check for non-null arguments.
1869 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1870 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001871 if (NonNullArgs[ArgIndex])
1872 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001873 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001874}
1875
Richard Smith55ce3522012-06-25 20:30:08 +00001876/// Handles the checks for format strings, non-POD arguments to vararg
1877/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001878void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1879 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001880 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001881 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001882 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001883 if (CurContext->isDependentContext())
1884 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001885
Ted Kremenekb8176da2010-09-09 04:33:05 +00001886 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001887 llvm::SmallBitVector CheckedVarArgs;
1888 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001889 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001890 // Only create vector if there are format attributes.
1891 CheckedVarArgs.resize(Args.size());
1892
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001893 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001894 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001895 }
Richard Smithd7293d72013-08-05 18:49:43 +00001896 }
Richard Smith55ce3522012-06-25 20:30:08 +00001897
1898 // Refuse POD arguments that weren't caught by the format string
1899 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001900 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001901 unsigned NumParams = Proto ? Proto->getNumParams()
1902 : FDecl && isa<FunctionDecl>(FDecl)
1903 ? cast<FunctionDecl>(FDecl)->getNumParams()
1904 : FDecl && isa<ObjCMethodDecl>(FDecl)
1905 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1906 : 0;
1907
Alp Toker9cacbab2014-01-20 20:26:09 +00001908 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001909 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001910 if (const Expr *Arg = Args[ArgIdx]) {
1911 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1912 checkVariadicArgument(Arg, CallType);
1913 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001914 }
Richard Smithd7293d72013-08-05 18:49:43 +00001915 }
Mike Stump11289f42009-09-09 15:08:12 +00001916
Douglas Gregorb4866e82015-06-19 18:13:19 +00001917 if (FDecl || Proto) {
1918 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001919
Richard Trieu41bc0992013-06-22 00:20:41 +00001920 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001921 if (FDecl) {
1922 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1923 CheckArgumentWithTypeTag(I, Args.data());
1924 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001925 }
Richard Smith55ce3522012-06-25 20:30:08 +00001926}
1927
1928/// CheckConstructorCall - Check a constructor call for correctness and safety
1929/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001930void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1931 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001932 const FunctionProtoType *Proto,
1933 SourceLocation Loc) {
1934 VariadicCallType CallType =
1935 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001936 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1937 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001938}
1939
1940/// CheckFunctionCall - Check a direct function call for various correctness
1941/// and safety properties not strictly enforced by the C type system.
1942bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1943 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001944 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1945 isa<CXXMethodDecl>(FDecl);
1946 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1947 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001948 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1949 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001950 Expr** Args = TheCall->getArgs();
1951 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001952 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001953 // If this is a call to a member operator, hide the first argument
1954 // from checkCall.
1955 // FIXME: Our choice of AST representation here is less than ideal.
1956 ++Args;
1957 --NumArgs;
1958 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001959 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001960 IsMemberFunction, TheCall->getRParenLoc(),
1961 TheCall->getCallee()->getSourceRange(), CallType);
1962
1963 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1964 // None of the checks below are needed for functions that don't have
1965 // simple names (e.g., C++ conversion functions).
1966 if (!FnInfo)
1967 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001968
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001969 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001970 if (getLangOpts().ObjC1)
1971 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001972
Anna Zaks22122702012-01-17 00:37:07 +00001973 unsigned CMId = FDecl->getMemoryFunctionKind();
1974 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001975 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001976
Anna Zaks201d4892012-01-13 21:52:01 +00001977 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001978 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001979 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001980 else if (CMId == Builtin::BIstrncat)
1981 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001982 else
Anna Zaks22122702012-01-17 00:37:07 +00001983 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001984
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001985 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001986}
1987
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001988bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001989 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001990 VariadicCallType CallType =
1991 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001992
Douglas Gregorb4866e82015-06-19 18:13:19 +00001993 checkCall(Method, nullptr, Args,
1994 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1995 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001996
1997 return false;
1998}
1999
Richard Trieu664c4c62013-06-20 21:03:13 +00002000bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2001 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002002 QualType Ty;
2003 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002004 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002005 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002006 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002007 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002008 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002009
Douglas Gregorb4866e82015-06-19 18:13:19 +00002010 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2011 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002012 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002013
Richard Trieu664c4c62013-06-20 21:03:13 +00002014 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002015 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002016 CallType = VariadicDoesNotApply;
2017 } else if (Ty->isBlockPointerType()) {
2018 CallType = VariadicBlock;
2019 } else { // Ty->isFunctionPointerType()
2020 CallType = VariadicFunction;
2021 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002022
Douglas Gregorb4866e82015-06-19 18:13:19 +00002023 checkCall(NDecl, Proto,
2024 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2025 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002026 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002027
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002028 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002029}
2030
Richard Trieu41bc0992013-06-22 00:20:41 +00002031/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2032/// such as function pointers returned from functions.
2033bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002034 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002035 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00002036 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002037 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002038 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002039 TheCall->getCallee()->getSourceRange(), CallType);
2040
2041 return false;
2042}
2043
Tim Northovere94a34c2014-03-11 10:49:14 +00002044static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002045 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002046 return false;
2047
JF Bastiendda2cb12016-04-18 18:01:49 +00002048 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002049 switch (Op) {
2050 case AtomicExpr::AO__c11_atomic_init:
2051 llvm_unreachable("There is no ordering argument for an init");
2052
2053 case AtomicExpr::AO__c11_atomic_load:
2054 case AtomicExpr::AO__atomic_load_n:
2055 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002056 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2057 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002058
2059 case AtomicExpr::AO__c11_atomic_store:
2060 case AtomicExpr::AO__atomic_store:
2061 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002062 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2063 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2064 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002065
2066 default:
2067 return true;
2068 }
2069}
2070
Richard Smithfeea8832012-04-12 05:08:17 +00002071ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2072 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002073 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2074 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002075
Richard Smithfeea8832012-04-12 05:08:17 +00002076 // All these operations take one of the following forms:
2077 enum {
2078 // C __c11_atomic_init(A *, C)
2079 Init,
2080 // C __c11_atomic_load(A *, int)
2081 Load,
2082 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002083 LoadCopy,
2084 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002085 Copy,
2086 // C __c11_atomic_add(A *, M, int)
2087 Arithmetic,
2088 // C __atomic_exchange_n(A *, CP, int)
2089 Xchg,
2090 // void __atomic_exchange(A *, C *, CP, int)
2091 GNUXchg,
2092 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2093 C11CmpXchg,
2094 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2095 GNUCmpXchg
2096 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002097 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2098 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002099 // where:
2100 // C is an appropriate type,
2101 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2102 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2103 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2104 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002105
Gabor Horvath98bd0982015-03-16 09:59:54 +00002106 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2107 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2108 AtomicExpr::AO__atomic_load,
2109 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002110 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2111 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2112 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2113 Op == AtomicExpr::AO__atomic_store_n ||
2114 Op == AtomicExpr::AO__atomic_exchange_n ||
2115 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2116 bool IsAddSub = false;
2117
2118 switch (Op) {
2119 case AtomicExpr::AO__c11_atomic_init:
2120 Form = Init;
2121 break;
2122
2123 case AtomicExpr::AO__c11_atomic_load:
2124 case AtomicExpr::AO__atomic_load_n:
2125 Form = Load;
2126 break;
2127
Richard Smithfeea8832012-04-12 05:08:17 +00002128 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002129 Form = LoadCopy;
2130 break;
2131
2132 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002133 case AtomicExpr::AO__atomic_store:
2134 case AtomicExpr::AO__atomic_store_n:
2135 Form = Copy;
2136 break;
2137
2138 case AtomicExpr::AO__c11_atomic_fetch_add:
2139 case AtomicExpr::AO__c11_atomic_fetch_sub:
2140 case AtomicExpr::AO__atomic_fetch_add:
2141 case AtomicExpr::AO__atomic_fetch_sub:
2142 case AtomicExpr::AO__atomic_add_fetch:
2143 case AtomicExpr::AO__atomic_sub_fetch:
2144 IsAddSub = true;
2145 // Fall through.
2146 case AtomicExpr::AO__c11_atomic_fetch_and:
2147 case AtomicExpr::AO__c11_atomic_fetch_or:
2148 case AtomicExpr::AO__c11_atomic_fetch_xor:
2149 case AtomicExpr::AO__atomic_fetch_and:
2150 case AtomicExpr::AO__atomic_fetch_or:
2151 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002152 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002153 case AtomicExpr::AO__atomic_and_fetch:
2154 case AtomicExpr::AO__atomic_or_fetch:
2155 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002156 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002157 Form = Arithmetic;
2158 break;
2159
2160 case AtomicExpr::AO__c11_atomic_exchange:
2161 case AtomicExpr::AO__atomic_exchange_n:
2162 Form = Xchg;
2163 break;
2164
2165 case AtomicExpr::AO__atomic_exchange:
2166 Form = GNUXchg;
2167 break;
2168
2169 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2170 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2171 Form = C11CmpXchg;
2172 break;
2173
2174 case AtomicExpr::AO__atomic_compare_exchange:
2175 case AtomicExpr::AO__atomic_compare_exchange_n:
2176 Form = GNUCmpXchg;
2177 break;
2178 }
2179
2180 // Check we have the right number of arguments.
2181 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002182 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002183 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002184 << TheCall->getCallee()->getSourceRange();
2185 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002186 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2187 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002188 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002189 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002190 << TheCall->getCallee()->getSourceRange();
2191 return ExprError();
2192 }
2193
Richard Smithfeea8832012-04-12 05:08:17 +00002194 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002195 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002196 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
2197 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2198 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002199 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002200 << Ptr->getType() << Ptr->getSourceRange();
2201 return ExprError();
2202 }
2203
Richard Smithfeea8832012-04-12 05:08:17 +00002204 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2205 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2206 QualType ValType = AtomTy; // 'C'
2207 if (IsC11) {
2208 if (!AtomTy->isAtomicType()) {
2209 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2210 << Ptr->getType() << Ptr->getSourceRange();
2211 return ExprError();
2212 }
Richard Smithe00921a2012-09-15 06:09:58 +00002213 if (AtomTy.isConstQualified()) {
2214 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2215 << Ptr->getType() << Ptr->getSourceRange();
2216 return ExprError();
2217 }
Richard Smithfeea8832012-04-12 05:08:17 +00002218 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002219 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002220 if (ValType.isConstQualified()) {
2221 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2222 << Ptr->getType() << Ptr->getSourceRange();
2223 return ExprError();
2224 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002225 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002226
Richard Smithfeea8832012-04-12 05:08:17 +00002227 // For an arithmetic operation, the implied arithmetic must be well-formed.
2228 if (Form == Arithmetic) {
2229 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2230 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2231 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2232 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2233 return ExprError();
2234 }
2235 if (!IsAddSub && !ValType->isIntegerType()) {
2236 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2237 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2238 return ExprError();
2239 }
David Majnemere85cff82015-01-28 05:48:06 +00002240 if (IsC11 && ValType->isPointerType() &&
2241 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2242 diag::err_incomplete_type)) {
2243 return ExprError();
2244 }
Richard Smithfeea8832012-04-12 05:08:17 +00002245 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2246 // For __atomic_*_n operations, the value type must be a scalar integral or
2247 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002248 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002249 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2250 return ExprError();
2251 }
2252
Eli Friedmanaa769812013-09-11 03:49:34 +00002253 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2254 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002255 // For GNU atomics, require a trivially-copyable type. This is not part of
2256 // the GNU atomics specification, but we enforce it for sanity.
2257 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002258 << Ptr->getType() << Ptr->getSourceRange();
2259 return ExprError();
2260 }
2261
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002262 switch (ValType.getObjCLifetime()) {
2263 case Qualifiers::OCL_None:
2264 case Qualifiers::OCL_ExplicitNone:
2265 // okay
2266 break;
2267
2268 case Qualifiers::OCL_Weak:
2269 case Qualifiers::OCL_Strong:
2270 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002271 // FIXME: Can this happen? By this point, ValType should be known
2272 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002273 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2274 << ValType << Ptr->getSourceRange();
2275 return ExprError();
2276 }
2277
David Majnemerc6eb6502015-06-03 00:26:35 +00002278 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2279 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002280 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002281 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002282 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002283 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002284 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002285 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002286 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002287 ResultType = Context.BoolTy;
2288
Richard Smithfeea8832012-04-12 05:08:17 +00002289 // The type of a parameter passed 'by value'. In the GNU atomics, such
2290 // arguments are actually passed as pointers.
2291 QualType ByValType = ValType; // 'CP'
2292 if (!IsC11 && !IsN)
2293 ByValType = Ptr->getType();
2294
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002295 // The first argument --- the pointer --- has a fixed type; we
2296 // deduce the types of the rest of the arguments accordingly. Walk
2297 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002298 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002299 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002300 if (i < NumVals[Form] + 1) {
2301 switch (i) {
2302 case 1:
2303 // The second argument is the non-atomic operand. For arithmetic, this
2304 // is always passed by value, and for a compare_exchange it is always
2305 // passed by address. For the rest, GNU uses by-address and C11 uses
2306 // by-value.
2307 assert(Form != Load);
2308 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2309 Ty = ValType;
2310 else if (Form == Copy || Form == Xchg)
2311 Ty = ByValType;
2312 else if (Form == Arithmetic)
2313 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002314 else {
2315 Expr *ValArg = TheCall->getArg(i);
2316 unsigned AS = 0;
2317 // Keep address space of non-atomic pointer type.
2318 if (const PointerType *PtrTy =
2319 ValArg->getType()->getAs<PointerType>()) {
2320 AS = PtrTy->getPointeeType().getAddressSpace();
2321 }
2322 Ty = Context.getPointerType(
2323 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2324 }
Richard Smithfeea8832012-04-12 05:08:17 +00002325 break;
2326 case 2:
2327 // The third argument to compare_exchange / GNU exchange is a
2328 // (pointer to a) desired value.
2329 Ty = ByValType;
2330 break;
2331 case 3:
2332 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2333 Ty = Context.BoolTy;
2334 break;
2335 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002336 } else {
2337 // The order(s) are always converted to int.
2338 Ty = Context.IntTy;
2339 }
Richard Smithfeea8832012-04-12 05:08:17 +00002340
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002341 InitializedEntity Entity =
2342 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002343 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002344 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2345 if (Arg.isInvalid())
2346 return true;
2347 TheCall->setArg(i, Arg.get());
2348 }
2349
Richard Smithfeea8832012-04-12 05:08:17 +00002350 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002351 SmallVector<Expr*, 5> SubExprs;
2352 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002353 switch (Form) {
2354 case Init:
2355 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002356 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002357 break;
2358 case Load:
2359 SubExprs.push_back(TheCall->getArg(1)); // Order
2360 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002361 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002362 case Copy:
2363 case Arithmetic:
2364 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002365 SubExprs.push_back(TheCall->getArg(2)); // Order
2366 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002367 break;
2368 case GNUXchg:
2369 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2370 SubExprs.push_back(TheCall->getArg(3)); // Order
2371 SubExprs.push_back(TheCall->getArg(1)); // Val1
2372 SubExprs.push_back(TheCall->getArg(2)); // Val2
2373 break;
2374 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002375 SubExprs.push_back(TheCall->getArg(3)); // Order
2376 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002377 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002378 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002379 break;
2380 case GNUCmpXchg:
2381 SubExprs.push_back(TheCall->getArg(4)); // Order
2382 SubExprs.push_back(TheCall->getArg(1)); // Val1
2383 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2384 SubExprs.push_back(TheCall->getArg(2)); // Val2
2385 SubExprs.push_back(TheCall->getArg(3)); // Weak
2386 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002387 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002388
2389 if (SubExprs.size() >= 2 && Form != Init) {
2390 llvm::APSInt Result(32);
2391 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2392 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002393 Diag(SubExprs[1]->getLocStart(),
2394 diag::warn_atomic_op_has_invalid_memory_order)
2395 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002396 }
2397
Fariborz Jahanian615de762013-05-28 17:37:39 +00002398 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2399 SubExprs, ResultType, Op,
2400 TheCall->getRParenLoc());
2401
2402 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2403 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2404 Context.AtomicUsesUnsupportedLibcall(AE))
2405 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2406 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002407
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002408 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002409}
2410
John McCall29ad95b2011-08-27 01:09:30 +00002411/// checkBuiltinArgument - Given a call to a builtin function, perform
2412/// normal type-checking on the given argument, updating the call in
2413/// place. This is useful when a builtin function requires custom
2414/// type-checking for some of its arguments but not necessarily all of
2415/// them.
2416///
2417/// Returns true on error.
2418static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2419 FunctionDecl *Fn = E->getDirectCallee();
2420 assert(Fn && "builtin call without direct callee!");
2421
2422 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2423 InitializedEntity Entity =
2424 InitializedEntity::InitializeParameter(S.Context, Param);
2425
2426 ExprResult Arg = E->getArg(0);
2427 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2428 if (Arg.isInvalid())
2429 return true;
2430
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002431 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002432 return false;
2433}
2434
Chris Lattnerdc046542009-05-08 06:58:22 +00002435/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2436/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2437/// type of its first argument. The main ActOnCallExpr routines have already
2438/// promoted the types of arguments because all of these calls are prototyped as
2439/// void(...).
2440///
2441/// This function goes through and does final semantic checking for these
2442/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002443ExprResult
2444Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002445 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002446 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2447 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2448
2449 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002450 if (TheCall->getNumArgs() < 1) {
2451 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2452 << 0 << 1 << TheCall->getNumArgs()
2453 << TheCall->getCallee()->getSourceRange();
2454 return ExprError();
2455 }
Mike Stump11289f42009-09-09 15:08:12 +00002456
Chris Lattnerdc046542009-05-08 06:58:22 +00002457 // Inspect the first argument of the atomic builtin. This should always be
2458 // a pointer type, whose element is an integral scalar or pointer type.
2459 // Because it is a pointer type, we don't have to worry about any implicit
2460 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002461 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002462 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002463 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2464 if (FirstArgResult.isInvalid())
2465 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002466 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002467 TheCall->setArg(0, FirstArg);
2468
John McCall31168b02011-06-15 23:02:42 +00002469 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2470 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002471 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2472 << FirstArg->getType() << FirstArg->getSourceRange();
2473 return ExprError();
2474 }
Mike Stump11289f42009-09-09 15:08:12 +00002475
John McCall31168b02011-06-15 23:02:42 +00002476 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002477 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002478 !ValType->isBlockPointerType()) {
2479 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2480 << FirstArg->getType() << FirstArg->getSourceRange();
2481 return ExprError();
2482 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002483
John McCall31168b02011-06-15 23:02:42 +00002484 switch (ValType.getObjCLifetime()) {
2485 case Qualifiers::OCL_None:
2486 case Qualifiers::OCL_ExplicitNone:
2487 // okay
2488 break;
2489
2490 case Qualifiers::OCL_Weak:
2491 case Qualifiers::OCL_Strong:
2492 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002493 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002494 << ValType << FirstArg->getSourceRange();
2495 return ExprError();
2496 }
2497
John McCallb50451a2011-10-05 07:41:44 +00002498 // Strip any qualifiers off ValType.
2499 ValType = ValType.getUnqualifiedType();
2500
Chandler Carruth3973af72010-07-18 20:54:12 +00002501 // The majority of builtins return a value, but a few have special return
2502 // types, so allow them to override appropriately below.
2503 QualType ResultType = ValType;
2504
Chris Lattnerdc046542009-05-08 06:58:22 +00002505 // We need to figure out which concrete builtin this maps onto. For example,
2506 // __sync_fetch_and_add with a 2 byte object turns into
2507 // __sync_fetch_and_add_2.
2508#define BUILTIN_ROW(x) \
2509 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2510 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002511
Chris Lattnerdc046542009-05-08 06:58:22 +00002512 static const unsigned BuiltinIndices[][5] = {
2513 BUILTIN_ROW(__sync_fetch_and_add),
2514 BUILTIN_ROW(__sync_fetch_and_sub),
2515 BUILTIN_ROW(__sync_fetch_and_or),
2516 BUILTIN_ROW(__sync_fetch_and_and),
2517 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002518 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002519
Chris Lattnerdc046542009-05-08 06:58:22 +00002520 BUILTIN_ROW(__sync_add_and_fetch),
2521 BUILTIN_ROW(__sync_sub_and_fetch),
2522 BUILTIN_ROW(__sync_and_and_fetch),
2523 BUILTIN_ROW(__sync_or_and_fetch),
2524 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002525 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002526
Chris Lattnerdc046542009-05-08 06:58:22 +00002527 BUILTIN_ROW(__sync_val_compare_and_swap),
2528 BUILTIN_ROW(__sync_bool_compare_and_swap),
2529 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002530 BUILTIN_ROW(__sync_lock_release),
2531 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002532 };
Mike Stump11289f42009-09-09 15:08:12 +00002533#undef BUILTIN_ROW
2534
Chris Lattnerdc046542009-05-08 06:58:22 +00002535 // Determine the index of the size.
2536 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002537 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002538 case 1: SizeIndex = 0; break;
2539 case 2: SizeIndex = 1; break;
2540 case 4: SizeIndex = 2; break;
2541 case 8: SizeIndex = 3; break;
2542 case 16: SizeIndex = 4; break;
2543 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002544 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2545 << FirstArg->getType() << FirstArg->getSourceRange();
2546 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002547 }
Mike Stump11289f42009-09-09 15:08:12 +00002548
Chris Lattnerdc046542009-05-08 06:58:22 +00002549 // Each of these builtins has one pointer argument, followed by some number of
2550 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2551 // that we ignore. Find out which row of BuiltinIndices to read from as well
2552 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002553 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002554 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002555 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002556 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002557 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002558 case Builtin::BI__sync_fetch_and_add:
2559 case Builtin::BI__sync_fetch_and_add_1:
2560 case Builtin::BI__sync_fetch_and_add_2:
2561 case Builtin::BI__sync_fetch_and_add_4:
2562 case Builtin::BI__sync_fetch_and_add_8:
2563 case Builtin::BI__sync_fetch_and_add_16:
2564 BuiltinIndex = 0;
2565 break;
2566
2567 case Builtin::BI__sync_fetch_and_sub:
2568 case Builtin::BI__sync_fetch_and_sub_1:
2569 case Builtin::BI__sync_fetch_and_sub_2:
2570 case Builtin::BI__sync_fetch_and_sub_4:
2571 case Builtin::BI__sync_fetch_and_sub_8:
2572 case Builtin::BI__sync_fetch_and_sub_16:
2573 BuiltinIndex = 1;
2574 break;
2575
2576 case Builtin::BI__sync_fetch_and_or:
2577 case Builtin::BI__sync_fetch_and_or_1:
2578 case Builtin::BI__sync_fetch_and_or_2:
2579 case Builtin::BI__sync_fetch_and_or_4:
2580 case Builtin::BI__sync_fetch_and_or_8:
2581 case Builtin::BI__sync_fetch_and_or_16:
2582 BuiltinIndex = 2;
2583 break;
2584
2585 case Builtin::BI__sync_fetch_and_and:
2586 case Builtin::BI__sync_fetch_and_and_1:
2587 case Builtin::BI__sync_fetch_and_and_2:
2588 case Builtin::BI__sync_fetch_and_and_4:
2589 case Builtin::BI__sync_fetch_and_and_8:
2590 case Builtin::BI__sync_fetch_and_and_16:
2591 BuiltinIndex = 3;
2592 break;
Mike Stump11289f42009-09-09 15:08:12 +00002593
Douglas Gregor73722482011-11-28 16:30:08 +00002594 case Builtin::BI__sync_fetch_and_xor:
2595 case Builtin::BI__sync_fetch_and_xor_1:
2596 case Builtin::BI__sync_fetch_and_xor_2:
2597 case Builtin::BI__sync_fetch_and_xor_4:
2598 case Builtin::BI__sync_fetch_and_xor_8:
2599 case Builtin::BI__sync_fetch_and_xor_16:
2600 BuiltinIndex = 4;
2601 break;
2602
Hal Finkeld2208b52014-10-02 20:53:50 +00002603 case Builtin::BI__sync_fetch_and_nand:
2604 case Builtin::BI__sync_fetch_and_nand_1:
2605 case Builtin::BI__sync_fetch_and_nand_2:
2606 case Builtin::BI__sync_fetch_and_nand_4:
2607 case Builtin::BI__sync_fetch_and_nand_8:
2608 case Builtin::BI__sync_fetch_and_nand_16:
2609 BuiltinIndex = 5;
2610 WarnAboutSemanticsChange = true;
2611 break;
2612
Douglas Gregor73722482011-11-28 16:30:08 +00002613 case Builtin::BI__sync_add_and_fetch:
2614 case Builtin::BI__sync_add_and_fetch_1:
2615 case Builtin::BI__sync_add_and_fetch_2:
2616 case Builtin::BI__sync_add_and_fetch_4:
2617 case Builtin::BI__sync_add_and_fetch_8:
2618 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002619 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002620 break;
2621
2622 case Builtin::BI__sync_sub_and_fetch:
2623 case Builtin::BI__sync_sub_and_fetch_1:
2624 case Builtin::BI__sync_sub_and_fetch_2:
2625 case Builtin::BI__sync_sub_and_fetch_4:
2626 case Builtin::BI__sync_sub_and_fetch_8:
2627 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002628 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002629 break;
2630
2631 case Builtin::BI__sync_and_and_fetch:
2632 case Builtin::BI__sync_and_and_fetch_1:
2633 case Builtin::BI__sync_and_and_fetch_2:
2634 case Builtin::BI__sync_and_and_fetch_4:
2635 case Builtin::BI__sync_and_and_fetch_8:
2636 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002637 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002638 break;
2639
2640 case Builtin::BI__sync_or_and_fetch:
2641 case Builtin::BI__sync_or_and_fetch_1:
2642 case Builtin::BI__sync_or_and_fetch_2:
2643 case Builtin::BI__sync_or_and_fetch_4:
2644 case Builtin::BI__sync_or_and_fetch_8:
2645 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002646 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002647 break;
2648
2649 case Builtin::BI__sync_xor_and_fetch:
2650 case Builtin::BI__sync_xor_and_fetch_1:
2651 case Builtin::BI__sync_xor_and_fetch_2:
2652 case Builtin::BI__sync_xor_and_fetch_4:
2653 case Builtin::BI__sync_xor_and_fetch_8:
2654 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002655 BuiltinIndex = 10;
2656 break;
2657
2658 case Builtin::BI__sync_nand_and_fetch:
2659 case Builtin::BI__sync_nand_and_fetch_1:
2660 case Builtin::BI__sync_nand_and_fetch_2:
2661 case Builtin::BI__sync_nand_and_fetch_4:
2662 case Builtin::BI__sync_nand_and_fetch_8:
2663 case Builtin::BI__sync_nand_and_fetch_16:
2664 BuiltinIndex = 11;
2665 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002666 break;
Mike Stump11289f42009-09-09 15:08:12 +00002667
Chris Lattnerdc046542009-05-08 06:58:22 +00002668 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002669 case Builtin::BI__sync_val_compare_and_swap_1:
2670 case Builtin::BI__sync_val_compare_and_swap_2:
2671 case Builtin::BI__sync_val_compare_and_swap_4:
2672 case Builtin::BI__sync_val_compare_and_swap_8:
2673 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002674 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002675 NumFixed = 2;
2676 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002677
Chris Lattnerdc046542009-05-08 06:58:22 +00002678 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002679 case Builtin::BI__sync_bool_compare_and_swap_1:
2680 case Builtin::BI__sync_bool_compare_and_swap_2:
2681 case Builtin::BI__sync_bool_compare_and_swap_4:
2682 case Builtin::BI__sync_bool_compare_and_swap_8:
2683 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002684 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002685 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002686 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002687 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002688
2689 case Builtin::BI__sync_lock_test_and_set:
2690 case Builtin::BI__sync_lock_test_and_set_1:
2691 case Builtin::BI__sync_lock_test_and_set_2:
2692 case Builtin::BI__sync_lock_test_and_set_4:
2693 case Builtin::BI__sync_lock_test_and_set_8:
2694 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002695 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002696 break;
2697
Chris Lattnerdc046542009-05-08 06:58:22 +00002698 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002699 case Builtin::BI__sync_lock_release_1:
2700 case Builtin::BI__sync_lock_release_2:
2701 case Builtin::BI__sync_lock_release_4:
2702 case Builtin::BI__sync_lock_release_8:
2703 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002704 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002705 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002706 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002707 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002708
2709 case Builtin::BI__sync_swap:
2710 case Builtin::BI__sync_swap_1:
2711 case Builtin::BI__sync_swap_2:
2712 case Builtin::BI__sync_swap_4:
2713 case Builtin::BI__sync_swap_8:
2714 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002715 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002716 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002717 }
Mike Stump11289f42009-09-09 15:08:12 +00002718
Chris Lattnerdc046542009-05-08 06:58:22 +00002719 // Now that we know how many fixed arguments we expect, first check that we
2720 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002721 if (TheCall->getNumArgs() < 1+NumFixed) {
2722 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2723 << 0 << 1+NumFixed << TheCall->getNumArgs()
2724 << TheCall->getCallee()->getSourceRange();
2725 return ExprError();
2726 }
Mike Stump11289f42009-09-09 15:08:12 +00002727
Hal Finkeld2208b52014-10-02 20:53:50 +00002728 if (WarnAboutSemanticsChange) {
2729 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2730 << TheCall->getCallee()->getSourceRange();
2731 }
2732
Chris Lattner5b9241b2009-05-08 15:36:58 +00002733 // Get the decl for the concrete builtin from this, we can tell what the
2734 // concrete integer type we should convert to is.
2735 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002736 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002737 FunctionDecl *NewBuiltinDecl;
2738 if (NewBuiltinID == BuiltinID)
2739 NewBuiltinDecl = FDecl;
2740 else {
2741 // Perform builtin lookup to avoid redeclaring it.
2742 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2743 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2744 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2745 assert(Res.getFoundDecl());
2746 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002747 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002748 return ExprError();
2749 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002750
John McCallcf142162010-08-07 06:22:56 +00002751 // The first argument --- the pointer --- has a fixed type; we
2752 // deduce the types of the rest of the arguments accordingly. Walk
2753 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002754 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002755 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002756
Chris Lattnerdc046542009-05-08 06:58:22 +00002757 // GCC does an implicit conversion to the pointer or integer ValType. This
2758 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002759 // Initialize the argument.
2760 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2761 ValType, /*consume*/ false);
2762 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002763 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002764 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002765
Chris Lattnerdc046542009-05-08 06:58:22 +00002766 // Okay, we have something that *can* be converted to the right type. Check
2767 // to see if there is a potentially weird extension going on here. This can
2768 // happen when you do an atomic operation on something like an char* and
2769 // pass in 42. The 42 gets converted to char. This is even more strange
2770 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002771 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002772 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002773 }
Mike Stump11289f42009-09-09 15:08:12 +00002774
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002775 ASTContext& Context = this->getASTContext();
2776
2777 // Create a new DeclRefExpr to refer to the new decl.
2778 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2779 Context,
2780 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002781 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002782 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002783 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002784 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002785 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002786 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002787
Chris Lattnerdc046542009-05-08 06:58:22 +00002788 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002789 // FIXME: This loses syntactic information.
2790 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2791 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2792 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002793 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002794
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002795 // Change the result type of the call to match the original value type. This
2796 // is arbitrary, but the codegen for these builtins ins design to handle it
2797 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002798 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002799
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002800 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002801}
2802
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002803/// SemaBuiltinNontemporalOverloaded - We have a call to
2804/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2805/// overloaded function based on the pointer type of its last argument.
2806///
2807/// This function goes through and does final semantic checking for these
2808/// builtins.
2809ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2810 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2811 DeclRefExpr *DRE =
2812 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2813 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2814 unsigned BuiltinID = FDecl->getBuiltinID();
2815 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2816 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2817 "Unexpected nontemporal load/store builtin!");
2818 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2819 unsigned numArgs = isStore ? 2 : 1;
2820
2821 // Ensure that we have the proper number of arguments.
2822 if (checkArgCount(*this, TheCall, numArgs))
2823 return ExprError();
2824
2825 // Inspect the last argument of the nontemporal builtin. This should always
2826 // be a pointer type, from which we imply the type of the memory access.
2827 // Because it is a pointer type, we don't have to worry about any implicit
2828 // casts here.
2829 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2830 ExprResult PointerArgResult =
2831 DefaultFunctionArrayLvalueConversion(PointerArg);
2832
2833 if (PointerArgResult.isInvalid())
2834 return ExprError();
2835 PointerArg = PointerArgResult.get();
2836 TheCall->setArg(numArgs - 1, PointerArg);
2837
2838 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2839 if (!pointerType) {
2840 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2841 << PointerArg->getType() << PointerArg->getSourceRange();
2842 return ExprError();
2843 }
2844
2845 QualType ValType = pointerType->getPointeeType();
2846
2847 // Strip any qualifiers off ValType.
2848 ValType = ValType.getUnqualifiedType();
2849 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2850 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2851 !ValType->isVectorType()) {
2852 Diag(DRE->getLocStart(),
2853 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2854 << PointerArg->getType() << PointerArg->getSourceRange();
2855 return ExprError();
2856 }
2857
2858 if (!isStore) {
2859 TheCall->setType(ValType);
2860 return TheCallResult;
2861 }
2862
2863 ExprResult ValArg = TheCall->getArg(0);
2864 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2865 Context, ValType, /*consume*/ false);
2866 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2867 if (ValArg.isInvalid())
2868 return ExprError();
2869
2870 TheCall->setArg(0, ValArg.get());
2871 TheCall->setType(Context.VoidTy);
2872 return TheCallResult;
2873}
2874
Chris Lattner6436fb62009-02-18 06:01:06 +00002875/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002876/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002877/// Note: It might also make sense to do the UTF-16 conversion here (would
2878/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002879bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002880 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002881 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2882
Douglas Gregorfb65e592011-07-27 05:40:30 +00002883 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002884 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2885 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002886 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002887 }
Mike Stump11289f42009-09-09 15:08:12 +00002888
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002889 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002890 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002891 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002892 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002893 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002894 UTF16 *ToPtr = &ToBuf[0];
2895
2896 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2897 &ToPtr, ToPtr + NumBytes,
2898 strictConversion);
2899 // Check for conversion failure.
2900 if (Result != conversionOK)
2901 Diag(Arg->getLocStart(),
2902 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2903 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002904 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002905}
2906
Charles Davisc7d5c942015-09-17 20:55:33 +00002907/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2908/// for validity. Emit an error and return true on failure; return false
2909/// on success.
2910bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002911 Expr *Fn = TheCall->getCallee();
2912 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002913 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002914 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002915 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2916 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002917 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002918 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002919 return true;
2920 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002921
2922 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002923 return Diag(TheCall->getLocEnd(),
2924 diag::err_typecheck_call_too_few_args_at_least)
2925 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002926 }
2927
John McCall29ad95b2011-08-27 01:09:30 +00002928 // Type-check the first argument normally.
2929 if (checkBuiltinArgument(*this, TheCall, 0))
2930 return true;
2931
Chris Lattnere202e6a2007-12-20 00:05:45 +00002932 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002933 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002934 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002935 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002936 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002937 else if (FunctionDecl *FD = getCurFunctionDecl())
2938 isVariadic = FD->isVariadic();
2939 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002940 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002941
Chris Lattnere202e6a2007-12-20 00:05:45 +00002942 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002943 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2944 return true;
2945 }
Mike Stump11289f42009-09-09 15:08:12 +00002946
Chris Lattner43be2e62007-12-19 23:59:04 +00002947 // Verify that the second argument to the builtin is the last argument of the
2948 // current function or method.
2949 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002950 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002951
Nico Weber9eea7642013-05-24 23:31:57 +00002952 // These are valid if SecondArgIsLastNamedArgument is false after the next
2953 // block.
2954 QualType Type;
2955 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00002956 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00002957
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002958 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2959 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002960 // FIXME: This isn't correct for methods (results in bogus warning).
2961 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002962 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002963 if (CurBlock)
2964 LastArg = *(CurBlock->TheDecl->param_end()-1);
2965 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002966 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002967 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002968 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002969 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002970
2971 Type = PV->getType();
2972 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00002973 IsCRegister =
2974 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00002975 }
2976 }
Mike Stump11289f42009-09-09 15:08:12 +00002977
Chris Lattner43be2e62007-12-19 23:59:04 +00002978 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002979 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00002980 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00002981 else if (IsCRegister || Type->isReferenceType() ||
2982 Type->isPromotableIntegerType() ||
2983 Type->isSpecificBuiltinType(BuiltinType::Float)) {
2984 unsigned Reason = 0;
2985 if (Type->isReferenceType()) Reason = 1;
2986 else if (IsCRegister) Reason = 2;
2987 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00002988 Diag(ParamLoc, diag::note_parameter_type) << Type;
2989 }
2990
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002991 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002992 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002993}
Chris Lattner43be2e62007-12-19 23:59:04 +00002994
Charles Davisc7d5c942015-09-17 20:55:33 +00002995/// Check the arguments to '__builtin_va_start' for validity, and that
2996/// it was called from a function of the native ABI.
2997/// Emit an error and return true on failure; return false on success.
2998bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2999 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3000 // On x64 Windows, don't allow this in System V ABI functions.
3001 // (Yes, that means there's no corresponding way to support variadic
3002 // System V ABI functions on Windows.)
3003 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3004 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3005 clang::CallingConv CC = CC_C;
3006 if (const FunctionDecl *FD = getCurFunctionDecl())
3007 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3008 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3009 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3010 return Diag(TheCall->getCallee()->getLocStart(),
3011 diag::err_va_start_used_in_wrong_abi_function)
3012 << (OS != llvm::Triple::Win32);
3013 }
3014 return SemaBuiltinVAStartImpl(TheCall);
3015}
3016
3017/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3018/// it was called from a Win64 ABI function.
3019/// Emit an error and return true on failure; return false on success.
3020bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3021 // This only makes sense for x86-64.
3022 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3023 Expr *Callee = TheCall->getCallee();
3024 if (TT.getArch() != llvm::Triple::x86_64)
3025 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3026 // Don't allow this in System V ABI functions.
3027 clang::CallingConv CC = CC_C;
3028 if (const FunctionDecl *FD = getCurFunctionDecl())
3029 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3030 if (CC == CC_X86_64SysV ||
3031 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3032 return Diag(Callee->getLocStart(),
3033 diag::err_ms_va_start_used_in_sysv_function);
3034 return SemaBuiltinVAStartImpl(TheCall);
3035}
3036
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003037bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3038 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3039 // const char *named_addr);
3040
3041 Expr *Func = Call->getCallee();
3042
3043 if (Call->getNumArgs() < 3)
3044 return Diag(Call->getLocEnd(),
3045 diag::err_typecheck_call_too_few_args_at_least)
3046 << 0 /*function call*/ << 3 << Call->getNumArgs();
3047
3048 // Determine whether the current function is variadic or not.
3049 bool IsVariadic;
3050 if (BlockScopeInfo *CurBlock = getCurBlock())
3051 IsVariadic = CurBlock->TheDecl->isVariadic();
3052 else if (FunctionDecl *FD = getCurFunctionDecl())
3053 IsVariadic = FD->isVariadic();
3054 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3055 IsVariadic = MD->isVariadic();
3056 else
3057 llvm_unreachable("unexpected statement type");
3058
3059 if (!IsVariadic) {
3060 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3061 return true;
3062 }
3063
3064 // Type-check the first argument normally.
3065 if (checkBuiltinArgument(*this, Call, 0))
3066 return true;
3067
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003068 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003069 unsigned ArgNo;
3070 QualType Type;
3071 } ArgumentTypes[] = {
3072 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3073 { 2, Context.getSizeType() },
3074 };
3075
3076 for (const auto &AT : ArgumentTypes) {
3077 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3078 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3079 continue;
3080 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3081 << Arg->getType() << AT.Type << 1 /* different class */
3082 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3083 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3084 }
3085
3086 return false;
3087}
3088
Chris Lattner2da14fb2007-12-20 00:26:33 +00003089/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3090/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003091bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3092 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003093 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003094 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003095 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003096 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003097 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003098 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003099 << SourceRange(TheCall->getArg(2)->getLocStart(),
3100 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003101
John Wiegley01296292011-04-08 18:41:53 +00003102 ExprResult OrigArg0 = TheCall->getArg(0);
3103 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003104
Chris Lattner2da14fb2007-12-20 00:26:33 +00003105 // Do standard promotions between the two arguments, returning their common
3106 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003107 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003108 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3109 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003110
3111 // Make sure any conversions are pushed back into the call; this is
3112 // type safe since unordered compare builtins are declared as "_Bool
3113 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003114 TheCall->setArg(0, OrigArg0.get());
3115 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003116
John Wiegley01296292011-04-08 18:41:53 +00003117 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003118 return false;
3119
Chris Lattner2da14fb2007-12-20 00:26:33 +00003120 // If the common type isn't a real floating type, then the arguments were
3121 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003122 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003123 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003124 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003125 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3126 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003127
Chris Lattner2da14fb2007-12-20 00:26:33 +00003128 return false;
3129}
3130
Benjamin Kramer634fc102010-02-15 22:42:31 +00003131/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3132/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003133/// to check everything. We expect the last argument to be a floating point
3134/// value.
3135bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3136 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003137 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003138 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003139 if (TheCall->getNumArgs() > NumArgs)
3140 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003141 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003142 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003143 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003144 (*(TheCall->arg_end()-1))->getLocEnd());
3145
Benjamin Kramer64aae502010-02-16 10:07:31 +00003146 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003147
Eli Friedman7e4faac2009-08-31 20:06:00 +00003148 if (OrigArg->isTypeDependent())
3149 return false;
3150
Chris Lattner68784ef2010-05-06 05:50:07 +00003151 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003152 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003153 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003154 diag::err_typecheck_call_invalid_unary_fp)
3155 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003156
Chris Lattner68784ef2010-05-06 05:50:07 +00003157 // If this is an implicit conversion from float -> double, remove it.
3158 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3159 Expr *CastArg = Cast->getSubExpr();
3160 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3161 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3162 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003163 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003164 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003165 }
3166 }
3167
Eli Friedman7e4faac2009-08-31 20:06:00 +00003168 return false;
3169}
3170
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003171/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3172// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003173ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003174 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003175 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003176 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003177 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3178 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003179
Nate Begemana0110022010-06-08 00:16:34 +00003180 // Determine which of the following types of shufflevector we're checking:
3181 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003182 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003183 QualType resType = TheCall->getArg(0)->getType();
3184 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003185
Douglas Gregorc25f7662009-05-19 22:10:17 +00003186 if (!TheCall->getArg(0)->isTypeDependent() &&
3187 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003188 QualType LHSType = TheCall->getArg(0)->getType();
3189 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003190
Craig Topperbaca3892013-07-29 06:47:04 +00003191 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3192 return ExprError(Diag(TheCall->getLocStart(),
3193 diag::err_shufflevector_non_vector)
3194 << SourceRange(TheCall->getArg(0)->getLocStart(),
3195 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003196
Nate Begemana0110022010-06-08 00:16:34 +00003197 numElements = LHSType->getAs<VectorType>()->getNumElements();
3198 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003199
Nate Begemana0110022010-06-08 00:16:34 +00003200 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3201 // with mask. If so, verify that RHS is an integer vector type with the
3202 // same number of elts as lhs.
3203 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003204 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003205 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003206 return ExprError(Diag(TheCall->getLocStart(),
3207 diag::err_shufflevector_incompatible_vector)
3208 << SourceRange(TheCall->getArg(1)->getLocStart(),
3209 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003210 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003211 return ExprError(Diag(TheCall->getLocStart(),
3212 diag::err_shufflevector_incompatible_vector)
3213 << SourceRange(TheCall->getArg(0)->getLocStart(),
3214 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003215 } else if (numElements != numResElements) {
3216 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003217 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003218 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003219 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003220 }
3221
3222 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003223 if (TheCall->getArg(i)->isTypeDependent() ||
3224 TheCall->getArg(i)->isValueDependent())
3225 continue;
3226
Nate Begemana0110022010-06-08 00:16:34 +00003227 llvm::APSInt Result(32);
3228 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3229 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003230 diag::err_shufflevector_nonconstant_argument)
3231 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003232
Craig Topper50ad5b72013-08-03 17:40:38 +00003233 // Allow -1 which will be translated to undef in the IR.
3234 if (Result.isSigned() && Result.isAllOnesValue())
3235 continue;
3236
Chris Lattner7ab824e2008-08-10 02:05:13 +00003237 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003238 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003239 diag::err_shufflevector_argument_too_large)
3240 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003241 }
3242
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003243 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003244
Chris Lattner7ab824e2008-08-10 02:05:13 +00003245 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003246 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003247 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003248 }
3249
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003250 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3251 TheCall->getCallee()->getLocStart(),
3252 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003253}
Chris Lattner43be2e62007-12-19 23:59:04 +00003254
Hal Finkelc4d7c822013-09-18 03:29:45 +00003255/// SemaConvertVectorExpr - Handle __builtin_convertvector
3256ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3257 SourceLocation BuiltinLoc,
3258 SourceLocation RParenLoc) {
3259 ExprValueKind VK = VK_RValue;
3260 ExprObjectKind OK = OK_Ordinary;
3261 QualType DstTy = TInfo->getType();
3262 QualType SrcTy = E->getType();
3263
3264 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3265 return ExprError(Diag(BuiltinLoc,
3266 diag::err_convertvector_non_vector)
3267 << E->getSourceRange());
3268 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3269 return ExprError(Diag(BuiltinLoc,
3270 diag::err_convertvector_non_vector_type));
3271
3272 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3273 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3274 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3275 if (SrcElts != DstElts)
3276 return ExprError(Diag(BuiltinLoc,
3277 diag::err_convertvector_incompatible_vector)
3278 << E->getSourceRange());
3279 }
3280
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003281 return new (Context)
3282 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003283}
3284
Daniel Dunbarb7257262008-07-21 22:59:13 +00003285/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3286// This is declared to take (const void*, ...) and can take two
3287// optional constant int args.
3288bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003289 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003290
Chris Lattner3b054132008-11-19 05:08:23 +00003291 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003292 return Diag(TheCall->getLocEnd(),
3293 diag::err_typecheck_call_too_many_args_at_most)
3294 << 0 /*function call*/ << 3 << NumArgs
3295 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003296
3297 // Argument 0 is checked for us and the remaining arguments must be
3298 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003299 for (unsigned i = 1; i != NumArgs; ++i)
3300 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003301 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003302
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003303 return false;
3304}
3305
Hal Finkelf0417332014-07-17 14:25:55 +00003306/// SemaBuiltinAssume - Handle __assume (MS Extension).
3307// __assume does not evaluate its arguments, and should warn if its argument
3308// has side effects.
3309bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3310 Expr *Arg = TheCall->getArg(0);
3311 if (Arg->isInstantiationDependent()) return false;
3312
3313 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003314 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003315 << Arg->getSourceRange()
3316 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3317
3318 return false;
3319}
3320
3321/// Handle __builtin_assume_aligned. This is declared
3322/// as (const void*, size_t, ...) and can take one optional constant int arg.
3323bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3324 unsigned NumArgs = TheCall->getNumArgs();
3325
3326 if (NumArgs > 3)
3327 return Diag(TheCall->getLocEnd(),
3328 diag::err_typecheck_call_too_many_args_at_most)
3329 << 0 /*function call*/ << 3 << NumArgs
3330 << TheCall->getSourceRange();
3331
3332 // The alignment must be a constant integer.
3333 Expr *Arg = TheCall->getArg(1);
3334
3335 // We can't check the value of a dependent argument.
3336 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3337 llvm::APSInt Result;
3338 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3339 return true;
3340
3341 if (!Result.isPowerOf2())
3342 return Diag(TheCall->getLocStart(),
3343 diag::err_alignment_not_power_of_two)
3344 << Arg->getSourceRange();
3345 }
3346
3347 if (NumArgs > 2) {
3348 ExprResult Arg(TheCall->getArg(2));
3349 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3350 Context.getSizeType(), false);
3351 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3352 if (Arg.isInvalid()) return true;
3353 TheCall->setArg(2, Arg.get());
3354 }
Hal Finkelf0417332014-07-17 14:25:55 +00003355
3356 return false;
3357}
3358
Eric Christopher8d0c6212010-04-17 02:26:23 +00003359/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3360/// TheCall is a constant expression.
3361bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3362 llvm::APSInt &Result) {
3363 Expr *Arg = TheCall->getArg(ArgNum);
3364 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3365 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3366
3367 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3368
3369 if (!Arg->isIntegerConstantExpr(Result, Context))
3370 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003371 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003372
Chris Lattnerd545ad12009-09-23 06:06:36 +00003373 return false;
3374}
3375
Richard Sandiford28940af2014-04-16 08:47:51 +00003376/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3377/// TheCall is a constant expression in the range [Low, High].
3378bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3379 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003380 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003381
3382 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003383 Expr *Arg = TheCall->getArg(ArgNum);
3384 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003385 return false;
3386
Eric Christopher8d0c6212010-04-17 02:26:23 +00003387 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003388 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003389 return true;
3390
Richard Sandiford28940af2014-04-16 08:47:51 +00003391 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003392 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003393 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003394
3395 return false;
3396}
3397
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003398/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3399/// TheCall is an ARM/AArch64 special register string literal.
3400bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3401 int ArgNum, unsigned ExpectedFieldNum,
3402 bool AllowName) {
3403 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3404 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3405 BuiltinID == ARM::BI__builtin_arm_rsr ||
3406 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3407 BuiltinID == ARM::BI__builtin_arm_wsr ||
3408 BuiltinID == ARM::BI__builtin_arm_wsrp;
3409 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3410 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3411 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3412 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3413 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3414 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3415 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3416
3417 // We can't check the value of a dependent argument.
3418 Expr *Arg = TheCall->getArg(ArgNum);
3419 if (Arg->isTypeDependent() || Arg->isValueDependent())
3420 return false;
3421
3422 // Check if the argument is a string literal.
3423 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3424 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3425 << Arg->getSourceRange();
3426
3427 // Check the type of special register given.
3428 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3429 SmallVector<StringRef, 6> Fields;
3430 Reg.split(Fields, ":");
3431
3432 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3433 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3434 << Arg->getSourceRange();
3435
3436 // If the string is the name of a register then we cannot check that it is
3437 // valid here but if the string is of one the forms described in ACLE then we
3438 // can check that the supplied fields are integers and within the valid
3439 // ranges.
3440 if (Fields.size() > 1) {
3441 bool FiveFields = Fields.size() == 5;
3442
3443 bool ValidString = true;
3444 if (IsARMBuiltin) {
3445 ValidString &= Fields[0].startswith_lower("cp") ||
3446 Fields[0].startswith_lower("p");
3447 if (ValidString)
3448 Fields[0] =
3449 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3450
3451 ValidString &= Fields[2].startswith_lower("c");
3452 if (ValidString)
3453 Fields[2] = Fields[2].drop_front(1);
3454
3455 if (FiveFields) {
3456 ValidString &= Fields[3].startswith_lower("c");
3457 if (ValidString)
3458 Fields[3] = Fields[3].drop_front(1);
3459 }
3460 }
3461
3462 SmallVector<int, 5> Ranges;
3463 if (FiveFields)
3464 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3465 else
3466 Ranges.append({15, 7, 15});
3467
3468 for (unsigned i=0; i<Fields.size(); ++i) {
3469 int IntField;
3470 ValidString &= !Fields[i].getAsInteger(10, IntField);
3471 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3472 }
3473
3474 if (!ValidString)
3475 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3476 << Arg->getSourceRange();
3477
3478 } else if (IsAArch64Builtin && Fields.size() == 1) {
3479 // If the register name is one of those that appear in the condition below
3480 // and the special register builtin being used is one of the write builtins,
3481 // then we require that the argument provided for writing to the register
3482 // is an integer constant expression. This is because it will be lowered to
3483 // an MSR (immediate) instruction, so we need to know the immediate at
3484 // compile time.
3485 if (TheCall->getNumArgs() != 2)
3486 return false;
3487
3488 std::string RegLower = Reg.lower();
3489 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3490 RegLower != "pan" && RegLower != "uao")
3491 return false;
3492
3493 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3494 }
3495
3496 return false;
3497}
3498
Eli Friedmanc97d0142009-05-03 06:04:26 +00003499/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003500/// This checks that the target supports __builtin_longjmp and
3501/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003502bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003503 if (!Context.getTargetInfo().hasSjLjLowering())
3504 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3505 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3506
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003507 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003508 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003509
Eric Christopher8d0c6212010-04-17 02:26:23 +00003510 // TODO: This is less than ideal. Overload this to take a value.
3511 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3512 return true;
3513
3514 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003515 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3516 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3517
3518 return false;
3519}
3520
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003521/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3522/// This checks that the target supports __builtin_setjmp.
3523bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3524 if (!Context.getTargetInfo().hasSjLjLowering())
3525 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3526 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3527 return false;
3528}
3529
Richard Smithd7293d72013-08-05 18:49:43 +00003530namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003531class UncoveredArgHandler {
3532 enum { Unknown = -1, AllCovered = -2 };
3533 signed FirstUncoveredArg;
3534 SmallVector<const Expr *, 4> DiagnosticExprs;
3535
3536public:
3537 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3538
3539 bool hasUncoveredArg() const {
3540 return (FirstUncoveredArg >= 0);
3541 }
3542
3543 unsigned getUncoveredArg() const {
3544 assert(hasUncoveredArg() && "no uncovered argument");
3545 return FirstUncoveredArg;
3546 }
3547
3548 void setAllCovered() {
3549 // A string has been found with all arguments covered, so clear out
3550 // the diagnostics.
3551 DiagnosticExprs.clear();
3552 FirstUncoveredArg = AllCovered;
3553 }
3554
3555 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3556 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3557
3558 // Don't update if a previous string covers all arguments.
3559 if (FirstUncoveredArg == AllCovered)
3560 return;
3561
3562 // UncoveredArgHandler tracks the highest uncovered argument index
3563 // and with it all the strings that match this index.
3564 if (NewFirstUncoveredArg == FirstUncoveredArg)
3565 DiagnosticExprs.push_back(StrExpr);
3566 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3567 DiagnosticExprs.clear();
3568 DiagnosticExprs.push_back(StrExpr);
3569 FirstUncoveredArg = NewFirstUncoveredArg;
3570 }
3571 }
3572
3573 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3574};
3575
Richard Smithd7293d72013-08-05 18:49:43 +00003576enum StringLiteralCheckType {
3577 SLCT_NotALiteral,
3578 SLCT_UncheckedLiteral,
3579 SLCT_CheckedLiteral
3580};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003581} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003582
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003583static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3584 const Expr *OrigFormatExpr,
3585 ArrayRef<const Expr *> Args,
3586 bool HasVAListArg, unsigned format_idx,
3587 unsigned firstDataArg,
3588 Sema::FormatStringType Type,
3589 bool inFunctionCall,
3590 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003591 llvm::SmallBitVector &CheckedVarArgs,
3592 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003593
Richard Smith55ce3522012-06-25 20:30:08 +00003594// Determine if an expression is a string literal or constant string.
3595// If this function returns false on the arguments to a function expecting a
3596// format string, we will usually need to emit a warning.
3597// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003598static StringLiteralCheckType
3599checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3600 bool HasVAListArg, unsigned format_idx,
3601 unsigned firstDataArg, Sema::FormatStringType Type,
3602 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003603 llvm::SmallBitVector &CheckedVarArgs,
3604 UncoveredArgHandler &UncoveredArg) {
Ted Kremenek808829352010-09-09 03:51:39 +00003605 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003606 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003607 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003608
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003609 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003610
Richard Smithd7293d72013-08-05 18:49:43 +00003611 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003612 // Technically -Wformat-nonliteral does not warn about this case.
3613 // The behavior of printf and friends in this case is implementation
3614 // dependent. Ideally if the format string cannot be null then
3615 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003616 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003617
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003618 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003619 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003620 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003621 // The expression is a literal if both sub-expressions were, and it was
3622 // completely checked only if both sub-expressions were checked.
3623 const AbstractConditionalOperator *C =
3624 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003625
3626 // Determine whether it is necessary to check both sub-expressions, for
3627 // example, because the condition expression is a constant that can be
3628 // evaluated at compile time.
3629 bool CheckLeft = true, CheckRight = true;
3630
3631 bool Cond;
3632 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3633 if (Cond)
3634 CheckRight = false;
3635 else
3636 CheckLeft = false;
3637 }
3638
3639 StringLiteralCheckType Left;
3640 if (!CheckLeft)
3641 Left = SLCT_UncheckedLiteral;
3642 else {
3643 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3644 HasVAListArg, format_idx, firstDataArg,
3645 Type, CallType, InFunctionCall,
3646 CheckedVarArgs, UncoveredArg);
3647 if (Left == SLCT_NotALiteral || !CheckRight)
3648 return Left;
3649 }
3650
Richard Smith55ce3522012-06-25 20:30:08 +00003651 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003652 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003653 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003654 Type, CallType, InFunctionCall, CheckedVarArgs,
3655 UncoveredArg);
3656
3657 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003658 }
3659
3660 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003661 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3662 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003663 }
3664
John McCallc07a0c72011-02-17 10:25:35 +00003665 case Stmt::OpaqueValueExprClass:
3666 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3667 E = src;
3668 goto tryAgain;
3669 }
Richard Smith55ce3522012-06-25 20:30:08 +00003670 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003671
Ted Kremeneka8890832011-02-24 23:03:04 +00003672 case Stmt::PredefinedExprClass:
3673 // While __func__, etc., are technically not string literals, they
3674 // cannot contain format specifiers and thus are not a security
3675 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003676 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003677
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003678 case Stmt::DeclRefExprClass: {
3679 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003680
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003681 // As an exception, do not flag errors for variables binding to
3682 // const string literals.
3683 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3684 bool isConstant = false;
3685 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003686
Richard Smithd7293d72013-08-05 18:49:43 +00003687 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3688 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003689 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003690 isConstant = T.isConstant(S.Context) &&
3691 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003692 } else if (T->isObjCObjectPointerType()) {
3693 // In ObjC, there is usually no "const ObjectPointer" type,
3694 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003695 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003696 }
Mike Stump11289f42009-09-09 15:08:12 +00003697
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003698 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003699 if (const Expr *Init = VD->getAnyInitializer()) {
3700 // Look through initializers like const char c[] = { "foo" }
3701 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3702 if (InitList->isStringLiteralInit())
3703 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3704 }
Richard Smithd7293d72013-08-05 18:49:43 +00003705 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003706 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003707 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003708 /*InFunctionCall*/false, CheckedVarArgs,
3709 UncoveredArg);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003710 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003711 }
Mike Stump11289f42009-09-09 15:08:12 +00003712
Anders Carlssonb012ca92009-06-28 19:55:58 +00003713 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3714 // special check to see if the format string is a function parameter
3715 // of the function calling the printf function. If the function
3716 // has an attribute indicating it is a printf-like function, then we
3717 // should suppress warnings concerning non-literals being used in a call
3718 // to a vprintf function. For example:
3719 //
3720 // void
3721 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3722 // va_list ap;
3723 // va_start(ap, fmt);
3724 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3725 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003726 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003727 if (HasVAListArg) {
3728 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3729 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3730 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003731 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003732 // adjust for implicit parameter
3733 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3734 if (MD->isInstance())
3735 ++PVIndex;
3736 // We also check if the formats are compatible.
3737 // We can't pass a 'scanf' string to a 'printf' function.
3738 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003739 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003740 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003741 }
3742 }
3743 }
3744 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003745 }
Mike Stump11289f42009-09-09 15:08:12 +00003746
Richard Smith55ce3522012-06-25 20:30:08 +00003747 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003748 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003749
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003750 case Stmt::CallExprClass:
3751 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003752 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003753 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3754 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3755 unsigned ArgIndex = FA->getFormatIdx();
3756 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3757 if (MD->isInstance())
3758 --ArgIndex;
3759 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003760
Richard Smithd7293d72013-08-05 18:49:43 +00003761 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003762 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003763 Type, CallType, InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003764 CheckedVarArgs, UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003765 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3766 unsigned BuiltinID = FD->getBuiltinID();
3767 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3768 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3769 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003770 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003771 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003772 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003773 InFunctionCall, CheckedVarArgs,
3774 UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003775 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003776 }
3777 }
Mike Stump11289f42009-09-09 15:08:12 +00003778
Richard Smith55ce3522012-06-25 20:30:08 +00003779 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003780 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003781 case Stmt::ObjCStringLiteralClass:
3782 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003783 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003784
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003785 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003786 StrE = ObjCFExpr->getString();
3787 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003788 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003789
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003790 if (StrE) {
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003791 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
3792 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003793 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00003794 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003795 }
Mike Stump11289f42009-09-09 15:08:12 +00003796
Richard Smith55ce3522012-06-25 20:30:08 +00003797 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003798 }
Mike Stump11289f42009-09-09 15:08:12 +00003799
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003800 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003801 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003802 }
3803}
3804
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003805Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003806 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003807 .Case("scanf", FST_Scanf)
3808 .Cases("printf", "printf0", FST_Printf)
3809 .Cases("NSString", "CFString", FST_NSString)
3810 .Case("strftime", FST_Strftime)
3811 .Case("strfmon", FST_Strfmon)
3812 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003813 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003814 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003815 .Default(FST_Unknown);
3816}
3817
Jordan Rose3e0ec582012-07-19 18:10:23 +00003818/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003819/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003820/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003821bool Sema::CheckFormatArguments(const FormatAttr *Format,
3822 ArrayRef<const Expr *> Args,
3823 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003824 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003825 SourceLocation Loc, SourceRange Range,
3826 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003827 FormatStringInfo FSI;
3828 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003829 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003830 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003831 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003832 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003833}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003834
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003835bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003836 bool HasVAListArg, unsigned format_idx,
3837 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003838 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003839 SourceLocation Loc, SourceRange Range,
3840 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003841 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003842 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003843 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003844 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003845 }
Mike Stump11289f42009-09-09 15:08:12 +00003846
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003847 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003848
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003849 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003850 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003851 // Dynamically generated format strings are difficult to
3852 // automatically vet at compile time. Requiring that format strings
3853 // are string literals: (1) permits the checking of format strings by
3854 // the compiler and thereby (2) can practically remove the source of
3855 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003856
Mike Stump11289f42009-09-09 15:08:12 +00003857 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003858 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003859 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003860 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003861 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00003862 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003863 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3864 format_idx, firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003865 /*IsFunctionCall*/true, CheckedVarArgs,
3866 UncoveredArg);
3867
3868 // Generate a diagnostic where an uncovered argument is detected.
3869 if (UncoveredArg.hasUncoveredArg()) {
3870 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
3871 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
3872 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
3873 }
3874
Richard Smith55ce3522012-06-25 20:30:08 +00003875 if (CT != SLCT_NotALiteral)
3876 // Literal format string found, check done!
3877 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003878
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003879 // Strftime is particular as it always uses a single 'time' argument,
3880 // so it is safe to pass a non-literal string.
3881 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003882 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003883
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003884 // Do not emit diag when the string param is a macro expansion and the
3885 // format is either NSString or CFString. This is a hack to prevent
3886 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3887 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003888 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
3889 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00003890 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003891
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003892 // If there are no arguments specified, warn with -Wformat-security, otherwise
3893 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003894 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00003895 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
3896 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003897 switch (Type) {
3898 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003899 break;
3900 case FST_Kprintf:
3901 case FST_FreeBSDKPrintf:
3902 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00003903 Diag(FormatLoc, diag::note_format_security_fixit)
3904 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003905 break;
3906 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00003907 Diag(FormatLoc, diag::note_format_security_fixit)
3908 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003909 break;
3910 }
3911 } else {
3912 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003913 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003914 }
Richard Smith55ce3522012-06-25 20:30:08 +00003915 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003916}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003917
Ted Kremenekab278de2010-01-28 23:39:18 +00003918namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003919class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3920protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003921 Sema &S;
3922 const StringLiteral *FExpr;
3923 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003924 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003925 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003926 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003927 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003928 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003929 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003930 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003931 bool usesPositionalArgs;
3932 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003933 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003934 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003935 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003936 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003937
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003938public:
Ted Kremenek02087932010-07-16 02:11:22 +00003939 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003940 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003941 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003942 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003943 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003944 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003945 llvm::SmallBitVector &CheckedVarArgs,
3946 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00003947 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003948 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3949 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003950 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003951 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003952 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003953 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00003954 CoveredArgs.resize(numDataArgs);
3955 CoveredArgs.reset();
3956 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003957
Ted Kremenek019d2242010-01-29 01:50:07 +00003958 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003959
Ted Kremenek02087932010-07-16 02:11:22 +00003960 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003961 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003962
Jordan Rose92303592012-09-08 04:00:03 +00003963 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003964 const analyze_format_string::FormatSpecifier &FS,
3965 const analyze_format_string::ConversionSpecifier &CS,
3966 const char *startSpecifier, unsigned specifierLen,
3967 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003968
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003969 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003970 const analyze_format_string::FormatSpecifier &FS,
3971 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003972
3973 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003974 const analyze_format_string::ConversionSpecifier &CS,
3975 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003976
Craig Toppere14c0f82014-03-12 04:55:44 +00003977 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003978
Craig Toppere14c0f82014-03-12 04:55:44 +00003979 void HandleInvalidPosition(const char *startSpecifier,
3980 unsigned specifierLen,
3981 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003982
Craig Toppere14c0f82014-03-12 04:55:44 +00003983 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003984
Craig Toppere14c0f82014-03-12 04:55:44 +00003985 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003986
Richard Trieu03cf7b72011-10-28 00:41:25 +00003987 template <typename Range>
3988 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3989 const Expr *ArgumentExpr,
3990 PartialDiagnostic PDiag,
3991 SourceLocation StringLoc,
3992 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003993 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003994
Ted Kremenek02087932010-07-16 02:11:22 +00003995protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003996 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3997 const char *startSpec,
3998 unsigned specifierLen,
3999 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004000
4001 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4002 const char *startSpec,
4003 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004004
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004005 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004006 CharSourceRange getSpecifierRange(const char *startSpecifier,
4007 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004008 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004009
Ted Kremenek5739de72010-01-29 01:06:55 +00004010 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004011
4012 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4013 const analyze_format_string::ConversionSpecifier &CS,
4014 const char *startSpecifier, unsigned specifierLen,
4015 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004016
4017 template <typename Range>
4018 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4019 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004020 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004021};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004022} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004023
Ted Kremenek02087932010-07-16 02:11:22 +00004024SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004025 return OrigFormatExpr->getSourceRange();
4026}
4027
Ted Kremenek02087932010-07-16 02:11:22 +00004028CharSourceRange CheckFormatHandler::
4029getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004030 SourceLocation Start = getLocationOfByte(startSpecifier);
4031 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4032
4033 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004034 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004035
4036 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004037}
4038
Ted Kremenek02087932010-07-16 02:11:22 +00004039SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004040 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00004041}
4042
Ted Kremenek02087932010-07-16 02:11:22 +00004043void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4044 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004045 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4046 getLocationOfByte(startSpecifier),
4047 /*IsStringLocation*/true,
4048 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004049}
4050
Jordan Rose92303592012-09-08 04:00:03 +00004051void CheckFormatHandler::HandleInvalidLengthModifier(
4052 const analyze_format_string::FormatSpecifier &FS,
4053 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004054 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004055 using namespace analyze_format_string;
4056
4057 const LengthModifier &LM = FS.getLengthModifier();
4058 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4059
4060 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004061 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004062 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004063 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004064 getLocationOfByte(LM.getStart()),
4065 /*IsStringLocation*/true,
4066 getSpecifierRange(startSpecifier, specifierLen));
4067
4068 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4069 << FixedLM->toString()
4070 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4071
4072 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004073 FixItHint Hint;
4074 if (DiagID == diag::warn_format_nonsensical_length)
4075 Hint = FixItHint::CreateRemoval(LMRange);
4076
4077 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004078 getLocationOfByte(LM.getStart()),
4079 /*IsStringLocation*/true,
4080 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004081 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004082 }
4083}
4084
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004085void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004086 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004087 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004088 using namespace analyze_format_string;
4089
4090 const LengthModifier &LM = FS.getLengthModifier();
4091 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4092
4093 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004094 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004095 if (FixedLM) {
4096 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4097 << LM.toString() << 0,
4098 getLocationOfByte(LM.getStart()),
4099 /*IsStringLocation*/true,
4100 getSpecifierRange(startSpecifier, specifierLen));
4101
4102 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4103 << FixedLM->toString()
4104 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4105
4106 } else {
4107 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4108 << LM.toString() << 0,
4109 getLocationOfByte(LM.getStart()),
4110 /*IsStringLocation*/true,
4111 getSpecifierRange(startSpecifier, specifierLen));
4112 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004113}
4114
4115void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4116 const analyze_format_string::ConversionSpecifier &CS,
4117 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00004118 using namespace analyze_format_string;
4119
4120 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00004121 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00004122 if (FixedCS) {
4123 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4124 << CS.toString() << /*conversion specifier*/1,
4125 getLocationOfByte(CS.getStart()),
4126 /*IsStringLocation*/true,
4127 getSpecifierRange(startSpecifier, specifierLen));
4128
4129 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4130 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4131 << FixedCS->toString()
4132 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4133 } else {
4134 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4135 << CS.toString() << /*conversion specifier*/1,
4136 getLocationOfByte(CS.getStart()),
4137 /*IsStringLocation*/true,
4138 getSpecifierRange(startSpecifier, specifierLen));
4139 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004140}
4141
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004142void CheckFormatHandler::HandlePosition(const char *startPos,
4143 unsigned posLen) {
4144 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4145 getLocationOfByte(startPos),
4146 /*IsStringLocation*/true,
4147 getSpecifierRange(startPos, posLen));
4148}
4149
Ted Kremenekd1668192010-02-27 01:41:03 +00004150void
Ted Kremenek02087932010-07-16 02:11:22 +00004151CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4152 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004153 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4154 << (unsigned) p,
4155 getLocationOfByte(startPos), /*IsStringLocation*/true,
4156 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004157}
4158
Ted Kremenek02087932010-07-16 02:11:22 +00004159void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00004160 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004161 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4162 getLocationOfByte(startPos),
4163 /*IsStringLocation*/true,
4164 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004165}
4166
Ted Kremenek02087932010-07-16 02:11:22 +00004167void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004168 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004169 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004170 EmitFormatDiagnostic(
4171 S.PDiag(diag::warn_printf_format_string_contains_null_char),
4172 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4173 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004174 }
Ted Kremenek02087932010-07-16 02:11:22 +00004175}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004176
Jordan Rose58bbe422012-07-19 18:10:08 +00004177// Note that this may return NULL if there was an error parsing or building
4178// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00004179const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004180 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00004181}
4182
4183void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004184 // Does the number of data arguments exceed the number of
4185 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00004186 if (!HasVAListArg) {
4187 // Find any arguments that weren't covered.
4188 CoveredArgs.flip();
4189 signed notCoveredArg = CoveredArgs.find_first();
4190 if (notCoveredArg >= 0) {
4191 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004192 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4193 } else {
4194 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00004195 }
4196 }
4197}
4198
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004199void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4200 const Expr *ArgExpr) {
4201 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4202 "Invalid state");
4203
4204 if (!ArgExpr)
4205 return;
4206
4207 SourceLocation Loc = ArgExpr->getLocStart();
4208
4209 if (S.getSourceManager().isInSystemMacro(Loc))
4210 return;
4211
4212 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4213 for (auto E : DiagnosticExprs)
4214 PDiag << E->getSourceRange();
4215
4216 CheckFormatHandler::EmitFormatDiagnostic(
4217 S, IsFunctionCall, DiagnosticExprs[0],
4218 PDiag, Loc, /*IsStringLocation*/false,
4219 DiagnosticExprs[0]->getSourceRange());
4220}
4221
Ted Kremenekce815422010-07-19 21:25:57 +00004222bool
4223CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4224 SourceLocation Loc,
4225 const char *startSpec,
4226 unsigned specifierLen,
4227 const char *csStart,
4228 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00004229 bool keepGoing = true;
4230 if (argIndex < NumDataArgs) {
4231 // Consider the argument coverered, even though the specifier doesn't
4232 // make sense.
4233 CoveredArgs.set(argIndex);
4234 }
4235 else {
4236 // If argIndex exceeds the number of data arguments we
4237 // don't issue a warning because that is just a cascade of warnings (and
4238 // they may have intended '%%' anyway). We don't want to continue processing
4239 // the format string after this point, however, as we will like just get
4240 // gibberish when trying to match arguments.
4241 keepGoing = false;
4242 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004243
4244 StringRef Specifier(csStart, csLen);
4245
4246 // If the specifier in non-printable, it could be the first byte of a UTF-8
4247 // sequence. In that case, print the UTF-8 code point. If not, print the byte
4248 // hex value.
4249 std::string CodePointStr;
4250 if (!llvm::sys::locale::isPrint(*csStart)) {
4251 UTF32 CodePoint;
4252 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4253 const UTF8 *E =
4254 reinterpret_cast<const UTF8 *>(csStart + csLen);
4255 ConversionResult Result =
4256 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4257
4258 if (Result != conversionOK) {
4259 unsigned char FirstChar = *csStart;
4260 CodePoint = (UTF32)FirstChar;
4261 }
4262
4263 llvm::raw_string_ostream OS(CodePointStr);
4264 if (CodePoint < 256)
4265 OS << "\\x" << llvm::format("%02x", CodePoint);
4266 else if (CodePoint <= 0xFFFF)
4267 OS << "\\u" << llvm::format("%04x", CodePoint);
4268 else
4269 OS << "\\U" << llvm::format("%08x", CodePoint);
4270 OS.flush();
4271 Specifier = CodePointStr;
4272 }
4273
4274 EmitFormatDiagnostic(
4275 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4276 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4277
Ted Kremenekce815422010-07-19 21:25:57 +00004278 return keepGoing;
4279}
4280
Richard Trieu03cf7b72011-10-28 00:41:25 +00004281void
4282CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4283 const char *startSpec,
4284 unsigned specifierLen) {
4285 EmitFormatDiagnostic(
4286 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4287 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4288}
4289
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004290bool
4291CheckFormatHandler::CheckNumArgs(
4292 const analyze_format_string::FormatSpecifier &FS,
4293 const analyze_format_string::ConversionSpecifier &CS,
4294 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4295
4296 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004297 PartialDiagnostic PDiag = FS.usesPositionalArg()
4298 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4299 << (argIndex+1) << NumDataArgs)
4300 : S.PDiag(diag::warn_printf_insufficient_data_args);
4301 EmitFormatDiagnostic(
4302 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4303 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004304
4305 // Since more arguments than conversion tokens are given, by extension
4306 // all arguments are covered, so mark this as so.
4307 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004308 return false;
4309 }
4310 return true;
4311}
4312
Richard Trieu03cf7b72011-10-28 00:41:25 +00004313template<typename Range>
4314void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4315 SourceLocation Loc,
4316 bool IsStringLocation,
4317 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004318 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004319 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004320 Loc, IsStringLocation, StringRange, FixIt);
4321}
4322
4323/// \brief If the format string is not within the funcion call, emit a note
4324/// so that the function call and string are in diagnostic messages.
4325///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004326/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004327/// call and only one diagnostic message will be produced. Otherwise, an
4328/// extra note will be emitted pointing to location of the format string.
4329///
4330/// \param ArgumentExpr the expression that is passed as the format string
4331/// argument in the function call. Used for getting locations when two
4332/// diagnostics are emitted.
4333///
4334/// \param PDiag the callee should already have provided any strings for the
4335/// diagnostic message. This function only adds locations and fixits
4336/// to diagnostics.
4337///
4338/// \param Loc primary location for diagnostic. If two diagnostics are
4339/// required, one will be at Loc and a new SourceLocation will be created for
4340/// the other one.
4341///
4342/// \param IsStringLocation if true, Loc points to the format string should be
4343/// used for the note. Otherwise, Loc points to the argument list and will
4344/// be used with PDiag.
4345///
4346/// \param StringRange some or all of the string to highlight. This is
4347/// templated so it can accept either a CharSourceRange or a SourceRange.
4348///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004349/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004350template<typename Range>
4351void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
4352 const Expr *ArgumentExpr,
4353 PartialDiagnostic PDiag,
4354 SourceLocation Loc,
4355 bool IsStringLocation,
4356 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004357 ArrayRef<FixItHint> FixIt) {
4358 if (InFunctionCall) {
4359 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4360 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004361 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004362 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004363 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4364 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004365
4366 const Sema::SemaDiagnosticBuilder &Note =
4367 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4368 diag::note_format_string_defined);
4369
4370 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004371 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004372 }
4373}
4374
Ted Kremenek02087932010-07-16 02:11:22 +00004375//===--- CHECK: Printf format string checking ------------------------------===//
4376
4377namespace {
4378class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004379 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004380
Ted Kremenek02087932010-07-16 02:11:22 +00004381public:
4382 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4383 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004384 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004385 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004386 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004387 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004388 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004389 llvm::SmallBitVector &CheckedVarArgs,
4390 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004391 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4392 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004393 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4394 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004395 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004396 {}
4397
Ted Kremenek02087932010-07-16 02:11:22 +00004398 bool HandleInvalidPrintfConversionSpecifier(
4399 const analyze_printf::PrintfSpecifier &FS,
4400 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004401 unsigned specifierLen) override;
4402
Ted Kremenek02087932010-07-16 02:11:22 +00004403 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4404 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004405 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004406 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4407 const char *StartSpecifier,
4408 unsigned SpecifierLen,
4409 const Expr *E);
4410
Ted Kremenek02087932010-07-16 02:11:22 +00004411 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4412 const char *startSpecifier, unsigned specifierLen);
4413 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4414 const analyze_printf::OptionalAmount &Amt,
4415 unsigned type,
4416 const char *startSpecifier, unsigned specifierLen);
4417 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4418 const analyze_printf::OptionalFlag &flag,
4419 const char *startSpecifier, unsigned specifierLen);
4420 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4421 const analyze_printf::OptionalFlag &ignoredFlag,
4422 const analyze_printf::OptionalFlag &flag,
4423 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004424 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004425 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004426
4427 void HandleEmptyObjCModifierFlag(const char *startFlag,
4428 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004429
Ted Kremenek2b417712015-07-02 05:39:16 +00004430 void HandleInvalidObjCModifierFlag(const char *startFlag,
4431 unsigned flagLen) override;
4432
4433 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4434 const char *flagsEnd,
4435 const char *conversionPosition)
4436 override;
4437};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004438} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004439
4440bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4441 const analyze_printf::PrintfSpecifier &FS,
4442 const char *startSpecifier,
4443 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004444 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004445 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004446
Ted Kremenekce815422010-07-19 21:25:57 +00004447 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4448 getLocationOfByte(CS.getStart()),
4449 startSpecifier, specifierLen,
4450 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004451}
4452
Ted Kremenek02087932010-07-16 02:11:22 +00004453bool CheckPrintfHandler::HandleAmount(
4454 const analyze_format_string::OptionalAmount &Amt,
4455 unsigned k, const char *startSpecifier,
4456 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004457 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004458 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004459 unsigned argIndex = Amt.getArgIndex();
4460 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004461 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4462 << k,
4463 getLocationOfByte(Amt.getStart()),
4464 /*IsStringLocation*/true,
4465 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004466 // Don't do any more checking. We will just emit
4467 // spurious errors.
4468 return false;
4469 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004470
Ted Kremenek5739de72010-01-29 01:06:55 +00004471 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004472 // Although not in conformance with C99, we also allow the argument to be
4473 // an 'unsigned int' as that is a reasonably safe case. GCC also
4474 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004475 CoveredArgs.set(argIndex);
4476 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004477 if (!Arg)
4478 return false;
4479
Ted Kremenek5739de72010-01-29 01:06:55 +00004480 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004481
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004482 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4483 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004484
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004485 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004486 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004487 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004488 << T << Arg->getSourceRange(),
4489 getLocationOfByte(Amt.getStart()),
4490 /*IsStringLocation*/true,
4491 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004492 // Don't do any more checking. We will just emit
4493 // spurious errors.
4494 return false;
4495 }
4496 }
4497 }
4498 return true;
4499}
Ted Kremenek5739de72010-01-29 01:06:55 +00004500
Tom Careb49ec692010-06-17 19:00:27 +00004501void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004502 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004503 const analyze_printf::OptionalAmount &Amt,
4504 unsigned type,
4505 const char *startSpecifier,
4506 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004507 const analyze_printf::PrintfConversionSpecifier &CS =
4508 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004509
Richard Trieu03cf7b72011-10-28 00:41:25 +00004510 FixItHint fixit =
4511 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4512 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4513 Amt.getConstantLength()))
4514 : FixItHint();
4515
4516 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4517 << type << CS.toString(),
4518 getLocationOfByte(Amt.getStart()),
4519 /*IsStringLocation*/true,
4520 getSpecifierRange(startSpecifier, specifierLen),
4521 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004522}
4523
Ted Kremenek02087932010-07-16 02:11:22 +00004524void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004525 const analyze_printf::OptionalFlag &flag,
4526 const char *startSpecifier,
4527 unsigned specifierLen) {
4528 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004529 const analyze_printf::PrintfConversionSpecifier &CS =
4530 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004531 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4532 << flag.toString() << CS.toString(),
4533 getLocationOfByte(flag.getPosition()),
4534 /*IsStringLocation*/true,
4535 getSpecifierRange(startSpecifier, specifierLen),
4536 FixItHint::CreateRemoval(
4537 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004538}
4539
4540void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004541 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004542 const analyze_printf::OptionalFlag &ignoredFlag,
4543 const analyze_printf::OptionalFlag &flag,
4544 const char *startSpecifier,
4545 unsigned specifierLen) {
4546 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004547 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4548 << ignoredFlag.toString() << flag.toString(),
4549 getLocationOfByte(ignoredFlag.getPosition()),
4550 /*IsStringLocation*/true,
4551 getSpecifierRange(startSpecifier, specifierLen),
4552 FixItHint::CreateRemoval(
4553 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004554}
4555
Ted Kremenek2b417712015-07-02 05:39:16 +00004556// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4557// bool IsStringLocation, Range StringRange,
4558// ArrayRef<FixItHint> Fixit = None);
4559
4560void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4561 unsigned flagLen) {
4562 // Warn about an empty flag.
4563 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4564 getLocationOfByte(startFlag),
4565 /*IsStringLocation*/true,
4566 getSpecifierRange(startFlag, flagLen));
4567}
4568
4569void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4570 unsigned flagLen) {
4571 // Warn about an invalid flag.
4572 auto Range = getSpecifierRange(startFlag, flagLen);
4573 StringRef flag(startFlag, flagLen);
4574 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4575 getLocationOfByte(startFlag),
4576 /*IsStringLocation*/true,
4577 Range, FixItHint::CreateRemoval(Range));
4578}
4579
4580void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4581 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4582 // Warn about using '[...]' without a '@' conversion.
4583 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4584 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4585 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4586 getLocationOfByte(conversionPosition),
4587 /*IsStringLocation*/true,
4588 Range, FixItHint::CreateRemoval(Range));
4589}
4590
Richard Smith55ce3522012-06-25 20:30:08 +00004591// Determines if the specified is a C++ class or struct containing
4592// a member with the specified name and kind (e.g. a CXXMethodDecl named
4593// "c_str()").
4594template<typename MemberKind>
4595static llvm::SmallPtrSet<MemberKind*, 1>
4596CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4597 const RecordType *RT = Ty->getAs<RecordType>();
4598 llvm::SmallPtrSet<MemberKind*, 1> Results;
4599
4600 if (!RT)
4601 return Results;
4602 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004603 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004604 return Results;
4605
Alp Tokerb6cc5922014-05-03 03:45:55 +00004606 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004607 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004608 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004609
4610 // We just need to include all members of the right kind turned up by the
4611 // filter, at this point.
4612 if (S.LookupQualifiedName(R, RT->getDecl()))
4613 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4614 NamedDecl *decl = (*I)->getUnderlyingDecl();
4615 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4616 Results.insert(FK);
4617 }
4618 return Results;
4619}
4620
Richard Smith2868a732014-02-28 01:36:39 +00004621/// Check if we could call '.c_str()' on an object.
4622///
4623/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4624/// allow the call, or if it would be ambiguous).
4625bool Sema::hasCStrMethod(const Expr *E) {
4626 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4627 MethodSet Results =
4628 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4629 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4630 MI != ME; ++MI)
4631 if ((*MI)->getMinRequiredArguments() == 0)
4632 return true;
4633 return false;
4634}
4635
Richard Smith55ce3522012-06-25 20:30:08 +00004636// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004637// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004638// Returns true when a c_str() conversion method is found.
4639bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004640 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004641 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4642
4643 MethodSet Results =
4644 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4645
4646 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4647 MI != ME; ++MI) {
4648 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004649 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004650 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004651 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004652 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004653 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4654 << "c_str()"
4655 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4656 return true;
4657 }
4658 }
4659
4660 return false;
4661}
4662
Ted Kremenekab278de2010-01-28 23:39:18 +00004663bool
Ted Kremenek02087932010-07-16 02:11:22 +00004664CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004665 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004666 const char *startSpecifier,
4667 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004668 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004669 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004670 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004671
Ted Kremenek6cd69422010-07-19 22:01:06 +00004672 if (FS.consumesDataArgument()) {
4673 if (atFirstArg) {
4674 atFirstArg = false;
4675 usesPositionalArgs = FS.usesPositionalArg();
4676 }
4677 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004678 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4679 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004680 return false;
4681 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004682 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004683
Ted Kremenekd1668192010-02-27 01:41:03 +00004684 // First check if the field width, precision, and conversion specifier
4685 // have matching data arguments.
4686 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4687 startSpecifier, specifierLen)) {
4688 return false;
4689 }
4690
4691 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4692 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004693 return false;
4694 }
4695
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004696 if (!CS.consumesDataArgument()) {
4697 // FIXME: Technically specifying a precision or field width here
4698 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004699 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004700 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004701
Ted Kremenek4a49d982010-02-26 19:18:41 +00004702 // Consume the argument.
4703 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004704 if (argIndex < NumDataArgs) {
4705 // The check to see if the argIndex is valid will come later.
4706 // We set the bit here because we may exit early from this
4707 // function if we encounter some other error.
4708 CoveredArgs.set(argIndex);
4709 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004710
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004711 // FreeBSD kernel extensions.
4712 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4713 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4714 // We need at least two arguments.
4715 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4716 return false;
4717
4718 // Claim the second argument.
4719 CoveredArgs.set(argIndex + 1);
4720
4721 // Type check the first argument (int for %b, pointer for %D)
4722 const Expr *Ex = getDataArg(argIndex);
4723 const analyze_printf::ArgType &AT =
4724 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4725 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4726 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4727 EmitFormatDiagnostic(
4728 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4729 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4730 << false << Ex->getSourceRange(),
4731 Ex->getLocStart(), /*IsStringLocation*/false,
4732 getSpecifierRange(startSpecifier, specifierLen));
4733
4734 // Type check the second argument (char * for both %b and %D)
4735 Ex = getDataArg(argIndex + 1);
4736 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4737 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4738 EmitFormatDiagnostic(
4739 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4740 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4741 << false << Ex->getSourceRange(),
4742 Ex->getLocStart(), /*IsStringLocation*/false,
4743 getSpecifierRange(startSpecifier, specifierLen));
4744
4745 return true;
4746 }
4747
Ted Kremenek4a49d982010-02-26 19:18:41 +00004748 // Check for using an Objective-C specific conversion specifier
4749 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004750 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004751 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4752 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004753 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004754
Tom Careb49ec692010-06-17 19:00:27 +00004755 // Check for invalid use of field width
4756 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004757 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004758 startSpecifier, specifierLen);
4759 }
4760
4761 // Check for invalid use of precision
4762 if (!FS.hasValidPrecision()) {
4763 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4764 startSpecifier, specifierLen);
4765 }
4766
4767 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004768 if (!FS.hasValidThousandsGroupingPrefix())
4769 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004770 if (!FS.hasValidLeadingZeros())
4771 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4772 if (!FS.hasValidPlusPrefix())
4773 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004774 if (!FS.hasValidSpacePrefix())
4775 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004776 if (!FS.hasValidAlternativeForm())
4777 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4778 if (!FS.hasValidLeftJustified())
4779 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4780
4781 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004782 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4783 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4784 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004785 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4786 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4787 startSpecifier, specifierLen);
4788
4789 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004790 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004791 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4792 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004793 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004794 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004795 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004796 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4797 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004798
Jordan Rose92303592012-09-08 04:00:03 +00004799 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4800 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4801
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004802 // The remaining checks depend on the data arguments.
4803 if (HasVAListArg)
4804 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004805
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004806 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004807 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004808
Jordan Rose58bbe422012-07-19 18:10:08 +00004809 const Expr *Arg = getDataArg(argIndex);
4810 if (!Arg)
4811 return true;
4812
4813 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004814}
4815
Jordan Roseaee34382012-09-05 22:56:26 +00004816static bool requiresParensToAddCast(const Expr *E) {
4817 // FIXME: We should have a general way to reason about operator
4818 // precedence and whether parens are actually needed here.
4819 // Take care of a few common cases where they aren't.
4820 const Expr *Inside = E->IgnoreImpCasts();
4821 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4822 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4823
4824 switch (Inside->getStmtClass()) {
4825 case Stmt::ArraySubscriptExprClass:
4826 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004827 case Stmt::CharacterLiteralClass:
4828 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004829 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004830 case Stmt::FloatingLiteralClass:
4831 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004832 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004833 case Stmt::ObjCArrayLiteralClass:
4834 case Stmt::ObjCBoolLiteralExprClass:
4835 case Stmt::ObjCBoxedExprClass:
4836 case Stmt::ObjCDictionaryLiteralClass:
4837 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004838 case Stmt::ObjCIvarRefExprClass:
4839 case Stmt::ObjCMessageExprClass:
4840 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004841 case Stmt::ObjCStringLiteralClass:
4842 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004843 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004844 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004845 case Stmt::UnaryOperatorClass:
4846 return false;
4847 default:
4848 return true;
4849 }
4850}
4851
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004852static std::pair<QualType, StringRef>
4853shouldNotPrintDirectly(const ASTContext &Context,
4854 QualType IntendedTy,
4855 const Expr *E) {
4856 // Use a 'while' to peel off layers of typedefs.
4857 QualType TyTy = IntendedTy;
4858 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4859 StringRef Name = UserTy->getDecl()->getName();
4860 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4861 .Case("NSInteger", Context.LongTy)
4862 .Case("NSUInteger", Context.UnsignedLongTy)
4863 .Case("SInt32", Context.IntTy)
4864 .Case("UInt32", Context.UnsignedIntTy)
4865 .Default(QualType());
4866
4867 if (!CastTy.isNull())
4868 return std::make_pair(CastTy, Name);
4869
4870 TyTy = UserTy->desugar();
4871 }
4872
4873 // Strip parens if necessary.
4874 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4875 return shouldNotPrintDirectly(Context,
4876 PE->getSubExpr()->getType(),
4877 PE->getSubExpr());
4878
4879 // If this is a conditional expression, then its result type is constructed
4880 // via usual arithmetic conversions and thus there might be no necessary
4881 // typedef sugar there. Recurse to operands to check for NSInteger &
4882 // Co. usage condition.
4883 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4884 QualType TrueTy, FalseTy;
4885 StringRef TrueName, FalseName;
4886
4887 std::tie(TrueTy, TrueName) =
4888 shouldNotPrintDirectly(Context,
4889 CO->getTrueExpr()->getType(),
4890 CO->getTrueExpr());
4891 std::tie(FalseTy, FalseName) =
4892 shouldNotPrintDirectly(Context,
4893 CO->getFalseExpr()->getType(),
4894 CO->getFalseExpr());
4895
4896 if (TrueTy == FalseTy)
4897 return std::make_pair(TrueTy, TrueName);
4898 else if (TrueTy.isNull())
4899 return std::make_pair(FalseTy, FalseName);
4900 else if (FalseTy.isNull())
4901 return std::make_pair(TrueTy, TrueName);
4902 }
4903
4904 return std::make_pair(QualType(), StringRef());
4905}
4906
Richard Smith55ce3522012-06-25 20:30:08 +00004907bool
4908CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4909 const char *StartSpecifier,
4910 unsigned SpecifierLen,
4911 const Expr *E) {
4912 using namespace analyze_format_string;
4913 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004914 // Now type check the data expression that matches the
4915 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004916 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4917 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004918 if (!AT.isValid())
4919 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004920
Jordan Rose598ec092012-12-05 18:44:40 +00004921 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004922 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4923 ExprTy = TET->getUnderlyingExpr()->getType();
4924 }
4925
Seth Cantrellb4802962015-03-04 03:12:10 +00004926 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4927
4928 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004929 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004930 }
Jordan Rose98709982012-06-04 22:48:57 +00004931
Jordan Rose22b74712012-09-05 22:56:19 +00004932 // Look through argument promotions for our error message's reported type.
4933 // This includes the integral and floating promotions, but excludes array
4934 // and function pointer decay; seeing that an argument intended to be a
4935 // string has type 'char [6]' is probably more confusing than 'char *'.
4936 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4937 if (ICE->getCastKind() == CK_IntegralCast ||
4938 ICE->getCastKind() == CK_FloatingCast) {
4939 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004940 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004941
4942 // Check if we didn't match because of an implicit cast from a 'char'
4943 // or 'short' to an 'int'. This is done because printf is a varargs
4944 // function.
4945 if (ICE->getType() == S.Context.IntTy ||
4946 ICE->getType() == S.Context.UnsignedIntTy) {
4947 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004948 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004949 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004950 }
Jordan Rose98709982012-06-04 22:48:57 +00004951 }
Jordan Rose598ec092012-12-05 18:44:40 +00004952 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4953 // Special case for 'a', which has type 'int' in C.
4954 // Note, however, that we do /not/ want to treat multibyte constants like
4955 // 'MooV' as characters! This form is deprecated but still exists.
4956 if (ExprTy == S.Context.IntTy)
4957 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4958 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004959 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004960
Jordan Rosebc53ed12014-05-31 04:12:14 +00004961 // Look through enums to their underlying type.
4962 bool IsEnum = false;
4963 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4964 ExprTy = EnumTy->getDecl()->getIntegerType();
4965 IsEnum = true;
4966 }
4967
Jordan Rose0e5badd2012-12-05 18:44:49 +00004968 // %C in an Objective-C context prints a unichar, not a wchar_t.
4969 // If the argument is an integer of some kind, believe the %C and suggest
4970 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004971 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004972 if (ObjCContext &&
4973 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4974 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4975 !ExprTy->isCharType()) {
4976 // 'unichar' is defined as a typedef of unsigned short, but we should
4977 // prefer using the typedef if it is visible.
4978 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004979
4980 // While we are here, check if the value is an IntegerLiteral that happens
4981 // to be within the valid range.
4982 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4983 const llvm::APInt &V = IL->getValue();
4984 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4985 return true;
4986 }
4987
Jordan Rose0e5badd2012-12-05 18:44:49 +00004988 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4989 Sema::LookupOrdinaryName);
4990 if (S.LookupName(Result, S.getCurScope())) {
4991 NamedDecl *ND = Result.getFoundDecl();
4992 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4993 if (TD->getUnderlyingType() == IntendedTy)
4994 IntendedTy = S.Context.getTypedefType(TD);
4995 }
4996 }
4997 }
4998
4999 // Special-case some of Darwin's platform-independence types by suggesting
5000 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005001 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005002 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005003 QualType CastTy;
5004 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5005 if (!CastTy.isNull()) {
5006 IntendedTy = CastTy;
5007 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005008 }
5009 }
5010
Jordan Rose22b74712012-09-05 22:56:19 +00005011 // We may be able to offer a FixItHint if it is a supported type.
5012 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00005013 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00005014 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005015
Jordan Rose22b74712012-09-05 22:56:19 +00005016 if (success) {
5017 // Get the fix string from the fixed format specifier
5018 SmallString<16> buf;
5019 llvm::raw_svector_ostream os(buf);
5020 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005021
Jordan Roseaee34382012-09-05 22:56:26 +00005022 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5023
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005024 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005025 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5026 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5027 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5028 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005029 // In this case, the specifier is wrong and should be changed to match
5030 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005031 EmitFormatDiagnostic(S.PDiag(diag)
5032 << AT.getRepresentativeTypeName(S.Context)
5033 << IntendedTy << IsEnum << E->getSourceRange(),
5034 E->getLocStart(),
5035 /*IsStringLocation*/ false, SpecRange,
5036 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005037 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005038 // The canonical type for formatting this value is different from the
5039 // actual type of the expression. (This occurs, for example, with Darwin's
5040 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5041 // should be printed as 'long' for 64-bit compatibility.)
5042 // Rather than emitting a normal format/argument mismatch, we want to
5043 // add a cast to the recommended type (and correct the format string
5044 // if necessary).
5045 SmallString<16> CastBuf;
5046 llvm::raw_svector_ostream CastFix(CastBuf);
5047 CastFix << "(";
5048 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5049 CastFix << ")";
5050
5051 SmallVector<FixItHint,4> Hints;
5052 if (!AT.matchesType(S.Context, IntendedTy))
5053 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5054
5055 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5056 // If there's already a cast present, just replace it.
5057 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5058 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5059
5060 } else if (!requiresParensToAddCast(E)) {
5061 // If the expression has high enough precedence,
5062 // just write the C-style cast.
5063 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5064 CastFix.str()));
5065 } else {
5066 // Otherwise, add parens around the expression as well as the cast.
5067 CastFix << "(";
5068 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5069 CastFix.str()));
5070
Alp Tokerb6cc5922014-05-03 03:45:55 +00005071 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00005072 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5073 }
5074
Jordan Rose0e5badd2012-12-05 18:44:49 +00005075 if (ShouldNotPrintDirectly) {
5076 // The expression has a type that should not be printed directly.
5077 // We extract the name from the typedef because we don't want to show
5078 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005079 StringRef Name;
5080 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5081 Name = TypedefTy->getDecl()->getName();
5082 else
5083 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005084 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00005085 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005086 << E->getSourceRange(),
5087 E->getLocStart(), /*IsStringLocation=*/false,
5088 SpecRange, Hints);
5089 } else {
5090 // In this case, the expression could be printed using a different
5091 // specifier, but we've decided that the specifier is probably correct
5092 // and we should cast instead. Just use the normal warning message.
5093 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00005094 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5095 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005096 << E->getSourceRange(),
5097 E->getLocStart(), /*IsStringLocation*/false,
5098 SpecRange, Hints);
5099 }
Jordan Roseaee34382012-09-05 22:56:26 +00005100 }
Jordan Rose22b74712012-09-05 22:56:19 +00005101 } else {
5102 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5103 SpecifierLen);
5104 // Since the warning for passing non-POD types to variadic functions
5105 // was deferred until now, we emit a warning for non-POD
5106 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00005107 switch (S.isValidVarArgType(ExprTy)) {
5108 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00005109 case Sema::VAK_ValidInCXX11: {
5110 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5111 if (match == analyze_printf::ArgType::NoMatchPedantic) {
5112 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5113 }
Richard Smithd7293d72013-08-05 18:49:43 +00005114
Seth Cantrellb4802962015-03-04 03:12:10 +00005115 EmitFormatDiagnostic(
5116 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5117 << IsEnum << CSR << E->getSourceRange(),
5118 E->getLocStart(), /*IsStringLocation*/ false, CSR);
5119 break;
5120 }
Richard Smithd7293d72013-08-05 18:49:43 +00005121 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00005122 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00005123 EmitFormatDiagnostic(
5124 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005125 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00005126 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00005127 << CallType
5128 << AT.getRepresentativeTypeName(S.Context)
5129 << CSR
5130 << E->getSourceRange(),
5131 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00005132 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00005133 break;
5134
5135 case Sema::VAK_Invalid:
5136 if (ExprTy->isObjCObjectType())
5137 EmitFormatDiagnostic(
5138 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5139 << S.getLangOpts().CPlusPlus11
5140 << ExprTy
5141 << CallType
5142 << AT.getRepresentativeTypeName(S.Context)
5143 << CSR
5144 << E->getSourceRange(),
5145 E->getLocStart(), /*IsStringLocation*/false, CSR);
5146 else
5147 // FIXME: If this is an initializer list, suggest removing the braces
5148 // or inserting a cast to the target type.
5149 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5150 << isa<InitListExpr>(E) << ExprTy << CallType
5151 << AT.getRepresentativeTypeName(S.Context)
5152 << E->getSourceRange();
5153 break;
5154 }
5155
5156 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5157 "format string specifier index out of range");
5158 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005159 }
5160
Ted Kremenekab278de2010-01-28 23:39:18 +00005161 return true;
5162}
5163
Ted Kremenek02087932010-07-16 02:11:22 +00005164//===--- CHECK: Scanf format string checking ------------------------------===//
5165
5166namespace {
5167class CheckScanfHandler : public CheckFormatHandler {
5168public:
5169 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
5170 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005171 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005172 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005173 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005174 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005175 llvm::SmallBitVector &CheckedVarArgs,
5176 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00005177 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5178 numDataArgs, beg, hasVAListArg,
5179 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005180 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00005181 {}
Ted Kremenek02087932010-07-16 02:11:22 +00005182
5183 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5184 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005185 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00005186
5187 bool HandleInvalidScanfConversionSpecifier(
5188 const analyze_scanf::ScanfSpecifier &FS,
5189 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005190 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005191
Craig Toppere14c0f82014-03-12 04:55:44 +00005192 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00005193};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005194} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005195
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005196void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5197 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005198 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5199 getLocationOfByte(end), /*IsStringLocation*/true,
5200 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005201}
5202
Ted Kremenekce815422010-07-19 21:25:57 +00005203bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5204 const analyze_scanf::ScanfSpecifier &FS,
5205 const char *startSpecifier,
5206 unsigned specifierLen) {
5207
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005208 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005209 FS.getConversionSpecifier();
5210
5211 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5212 getLocationOfByte(CS.getStart()),
5213 startSpecifier, specifierLen,
5214 CS.getStart(), CS.getLength());
5215}
5216
Ted Kremenek02087932010-07-16 02:11:22 +00005217bool CheckScanfHandler::HandleScanfSpecifier(
5218 const analyze_scanf::ScanfSpecifier &FS,
5219 const char *startSpecifier,
5220 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00005221 using namespace analyze_scanf;
5222 using namespace analyze_format_string;
5223
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005224 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005225
Ted Kremenek6cd69422010-07-19 22:01:06 +00005226 // Handle case where '%' and '*' don't consume an argument. These shouldn't
5227 // be used to decide if we are using positional arguments consistently.
5228 if (FS.consumesDataArgument()) {
5229 if (atFirstArg) {
5230 atFirstArg = false;
5231 usesPositionalArgs = FS.usesPositionalArg();
5232 }
5233 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005234 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5235 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005236 return false;
5237 }
Ted Kremenek02087932010-07-16 02:11:22 +00005238 }
5239
5240 // Check if the field with is non-zero.
5241 const OptionalAmount &Amt = FS.getFieldWidth();
5242 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5243 if (Amt.getConstantAmount() == 0) {
5244 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5245 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00005246 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5247 getLocationOfByte(Amt.getStart()),
5248 /*IsStringLocation*/true, R,
5249 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00005250 }
5251 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005252
Ted Kremenek02087932010-07-16 02:11:22 +00005253 if (!FS.consumesDataArgument()) {
5254 // FIXME: Technically specifying a precision or field width here
5255 // makes no sense. Worth issuing a warning at some point.
5256 return true;
5257 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005258
Ted Kremenek02087932010-07-16 02:11:22 +00005259 // Consume the argument.
5260 unsigned argIndex = FS.getArgIndex();
5261 if (argIndex < NumDataArgs) {
5262 // The check to see if the argIndex is valid will come later.
5263 // We set the bit here because we may exit early from this
5264 // function if we encounter some other error.
5265 CoveredArgs.set(argIndex);
5266 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005267
Ted Kremenek4407ea42010-07-20 20:04:47 +00005268 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005269 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005270 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5271 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005272 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005273 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005274 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005275 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5276 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005277
Jordan Rose92303592012-09-08 04:00:03 +00005278 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5279 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5280
Ted Kremenek02087932010-07-16 02:11:22 +00005281 // The remaining checks depend on the data arguments.
5282 if (HasVAListArg)
5283 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005284
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005285 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00005286 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00005287
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005288 // Check that the argument type matches the format specifier.
5289 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005290 if (!Ex)
5291 return true;
5292
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00005293 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005294
5295 if (!AT.isValid()) {
5296 return true;
5297 }
5298
Seth Cantrellb4802962015-03-04 03:12:10 +00005299 analyze_format_string::ArgType::MatchKind match =
5300 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005301 if (match == analyze_format_string::ArgType::Match) {
5302 return true;
5303 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005304
Seth Cantrell79340072015-03-04 05:58:08 +00005305 ScanfSpecifier fixedFS = FS;
5306 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5307 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005308
Seth Cantrell79340072015-03-04 05:58:08 +00005309 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5310 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5311 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5312 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005313
Seth Cantrell79340072015-03-04 05:58:08 +00005314 if (success) {
5315 // Get the fix string from the fixed format specifier.
5316 SmallString<128> buf;
5317 llvm::raw_svector_ostream os(buf);
5318 fixedFS.toString(os);
5319
5320 EmitFormatDiagnostic(
5321 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5322 << Ex->getType() << false << Ex->getSourceRange(),
5323 Ex->getLocStart(),
5324 /*IsStringLocation*/ false,
5325 getSpecifierRange(startSpecifier, specifierLen),
5326 FixItHint::CreateReplacement(
5327 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5328 } else {
5329 EmitFormatDiagnostic(S.PDiag(diag)
5330 << AT.getRepresentativeTypeName(S.Context)
5331 << Ex->getType() << false << Ex->getSourceRange(),
5332 Ex->getLocStart(),
5333 /*IsStringLocation*/ false,
5334 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005335 }
5336
Ted Kremenek02087932010-07-16 02:11:22 +00005337 return true;
5338}
5339
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005340static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5341 const Expr *OrigFormatExpr,
5342 ArrayRef<const Expr *> Args,
5343 bool HasVAListArg, unsigned format_idx,
5344 unsigned firstDataArg,
5345 Sema::FormatStringType Type,
5346 bool inFunctionCall,
5347 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005348 llvm::SmallBitVector &CheckedVarArgs,
5349 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005350 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005351 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005352 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005353 S, inFunctionCall, Args[format_idx],
5354 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005355 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005356 return;
5357 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005358
Ted Kremenekab278de2010-01-28 23:39:18 +00005359 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005360 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005361 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005362 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005363 const ConstantArrayType *T =
5364 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005365 assert(T && "String literal not of constant array type!");
5366 size_t TypeSize = T->getSize().getZExtValue();
5367 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005368 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005369
5370 // Emit a warning if the string literal is truncated and does not contain an
5371 // embedded null character.
5372 if (TypeSize <= StrRef.size() &&
5373 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5374 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005375 S, inFunctionCall, Args[format_idx],
5376 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005377 FExpr->getLocStart(),
5378 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5379 return;
5380 }
5381
Ted Kremenekab278de2010-01-28 23:39:18 +00005382 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005383 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005384 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005385 S, inFunctionCall, Args[format_idx],
5386 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005387 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005388 return;
5389 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005390
5391 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5392 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5393 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5394 numDataArgs, (Type == Sema::FST_NSString ||
5395 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005396 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005397 inFunctionCall, CallType, CheckedVarArgs,
5398 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005399
Hans Wennborg23926bd2011-12-15 10:25:47 +00005400 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005401 S.getLangOpts(),
5402 S.Context.getTargetInfo(),
5403 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005404 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005405 } else if (Type == Sema::FST_Scanf) {
5406 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005407 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005408 inFunctionCall, CallType, CheckedVarArgs,
5409 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005410
Hans Wennborg23926bd2011-12-15 10:25:47 +00005411 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005412 S.getLangOpts(),
5413 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005414 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005415 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005416}
5417
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005418bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5419 // Str - The format string. NOTE: this is NOT null-terminated!
5420 StringRef StrRef = FExpr->getString();
5421 const char *Str = StrRef.data();
5422 // Account for cases where the string literal is truncated in a declaration.
5423 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5424 assert(T && "String literal not of constant array type!");
5425 size_t TypeSize = T->getSize().getZExtValue();
5426 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5427 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5428 getLangOpts(),
5429 Context.getTargetInfo());
5430}
5431
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005432//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5433
5434// Returns the related absolute value function that is larger, of 0 if one
5435// does not exist.
5436static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5437 switch (AbsFunction) {
5438 default:
5439 return 0;
5440
5441 case Builtin::BI__builtin_abs:
5442 return Builtin::BI__builtin_labs;
5443 case Builtin::BI__builtin_labs:
5444 return Builtin::BI__builtin_llabs;
5445 case Builtin::BI__builtin_llabs:
5446 return 0;
5447
5448 case Builtin::BI__builtin_fabsf:
5449 return Builtin::BI__builtin_fabs;
5450 case Builtin::BI__builtin_fabs:
5451 return Builtin::BI__builtin_fabsl;
5452 case Builtin::BI__builtin_fabsl:
5453 return 0;
5454
5455 case Builtin::BI__builtin_cabsf:
5456 return Builtin::BI__builtin_cabs;
5457 case Builtin::BI__builtin_cabs:
5458 return Builtin::BI__builtin_cabsl;
5459 case Builtin::BI__builtin_cabsl:
5460 return 0;
5461
5462 case Builtin::BIabs:
5463 return Builtin::BIlabs;
5464 case Builtin::BIlabs:
5465 return Builtin::BIllabs;
5466 case Builtin::BIllabs:
5467 return 0;
5468
5469 case Builtin::BIfabsf:
5470 return Builtin::BIfabs;
5471 case Builtin::BIfabs:
5472 return Builtin::BIfabsl;
5473 case Builtin::BIfabsl:
5474 return 0;
5475
5476 case Builtin::BIcabsf:
5477 return Builtin::BIcabs;
5478 case Builtin::BIcabs:
5479 return Builtin::BIcabsl;
5480 case Builtin::BIcabsl:
5481 return 0;
5482 }
5483}
5484
5485// Returns the argument type of the absolute value function.
5486static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5487 unsigned AbsType) {
5488 if (AbsType == 0)
5489 return QualType();
5490
5491 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5492 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5493 if (Error != ASTContext::GE_None)
5494 return QualType();
5495
5496 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5497 if (!FT)
5498 return QualType();
5499
5500 if (FT->getNumParams() != 1)
5501 return QualType();
5502
5503 return FT->getParamType(0);
5504}
5505
5506// Returns the best absolute value function, or zero, based on type and
5507// current absolute value function.
5508static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5509 unsigned AbsFunctionKind) {
5510 unsigned BestKind = 0;
5511 uint64_t ArgSize = Context.getTypeSize(ArgType);
5512 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5513 Kind = getLargerAbsoluteValueFunction(Kind)) {
5514 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5515 if (Context.getTypeSize(ParamType) >= ArgSize) {
5516 if (BestKind == 0)
5517 BestKind = Kind;
5518 else if (Context.hasSameType(ParamType, ArgType)) {
5519 BestKind = Kind;
5520 break;
5521 }
5522 }
5523 }
5524 return BestKind;
5525}
5526
5527enum AbsoluteValueKind {
5528 AVK_Integer,
5529 AVK_Floating,
5530 AVK_Complex
5531};
5532
5533static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5534 if (T->isIntegralOrEnumerationType())
5535 return AVK_Integer;
5536 if (T->isRealFloatingType())
5537 return AVK_Floating;
5538 if (T->isAnyComplexType())
5539 return AVK_Complex;
5540
5541 llvm_unreachable("Type not integer, floating, or complex");
5542}
5543
5544// Changes the absolute value function to a different type. Preserves whether
5545// the function is a builtin.
5546static unsigned changeAbsFunction(unsigned AbsKind,
5547 AbsoluteValueKind ValueKind) {
5548 switch (ValueKind) {
5549 case AVK_Integer:
5550 switch (AbsKind) {
5551 default:
5552 return 0;
5553 case Builtin::BI__builtin_fabsf:
5554 case Builtin::BI__builtin_fabs:
5555 case Builtin::BI__builtin_fabsl:
5556 case Builtin::BI__builtin_cabsf:
5557 case Builtin::BI__builtin_cabs:
5558 case Builtin::BI__builtin_cabsl:
5559 return Builtin::BI__builtin_abs;
5560 case Builtin::BIfabsf:
5561 case Builtin::BIfabs:
5562 case Builtin::BIfabsl:
5563 case Builtin::BIcabsf:
5564 case Builtin::BIcabs:
5565 case Builtin::BIcabsl:
5566 return Builtin::BIabs;
5567 }
5568 case AVK_Floating:
5569 switch (AbsKind) {
5570 default:
5571 return 0;
5572 case Builtin::BI__builtin_abs:
5573 case Builtin::BI__builtin_labs:
5574 case Builtin::BI__builtin_llabs:
5575 case Builtin::BI__builtin_cabsf:
5576 case Builtin::BI__builtin_cabs:
5577 case Builtin::BI__builtin_cabsl:
5578 return Builtin::BI__builtin_fabsf;
5579 case Builtin::BIabs:
5580 case Builtin::BIlabs:
5581 case Builtin::BIllabs:
5582 case Builtin::BIcabsf:
5583 case Builtin::BIcabs:
5584 case Builtin::BIcabsl:
5585 return Builtin::BIfabsf;
5586 }
5587 case AVK_Complex:
5588 switch (AbsKind) {
5589 default:
5590 return 0;
5591 case Builtin::BI__builtin_abs:
5592 case Builtin::BI__builtin_labs:
5593 case Builtin::BI__builtin_llabs:
5594 case Builtin::BI__builtin_fabsf:
5595 case Builtin::BI__builtin_fabs:
5596 case Builtin::BI__builtin_fabsl:
5597 return Builtin::BI__builtin_cabsf;
5598 case Builtin::BIabs:
5599 case Builtin::BIlabs:
5600 case Builtin::BIllabs:
5601 case Builtin::BIfabsf:
5602 case Builtin::BIfabs:
5603 case Builtin::BIfabsl:
5604 return Builtin::BIcabsf;
5605 }
5606 }
5607 llvm_unreachable("Unable to convert function");
5608}
5609
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005610static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005611 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5612 if (!FnInfo)
5613 return 0;
5614
5615 switch (FDecl->getBuiltinID()) {
5616 default:
5617 return 0;
5618 case Builtin::BI__builtin_abs:
5619 case Builtin::BI__builtin_fabs:
5620 case Builtin::BI__builtin_fabsf:
5621 case Builtin::BI__builtin_fabsl:
5622 case Builtin::BI__builtin_labs:
5623 case Builtin::BI__builtin_llabs:
5624 case Builtin::BI__builtin_cabs:
5625 case Builtin::BI__builtin_cabsf:
5626 case Builtin::BI__builtin_cabsl:
5627 case Builtin::BIabs:
5628 case Builtin::BIlabs:
5629 case Builtin::BIllabs:
5630 case Builtin::BIfabs:
5631 case Builtin::BIfabsf:
5632 case Builtin::BIfabsl:
5633 case Builtin::BIcabs:
5634 case Builtin::BIcabsf:
5635 case Builtin::BIcabsl:
5636 return FDecl->getBuiltinID();
5637 }
5638 llvm_unreachable("Unknown Builtin type");
5639}
5640
5641// If the replacement is valid, emit a note with replacement function.
5642// Additionally, suggest including the proper header if not already included.
5643static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005644 unsigned AbsKind, QualType ArgType) {
5645 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005646 const char *HeaderName = nullptr;
5647 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005648 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5649 FunctionName = "std::abs";
5650 if (ArgType->isIntegralOrEnumerationType()) {
5651 HeaderName = "cstdlib";
5652 } else if (ArgType->isRealFloatingType()) {
5653 HeaderName = "cmath";
5654 } else {
5655 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005656 }
Richard Trieubeffb832014-04-15 23:47:53 +00005657
5658 // Lookup all std::abs
5659 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005660 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005661 R.suppressDiagnostics();
5662 S.LookupQualifiedName(R, Std);
5663
5664 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005665 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005666 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5667 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5668 } else {
5669 FDecl = dyn_cast<FunctionDecl>(I);
5670 }
5671 if (!FDecl)
5672 continue;
5673
5674 // Found std::abs(), check that they are the right ones.
5675 if (FDecl->getNumParams() != 1)
5676 continue;
5677
5678 // Check that the parameter type can handle the argument.
5679 QualType ParamType = FDecl->getParamDecl(0)->getType();
5680 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5681 S.Context.getTypeSize(ArgType) <=
5682 S.Context.getTypeSize(ParamType)) {
5683 // Found a function, don't need the header hint.
5684 EmitHeaderHint = false;
5685 break;
5686 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005687 }
Richard Trieubeffb832014-04-15 23:47:53 +00005688 }
5689 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005690 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005691 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5692
5693 if (HeaderName) {
5694 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5695 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5696 R.suppressDiagnostics();
5697 S.LookupName(R, S.getCurScope());
5698
5699 if (R.isSingleResult()) {
5700 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5701 if (FD && FD->getBuiltinID() == AbsKind) {
5702 EmitHeaderHint = false;
5703 } else {
5704 return;
5705 }
5706 } else if (!R.empty()) {
5707 return;
5708 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005709 }
5710 }
5711
5712 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005713 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005714
Richard Trieubeffb832014-04-15 23:47:53 +00005715 if (!HeaderName)
5716 return;
5717
5718 if (!EmitHeaderHint)
5719 return;
5720
Alp Toker5d96e0a2014-07-11 20:53:51 +00005721 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5722 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005723}
5724
5725static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5726 if (!FDecl)
5727 return false;
5728
5729 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5730 return false;
5731
5732 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5733
5734 while (ND && ND->isInlineNamespace()) {
5735 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005736 }
Richard Trieubeffb832014-04-15 23:47:53 +00005737
5738 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5739 return false;
5740
5741 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5742 return false;
5743
5744 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005745}
5746
5747// Warn when using the wrong abs() function.
5748void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5749 const FunctionDecl *FDecl,
5750 IdentifierInfo *FnInfo) {
5751 if (Call->getNumArgs() != 1)
5752 return;
5753
5754 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005755 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5756 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005757 return;
5758
5759 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5760 QualType ParamType = Call->getArg(0)->getType();
5761
Alp Toker5d96e0a2014-07-11 20:53:51 +00005762 // Unsigned types cannot be negative. Suggest removing the absolute value
5763 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005764 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005765 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005766 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005767 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5768 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005769 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005770 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5771 return;
5772 }
5773
David Majnemer7f77eb92015-11-15 03:04:34 +00005774 // Taking the absolute value of a pointer is very suspicious, they probably
5775 // wanted to index into an array, dereference a pointer, call a function, etc.
5776 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5777 unsigned DiagType = 0;
5778 if (ArgType->isFunctionType())
5779 DiagType = 1;
5780 else if (ArgType->isArrayType())
5781 DiagType = 2;
5782
5783 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5784 return;
5785 }
5786
Richard Trieubeffb832014-04-15 23:47:53 +00005787 // std::abs has overloads which prevent most of the absolute value problems
5788 // from occurring.
5789 if (IsStdAbs)
5790 return;
5791
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005792 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5793 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5794
5795 // The argument and parameter are the same kind. Check if they are the right
5796 // size.
5797 if (ArgValueKind == ParamValueKind) {
5798 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5799 return;
5800
5801 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5802 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5803 << FDecl << ArgType << ParamType;
5804
5805 if (NewAbsKind == 0)
5806 return;
5807
5808 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005809 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005810 return;
5811 }
5812
5813 // ArgValueKind != ParamValueKind
5814 // The wrong type of absolute value function was used. Attempt to find the
5815 // proper one.
5816 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5817 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5818 if (NewAbsKind == 0)
5819 return;
5820
5821 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5822 << FDecl << ParamValueKind << ArgValueKind;
5823
5824 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005825 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005826}
5827
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005828//===--- CHECK: Standard memory functions ---------------------------------===//
5829
Nico Weber0e6daef2013-12-26 23:38:39 +00005830/// \brief Takes the expression passed to the size_t parameter of functions
5831/// such as memcmp, strncat, etc and warns if it's a comparison.
5832///
5833/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5834static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5835 IdentifierInfo *FnName,
5836 SourceLocation FnLoc,
5837 SourceLocation RParenLoc) {
5838 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5839 if (!Size)
5840 return false;
5841
5842 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5843 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5844 return false;
5845
Nico Weber0e6daef2013-12-26 23:38:39 +00005846 SourceRange SizeRange = Size->getSourceRange();
5847 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5848 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005849 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005850 << FnName << FixItHint::CreateInsertion(
5851 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005852 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005853 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005854 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005855 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5856 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005857
5858 return true;
5859}
5860
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005861/// \brief Determine whether the given type is or contains a dynamic class type
5862/// (e.g., whether it has a vtable).
5863static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5864 bool &IsContained) {
5865 // Look through array types while ignoring qualifiers.
5866 const Type *Ty = T->getBaseElementTypeUnsafe();
5867 IsContained = false;
5868
5869 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5870 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00005871 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005872 return nullptr;
5873
5874 if (RD->isDynamicClass())
5875 return RD;
5876
5877 // Check all the fields. If any bases were dynamic, the class is dynamic.
5878 // It's impossible for a class to transitively contain itself by value, so
5879 // infinite recursion is impossible.
5880 for (auto *FD : RD->fields()) {
5881 bool SubContained;
5882 if (const CXXRecordDecl *ContainedRD =
5883 getContainedDynamicClass(FD->getType(), SubContained)) {
5884 IsContained = true;
5885 return ContainedRD;
5886 }
5887 }
5888
5889 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005890}
5891
Chandler Carruth889ed862011-06-21 23:04:20 +00005892/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005893/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005894static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005895 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005896 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5897 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5898 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005899
Craig Topperc3ec1492014-05-26 06:22:03 +00005900 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005901}
5902
Chandler Carruth889ed862011-06-21 23:04:20 +00005903/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005904static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005905 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5906 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5907 if (SizeOf->getKind() == clang::UETT_SizeOf)
5908 return SizeOf->getTypeOfArgument();
5909
5910 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005911}
5912
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005913/// \brief Check for dangerous or invalid arguments to memset().
5914///
Chandler Carruthac687262011-06-03 06:23:57 +00005915/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005916/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5917/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005918///
5919/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005920void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005921 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005922 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005923 assert(BId != 0);
5924
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005925 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005926 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005927 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005928 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005929 return;
5930
Anna Zaks22122702012-01-17 00:37:07 +00005931 unsigned LastArg = (BId == Builtin::BImemset ||
5932 BId == Builtin::BIstrndup ? 1 : 2);
5933 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005934 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005935
Nico Weber0e6daef2013-12-26 23:38:39 +00005936 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5937 Call->getLocStart(), Call->getRParenLoc()))
5938 return;
5939
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005940 // We have special checking when the length is a sizeof expression.
5941 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5942 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5943 llvm::FoldingSetNodeID SizeOfArgID;
5944
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005945 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5946 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005947 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005948
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005949 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005950 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005951 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005952 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005953
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005954 // Never warn about void type pointers. This can be used to suppress
5955 // false positives.
5956 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005957 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005958
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005959 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5960 // actually comparing the expressions for equality. Because computing the
5961 // expression IDs can be expensive, we only do this if the diagnostic is
5962 // enabled.
5963 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005964 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5965 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005966 // We only compute IDs for expressions if the warning is enabled, and
5967 // cache the sizeof arg's ID.
5968 if (SizeOfArgID == llvm::FoldingSetNodeID())
5969 SizeOfArg->Profile(SizeOfArgID, Context, true);
5970 llvm::FoldingSetNodeID DestID;
5971 Dest->Profile(DestID, Context, true);
5972 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005973 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5974 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005975 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005976 StringRef ReadableName = FnName->getName();
5977
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005978 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005979 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005980 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005981 if (!PointeeTy->isIncompleteType() &&
5982 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005983 ActionIdx = 2; // If the pointee's size is sizeof(char),
5984 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005985
5986 // If the function is defined as a builtin macro, do not show macro
5987 // expansion.
5988 SourceLocation SL = SizeOfArg->getExprLoc();
5989 SourceRange DSR = Dest->getSourceRange();
5990 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005991 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005992
5993 if (SM.isMacroArgExpansion(SL)) {
5994 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5995 SL = SM.getSpellingLoc(SL);
5996 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5997 SM.getSpellingLoc(DSR.getEnd()));
5998 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5999 SM.getSpellingLoc(SSR.getEnd()));
6000 }
6001
Anna Zaksd08d9152012-05-30 23:14:52 +00006002 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006003 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00006004 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00006005 << PointeeTy
6006 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00006007 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006008 << SSR);
6009 DiagRuntimeBehavior(SL, SizeOfArg,
6010 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6011 << ActionIdx
6012 << SSR);
6013
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006014 break;
6015 }
6016 }
6017
6018 // Also check for cases where the sizeof argument is the exact same
6019 // type as the memory argument, and where it points to a user-defined
6020 // record type.
6021 if (SizeOfArgTy != QualType()) {
6022 if (PointeeTy->isRecordType() &&
6023 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6024 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6025 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6026 << FnName << SizeOfArgTy << ArgIdx
6027 << PointeeTy << Dest->getSourceRange()
6028 << LenExpr->getSourceRange());
6029 break;
6030 }
Nico Weberc5e73862011-06-14 16:14:58 +00006031 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006032 } else if (DestTy->isArrayType()) {
6033 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006034 }
Nico Weberc5e73862011-06-14 16:14:58 +00006035
Nico Weberc44b35e2015-03-21 17:37:46 +00006036 if (PointeeTy == QualType())
6037 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006038
Nico Weberc44b35e2015-03-21 17:37:46 +00006039 // Always complain about dynamic classes.
6040 bool IsContained;
6041 if (const CXXRecordDecl *ContainedRD =
6042 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006043
Nico Weberc44b35e2015-03-21 17:37:46 +00006044 unsigned OperationType = 0;
6045 // "overwritten" if we're warning about the destination for any call
6046 // but memcmp; otherwise a verb appropriate to the call.
6047 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6048 if (BId == Builtin::BImemcpy)
6049 OperationType = 1;
6050 else if(BId == Builtin::BImemmove)
6051 OperationType = 2;
6052 else if (BId == Builtin::BImemcmp)
6053 OperationType = 3;
6054 }
6055
John McCall31168b02011-06-15 23:02:42 +00006056 DiagRuntimeBehavior(
6057 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00006058 PDiag(diag::warn_dyn_class_memaccess)
6059 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6060 << FnName << IsContained << ContainedRD << OperationType
6061 << Call->getCallee()->getSourceRange());
6062 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6063 BId != Builtin::BImemset)
6064 DiagRuntimeBehavior(
6065 Dest->getExprLoc(), Dest,
6066 PDiag(diag::warn_arc_object_memaccess)
6067 << ArgIdx << FnName << PointeeTy
6068 << Call->getCallee()->getSourceRange());
6069 else
6070 continue;
6071
6072 DiagRuntimeBehavior(
6073 Dest->getExprLoc(), Dest,
6074 PDiag(diag::note_bad_memaccess_silence)
6075 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6076 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006077 }
6078}
6079
Ted Kremenek6865f772011-08-18 20:55:45 +00006080// A little helper routine: ignore addition and subtraction of integer literals.
6081// This intentionally does not ignore all integer constant expressions because
6082// we don't want to remove sizeof().
6083static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6084 Ex = Ex->IgnoreParenCasts();
6085
6086 for (;;) {
6087 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6088 if (!BO || !BO->isAdditiveOp())
6089 break;
6090
6091 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6092 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6093
6094 if (isa<IntegerLiteral>(RHS))
6095 Ex = LHS;
6096 else if (isa<IntegerLiteral>(LHS))
6097 Ex = RHS;
6098 else
6099 break;
6100 }
6101
6102 return Ex;
6103}
6104
Anna Zaks13b08572012-08-08 21:42:23 +00006105static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6106 ASTContext &Context) {
6107 // Only handle constant-sized or VLAs, but not flexible members.
6108 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6109 // Only issue the FIXIT for arrays of size > 1.
6110 if (CAT->getSize().getSExtValue() <= 1)
6111 return false;
6112 } else if (!Ty->isVariableArrayType()) {
6113 return false;
6114 }
6115 return true;
6116}
6117
Ted Kremenek6865f772011-08-18 20:55:45 +00006118// Warn if the user has made the 'size' argument to strlcpy or strlcat
6119// be the size of the source, instead of the destination.
6120void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6121 IdentifierInfo *FnName) {
6122
6123 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00006124 unsigned NumArgs = Call->getNumArgs();
6125 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00006126 return;
6127
6128 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6129 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00006130 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00006131
6132 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6133 Call->getLocStart(), Call->getRParenLoc()))
6134 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00006135
6136 // Look for 'strlcpy(dst, x, sizeof(x))'
6137 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6138 CompareWithSrc = Ex;
6139 else {
6140 // Look for 'strlcpy(dst, x, strlen(x))'
6141 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00006142 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6143 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00006144 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6145 }
6146 }
6147
6148 if (!CompareWithSrc)
6149 return;
6150
6151 // Determine if the argument to sizeof/strlen is equal to the source
6152 // argument. In principle there's all kinds of things you could do
6153 // here, for instance creating an == expression and evaluating it with
6154 // EvaluateAsBooleanCondition, but this uses a more direct technique:
6155 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6156 if (!SrcArgDRE)
6157 return;
6158
6159 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6160 if (!CompareWithSrcDRE ||
6161 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6162 return;
6163
6164 const Expr *OriginalSizeArg = Call->getArg(2);
6165 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6166 << OriginalSizeArg->getSourceRange() << FnName;
6167
6168 // Output a FIXIT hint if the destination is an array (rather than a
6169 // pointer to an array). This could be enhanced to handle some
6170 // pointers if we know the actual size, like if DstArg is 'array+2'
6171 // we could say 'sizeof(array)-2'.
6172 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00006173 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00006174 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006175
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006176 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006177 llvm::raw_svector_ostream OS(sizeString);
6178 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006179 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00006180 OS << ")";
6181
6182 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6183 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6184 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00006185}
6186
Anna Zaks314cd092012-02-01 19:08:57 +00006187/// Check if two expressions refer to the same declaration.
6188static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6189 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6190 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6191 return D1->getDecl() == D2->getDecl();
6192 return false;
6193}
6194
6195static const Expr *getStrlenExprArg(const Expr *E) {
6196 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6197 const FunctionDecl *FD = CE->getDirectCallee();
6198 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00006199 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006200 return CE->getArg(0)->IgnoreParenCasts();
6201 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006202 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006203}
6204
6205// Warn on anti-patterns as the 'size' argument to strncat.
6206// The correct size argument should look like following:
6207// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6208void Sema::CheckStrncatArguments(const CallExpr *CE,
6209 IdentifierInfo *FnName) {
6210 // Don't crash if the user has the wrong number of arguments.
6211 if (CE->getNumArgs() < 3)
6212 return;
6213 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6214 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6215 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6216
Nico Weber0e6daef2013-12-26 23:38:39 +00006217 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6218 CE->getRParenLoc()))
6219 return;
6220
Anna Zaks314cd092012-02-01 19:08:57 +00006221 // Identify common expressions, which are wrongly used as the size argument
6222 // to strncat and may lead to buffer overflows.
6223 unsigned PatternType = 0;
6224 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6225 // - sizeof(dst)
6226 if (referToTheSameDecl(SizeOfArg, DstArg))
6227 PatternType = 1;
6228 // - sizeof(src)
6229 else if (referToTheSameDecl(SizeOfArg, SrcArg))
6230 PatternType = 2;
6231 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6232 if (BE->getOpcode() == BO_Sub) {
6233 const Expr *L = BE->getLHS()->IgnoreParenCasts();
6234 const Expr *R = BE->getRHS()->IgnoreParenCasts();
6235 // - sizeof(dst) - strlen(dst)
6236 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6237 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6238 PatternType = 1;
6239 // - sizeof(src) - (anything)
6240 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6241 PatternType = 2;
6242 }
6243 }
6244
6245 if (PatternType == 0)
6246 return;
6247
Anna Zaks5069aa32012-02-03 01:27:37 +00006248 // Generate the diagnostic.
6249 SourceLocation SL = LenArg->getLocStart();
6250 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006251 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00006252
6253 // If the function is defined as a builtin macro, do not show macro expansion.
6254 if (SM.isMacroArgExpansion(SL)) {
6255 SL = SM.getSpellingLoc(SL);
6256 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6257 SM.getSpellingLoc(SR.getEnd()));
6258 }
6259
Anna Zaks13b08572012-08-08 21:42:23 +00006260 // Check if the destination is an array (rather than a pointer to an array).
6261 QualType DstTy = DstArg->getType();
6262 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6263 Context);
6264 if (!isKnownSizeArray) {
6265 if (PatternType == 1)
6266 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6267 else
6268 Diag(SL, diag::warn_strncat_src_size) << SR;
6269 return;
6270 }
6271
Anna Zaks314cd092012-02-01 19:08:57 +00006272 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006273 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006274 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006275 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006276
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006277 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006278 llvm::raw_svector_ostream OS(sizeString);
6279 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006280 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006281 OS << ") - ";
6282 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006283 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006284 OS << ") - 1";
6285
Anna Zaks5069aa32012-02-03 01:27:37 +00006286 Diag(SL, diag::note_strncat_wrong_size)
6287 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006288}
6289
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006290//===--- CHECK: Return Address of Stack Variable --------------------------===//
6291
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006292static const Expr *EvalVal(const Expr *E,
6293 SmallVectorImpl<const DeclRefExpr *> &refVars,
6294 const Decl *ParentDecl);
6295static const Expr *EvalAddr(const Expr *E,
6296 SmallVectorImpl<const DeclRefExpr *> &refVars,
6297 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006298
6299/// CheckReturnStackAddr - Check if a return statement returns the address
6300/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006301static void
6302CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6303 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006304
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006305 const Expr *stackE = nullptr;
6306 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006307
6308 // Perform checking for returned stack addresses, local blocks,
6309 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006310 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006311 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006312 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006313 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006314 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006315 }
6316
Craig Topperc3ec1492014-05-26 06:22:03 +00006317 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006318 return; // Nothing suspicious was found.
6319
6320 SourceLocation diagLoc;
6321 SourceRange diagRange;
6322 if (refVars.empty()) {
6323 diagLoc = stackE->getLocStart();
6324 diagRange = stackE->getSourceRange();
6325 } else {
6326 // We followed through a reference variable. 'stackE' contains the
6327 // problematic expression but we will warn at the return statement pointing
6328 // at the reference variable. We will later display the "trail" of
6329 // reference variables using notes.
6330 diagLoc = refVars[0]->getLocStart();
6331 diagRange = refVars[0]->getSourceRange();
6332 }
6333
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006334 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6335 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006336 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006337 << DR->getDecl()->getDeclName() << diagRange;
6338 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006339 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006340 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006341 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006342 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00006343 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6344 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006345 }
6346
6347 // Display the "trail" of reference variables that we followed until we
6348 // found the problematic expression using notes.
6349 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006350 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006351 // If this var binds to another reference var, show the range of the next
6352 // var, otherwise the var binds to the problematic expression, in which case
6353 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006354 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6355 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006356 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6357 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006358 }
6359}
6360
6361/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6362/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006363/// to a location on the stack, a local block, an address of a label, or a
6364/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006365/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006366/// encounter a subexpression that (1) clearly does not lead to one of the
6367/// above problematic expressions (2) is something we cannot determine leads to
6368/// a problematic expression based on such local checking.
6369///
6370/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6371/// the expression that they point to. Such variables are added to the
6372/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006373///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006374/// EvalAddr processes expressions that are pointers that are used as
6375/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006376/// At the base case of the recursion is a check for the above problematic
6377/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006378///
6379/// This implementation handles:
6380///
6381/// * pointer-to-pointer casts
6382/// * implicit conversions from array references to pointers
6383/// * taking the address of fields
6384/// * arbitrary interplay between "&" and "*" operators
6385/// * pointer arithmetic from an address of a stack variable
6386/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006387static const Expr *EvalAddr(const Expr *E,
6388 SmallVectorImpl<const DeclRefExpr *> &refVars,
6389 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006390 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006391 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006392
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006393 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006394 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006395 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006396 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006397 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006398
Peter Collingbourne91147592011-04-15 00:35:48 +00006399 E = E->IgnoreParens();
6400
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006401 // Our "symbolic interpreter" is just a dispatch off the currently
6402 // viewed AST node. We then recursively traverse the AST by calling
6403 // EvalAddr and EvalVal appropriately.
6404 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006405 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006406 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006407
Richard Smith40f08eb2014-01-30 22:05:38 +00006408 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006409 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006410 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006411
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006412 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006413 // If this is a reference variable, follow through to the expression that
6414 // it points to.
6415 if (V->hasLocalStorage() &&
6416 V->getType()->isReferenceType() && V->hasInit()) {
6417 // Add the reference variable to the "trail".
6418 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006419 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006420 }
6421
Craig Topperc3ec1492014-05-26 06:22:03 +00006422 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006423 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006424
Chris Lattner934edb22007-12-28 05:31:15 +00006425 case Stmt::UnaryOperatorClass: {
6426 // The only unary operator that make sense to handle here
6427 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006428 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006429
John McCalle3027922010-08-25 11:45:40 +00006430 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006431 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006432 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006433 }
Mike Stump11289f42009-09-09 15:08:12 +00006434
Chris Lattner934edb22007-12-28 05:31:15 +00006435 case Stmt::BinaryOperatorClass: {
6436 // Handle pointer arithmetic. All other binary operators are not valid
6437 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006438 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006439 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006440
John McCalle3027922010-08-25 11:45:40 +00006441 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006442 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006443
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006444 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006445
6446 // Determine which argument is the real pointer base. It could be
6447 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006448 if (!Base->getType()->isPointerType())
6449 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006450
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006451 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006452 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006453 }
Steve Naroff2752a172008-09-10 19:17:48 +00006454
Chris Lattner934edb22007-12-28 05:31:15 +00006455 // For conditional operators we need to see if either the LHS or RHS are
6456 // valid DeclRefExpr*s. If one of them is valid, we return it.
6457 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006458 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006459
Chris Lattner934edb22007-12-28 05:31:15 +00006460 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006461 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006462 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006463 // In C++, we can have a throw-expression, which has 'void' type.
6464 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006465 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006466 return LHS;
6467 }
Chris Lattner934edb22007-12-28 05:31:15 +00006468
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006469 // In C++, we can have a throw-expression, which has 'void' type.
6470 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006471 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006472
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006473 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006474 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006475
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006476 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006477 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006478 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006479 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006480
6481 case Stmt::AddrLabelExprClass:
6482 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006483
John McCall28fc7092011-11-10 05:35:25 +00006484 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006485 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6486 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006487
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006488 // For casts, we need to handle conversions from arrays to
6489 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006490 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006491 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006492 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006493 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006494 case Stmt::CXXStaticCastExprClass:
6495 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006496 case Stmt::CXXConstCastExprClass:
6497 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006498 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006499 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006500 case CK_LValueToRValue:
6501 case CK_NoOp:
6502 case CK_BaseToDerived:
6503 case CK_DerivedToBase:
6504 case CK_UncheckedDerivedToBase:
6505 case CK_Dynamic:
6506 case CK_CPointerToObjCPointerCast:
6507 case CK_BlockPointerToObjCPointerCast:
6508 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006509 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006510
6511 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006512 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006513
Richard Trieudadefde2014-07-02 04:39:38 +00006514 case CK_BitCast:
6515 if (SubExpr->getType()->isAnyPointerType() ||
6516 SubExpr->getType()->isBlockPointerType() ||
6517 SubExpr->getType()->isObjCQualifiedIdType())
6518 return EvalAddr(SubExpr, refVars, ParentDecl);
6519 else
6520 return nullptr;
6521
Eli Friedman8195ad72012-02-23 23:04:32 +00006522 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006523 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006524 }
Chris Lattner934edb22007-12-28 05:31:15 +00006525 }
Mike Stump11289f42009-09-09 15:08:12 +00006526
Douglas Gregorfe314812011-06-21 17:03:29 +00006527 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006528 if (const Expr *Result =
6529 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6530 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006531 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006532 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006533
Chris Lattner934edb22007-12-28 05:31:15 +00006534 // Everything else: we simply don't reason about them.
6535 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006536 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006537 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006538}
Mike Stump11289f42009-09-09 15:08:12 +00006539
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006540/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6541/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006542static const Expr *EvalVal(const Expr *E,
6543 SmallVectorImpl<const DeclRefExpr *> &refVars,
6544 const Decl *ParentDecl) {
6545 do {
6546 // We should only be called for evaluating non-pointer expressions, or
6547 // expressions with a pointer type that are not used as references but
6548 // instead
6549 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006550
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006551 // Our "symbolic interpreter" is just a dispatch off the currently
6552 // viewed AST node. We then recursively traverse the AST by calling
6553 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006554
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006555 E = E->IgnoreParens();
6556 switch (E->getStmtClass()) {
6557 case Stmt::ImplicitCastExprClass: {
6558 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6559 if (IE->getValueKind() == VK_LValue) {
6560 E = IE->getSubExpr();
6561 continue;
6562 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006563 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006564 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006565
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006566 case Stmt::ExprWithCleanupsClass:
6567 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6568 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006569
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006570 case Stmt::DeclRefExprClass: {
6571 // When we hit a DeclRefExpr we are looking at code that refers to a
6572 // variable's name. If it's not a reference variable we check if it has
6573 // local storage within the function, and if so, return the expression.
6574 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6575
6576 // If we leave the immediate function, the lifetime isn't about to end.
6577 if (DR->refersToEnclosingVariableOrCapture())
6578 return nullptr;
6579
6580 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6581 // Check if it refers to itself, e.g. "int& i = i;".
6582 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006583 return DR;
6584
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006585 if (V->hasLocalStorage()) {
6586 if (!V->getType()->isReferenceType())
6587 return DR;
6588
6589 // Reference variable, follow through to the expression that
6590 // it points to.
6591 if (V->hasInit()) {
6592 // Add the reference variable to the "trail".
6593 refVars.push_back(DR);
6594 return EvalVal(V->getInit(), refVars, V);
6595 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006596 }
6597 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006598
6599 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006600 }
Mike Stump11289f42009-09-09 15:08:12 +00006601
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006602 case Stmt::UnaryOperatorClass: {
6603 // The only unary operator that make sense to handle here
6604 // is Deref. All others don't resolve to a "name." This includes
6605 // handling all sorts of rvalues passed to a unary operator.
6606 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006607
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006608 if (U->getOpcode() == UO_Deref)
6609 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006610
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006611 return nullptr;
6612 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006613
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006614 case Stmt::ArraySubscriptExprClass: {
6615 // Array subscripts are potential references to data on the stack. We
6616 // retrieve the DeclRefExpr* for the array variable if it indeed
6617 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006618 const auto *ASE = cast<ArraySubscriptExpr>(E);
6619 if (ASE->isTypeDependent())
6620 return nullptr;
6621 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006622 }
Mike Stump11289f42009-09-09 15:08:12 +00006623
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006624 case Stmt::OMPArraySectionExprClass: {
6625 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6626 ParentDecl);
6627 }
Mike Stump11289f42009-09-09 15:08:12 +00006628
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006629 case Stmt::ConditionalOperatorClass: {
6630 // For conditional operators we need to see if either the LHS or RHS are
6631 // non-NULL Expr's. If one is non-NULL, we return it.
6632 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006633
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006634 // Handle the GNU extension for missing LHS.
6635 if (const Expr *LHSExpr = C->getLHS()) {
6636 // In C++, we can have a throw-expression, which has 'void' type.
6637 if (!LHSExpr->getType()->isVoidType())
6638 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6639 return LHS;
6640 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006641
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006642 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006643 if (C->getRHS()->getType()->isVoidType())
6644 return nullptr;
6645
6646 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006647 }
6648
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006649 // Accesses to members are potential references to data on the stack.
6650 case Stmt::MemberExprClass: {
6651 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006652
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006653 // Check for indirect access. We only want direct field accesses.
6654 if (M->isArrow())
6655 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006656
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006657 // Check whether the member type is itself a reference, in which case
6658 // we're not going to refer to the member, but to what the member refers
6659 // to.
6660 if (M->getMemberDecl()->getType()->isReferenceType())
6661 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006662
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006663 return EvalVal(M->getBase(), refVars, ParentDecl);
6664 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006665
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006666 case Stmt::MaterializeTemporaryExprClass:
6667 if (const Expr *Result =
6668 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6669 refVars, ParentDecl))
6670 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006671 return E;
6672
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006673 default:
6674 // Check that we don't return or take the address of a reference to a
6675 // temporary. This is only useful in C++.
6676 if (!E->isTypeDependent() && E->isRValue())
6677 return E;
6678
6679 // Everything else: we simply don't reason about them.
6680 return nullptr;
6681 }
6682 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006683}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006684
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006685void
6686Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6687 SourceLocation ReturnLoc,
6688 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006689 const AttrVec *Attrs,
6690 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006691 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6692
6693 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006694 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6695 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006696 CheckNonNullExpr(*this, RetValExp))
6697 Diag(ReturnLoc, diag::warn_null_ret)
6698 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006699
6700 // C++11 [basic.stc.dynamic.allocation]p4:
6701 // If an allocation function declared with a non-throwing
6702 // exception-specification fails to allocate storage, it shall return
6703 // a null pointer. Any other allocation function that fails to allocate
6704 // storage shall indicate failure only by throwing an exception [...]
6705 if (FD) {
6706 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6707 if (Op == OO_New || Op == OO_Array_New) {
6708 const FunctionProtoType *Proto
6709 = FD->getType()->castAs<FunctionProtoType>();
6710 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6711 CheckNonNullExpr(*this, RetValExp))
6712 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6713 << FD << getLangOpts().CPlusPlus11;
6714 }
6715 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006716}
6717
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006718//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6719
6720/// Check for comparisons of floating point operands using != and ==.
6721/// Issue a warning if these are no self-comparisons, as they are not likely
6722/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006723void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006724 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6725 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006726
6727 // Special case: check for x == x (which is OK).
6728 // Do not emit warnings for such cases.
6729 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6730 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6731 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006732 return;
Mike Stump11289f42009-09-09 15:08:12 +00006733
Ted Kremenekeda40e22007-11-29 00:59:04 +00006734 // Special case: check for comparisons against literals that can be exactly
6735 // represented by APFloat. In such cases, do not emit a warning. This
6736 // is a heuristic: often comparison against such literals are used to
6737 // detect if a value in a variable has not changed. This clearly can
6738 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006739 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6740 if (FLL->isExact())
6741 return;
6742 } else
6743 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6744 if (FLR->isExact())
6745 return;
Mike Stump11289f42009-09-09 15:08:12 +00006746
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006747 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006748 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006749 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006750 return;
Mike Stump11289f42009-09-09 15:08:12 +00006751
David Blaikie1f4ff152012-07-16 20:47:22 +00006752 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006753 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006754 return;
Mike Stump11289f42009-09-09 15:08:12 +00006755
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006756 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006757 Diag(Loc, diag::warn_floatingpoint_eq)
6758 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006759}
John McCallca01b222010-01-04 23:21:16 +00006760
John McCall70aa5392010-01-06 05:24:50 +00006761//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6762//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006763
John McCall70aa5392010-01-06 05:24:50 +00006764namespace {
John McCallca01b222010-01-04 23:21:16 +00006765
John McCall70aa5392010-01-06 05:24:50 +00006766/// Structure recording the 'active' range of an integer-valued
6767/// expression.
6768struct IntRange {
6769 /// The number of bits active in the int.
6770 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006771
John McCall70aa5392010-01-06 05:24:50 +00006772 /// True if the int is known not to have negative values.
6773 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006774
John McCall70aa5392010-01-06 05:24:50 +00006775 IntRange(unsigned Width, bool NonNegative)
6776 : Width(Width), NonNegative(NonNegative)
6777 {}
John McCallca01b222010-01-04 23:21:16 +00006778
John McCall817d4af2010-11-10 23:38:19 +00006779 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006780 static IntRange forBoolType() {
6781 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006782 }
6783
John McCall817d4af2010-11-10 23:38:19 +00006784 /// Returns the range of an opaque value of the given integral type.
6785 static IntRange forValueOfType(ASTContext &C, QualType T) {
6786 return forValueOfCanonicalType(C,
6787 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006788 }
6789
John McCall817d4af2010-11-10 23:38:19 +00006790 /// Returns the range of an opaque value of a canonical integral type.
6791 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006792 assert(T->isCanonicalUnqualified());
6793
6794 if (const VectorType *VT = dyn_cast<VectorType>(T))
6795 T = VT->getElementType().getTypePtr();
6796 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6797 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006798 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6799 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006800
David Majnemer6a426652013-06-07 22:07:20 +00006801 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006802 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006803 EnumDecl *Enum = ET->getDecl();
6804 if (!Enum->isCompleteDefinition())
6805 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006806
David Majnemer6a426652013-06-07 22:07:20 +00006807 unsigned NumPositive = Enum->getNumPositiveBits();
6808 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006809
David Majnemer6a426652013-06-07 22:07:20 +00006810 if (NumNegative == 0)
6811 return IntRange(NumPositive, true/*NonNegative*/);
6812 else
6813 return IntRange(std::max(NumPositive + 1, NumNegative),
6814 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006815 }
John McCall70aa5392010-01-06 05:24:50 +00006816
6817 const BuiltinType *BT = cast<BuiltinType>(T);
6818 assert(BT->isInteger());
6819
6820 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6821 }
6822
John McCall817d4af2010-11-10 23:38:19 +00006823 /// Returns the "target" range of a canonical integral type, i.e.
6824 /// the range of values expressible in the type.
6825 ///
6826 /// This matches forValueOfCanonicalType except that enums have the
6827 /// full range of their type, not the range of their enumerators.
6828 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6829 assert(T->isCanonicalUnqualified());
6830
6831 if (const VectorType *VT = dyn_cast<VectorType>(T))
6832 T = VT->getElementType().getTypePtr();
6833 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6834 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006835 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6836 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006837 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006838 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006839
6840 const BuiltinType *BT = cast<BuiltinType>(T);
6841 assert(BT->isInteger());
6842
6843 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6844 }
6845
6846 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006847 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006848 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006849 L.NonNegative && R.NonNegative);
6850 }
6851
John McCall817d4af2010-11-10 23:38:19 +00006852 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006853 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006854 return IntRange(std::min(L.Width, R.Width),
6855 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006856 }
6857};
6858
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006859IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006860 if (value.isSigned() && value.isNegative())
6861 return IntRange(value.getMinSignedBits(), false);
6862
6863 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006864 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006865
6866 // isNonNegative() just checks the sign bit without considering
6867 // signedness.
6868 return IntRange(value.getActiveBits(), true);
6869}
6870
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006871IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6872 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006873 if (result.isInt())
6874 return GetValueRange(C, result.getInt(), MaxWidth);
6875
6876 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006877 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6878 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6879 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6880 R = IntRange::join(R, El);
6881 }
John McCall70aa5392010-01-06 05:24:50 +00006882 return R;
6883 }
6884
6885 if (result.isComplexInt()) {
6886 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6887 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6888 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006889 }
6890
6891 // This can happen with lossless casts to intptr_t of "based" lvalues.
6892 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006893 // FIXME: The only reason we need to pass the type in here is to get
6894 // the sign right on this one case. It would be nice if APValue
6895 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006896 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006897 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006898}
John McCall70aa5392010-01-06 05:24:50 +00006899
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006900QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006901 QualType Ty = E->getType();
6902 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6903 Ty = AtomicRHS->getValueType();
6904 return Ty;
6905}
6906
John McCall70aa5392010-01-06 05:24:50 +00006907/// Pseudo-evaluate the given integer expression, estimating the
6908/// range of values it might take.
6909///
6910/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006911IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006912 E = E->IgnoreParens();
6913
6914 // Try a full evaluation first.
6915 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006916 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006917 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006918
6919 // I think we only want to look through implicit casts here; if the
6920 // user has an explicit widening cast, we should treat the value as
6921 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006922 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006923 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006924 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6925
Eli Friedmane6d33952013-07-08 20:20:06 +00006926 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006927
George Burgess IVdf1ed002016-01-13 01:52:39 +00006928 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6929 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00006930
John McCall70aa5392010-01-06 05:24:50 +00006931 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006932 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006933 return OutputTypeRange;
6934
6935 IntRange SubRange
6936 = GetExprRange(C, CE->getSubExpr(),
6937 std::min(MaxWidth, OutputTypeRange.Width));
6938
6939 // Bail out if the subexpr's range is as wide as the cast type.
6940 if (SubRange.Width >= OutputTypeRange.Width)
6941 return OutputTypeRange;
6942
6943 // Otherwise, we take the smaller width, and we're non-negative if
6944 // either the output type or the subexpr is.
6945 return IntRange(SubRange.Width,
6946 SubRange.NonNegative || OutputTypeRange.NonNegative);
6947 }
6948
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006949 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006950 // If we can fold the condition, just take that operand.
6951 bool CondResult;
6952 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6953 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6954 : CO->getFalseExpr(),
6955 MaxWidth);
6956
6957 // Otherwise, conservatively merge.
6958 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6959 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6960 return IntRange::join(L, R);
6961 }
6962
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006963 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006964 switch (BO->getOpcode()) {
6965
6966 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006967 case BO_LAnd:
6968 case BO_LOr:
6969 case BO_LT:
6970 case BO_GT:
6971 case BO_LE:
6972 case BO_GE:
6973 case BO_EQ:
6974 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006975 return IntRange::forBoolType();
6976
John McCallc3688382011-07-13 06:35:24 +00006977 // The type of the assignments is the type of the LHS, so the RHS
6978 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006979 case BO_MulAssign:
6980 case BO_DivAssign:
6981 case BO_RemAssign:
6982 case BO_AddAssign:
6983 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006984 case BO_XorAssign:
6985 case BO_OrAssign:
6986 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006987 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006988
John McCallc3688382011-07-13 06:35:24 +00006989 // Simple assignments just pass through the RHS, which will have
6990 // been coerced to the LHS type.
6991 case BO_Assign:
6992 // TODO: bitfields?
6993 return GetExprRange(C, BO->getRHS(), MaxWidth);
6994
John McCall70aa5392010-01-06 05:24:50 +00006995 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006996 case BO_PtrMemD:
6997 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006998 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006999
John McCall2ce81ad2010-01-06 22:07:33 +00007000 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00007001 case BO_And:
7002 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00007003 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7004 GetExprRange(C, BO->getRHS(), MaxWidth));
7005
John McCall70aa5392010-01-06 05:24:50 +00007006 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00007007 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007008 // ...except that we want to treat '1 << (blah)' as logically
7009 // positive. It's an important idiom.
7010 if (IntegerLiteral *I
7011 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7012 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007013 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007014 return IntRange(R.Width, /*NonNegative*/ true);
7015 }
7016 }
7017 // fallthrough
7018
John McCalle3027922010-08-25 11:45:40 +00007019 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007020 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007021
John McCall2ce81ad2010-01-06 22:07:33 +00007022 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007023 case BO_Shr:
7024 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007025 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7026
7027 // If the shift amount is a positive constant, drop the width by
7028 // that much.
7029 llvm::APSInt shift;
7030 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7031 shift.isNonNegative()) {
7032 unsigned zext = shift.getZExtValue();
7033 if (zext >= L.Width)
7034 L.Width = (L.NonNegative ? 0 : 1);
7035 else
7036 L.Width -= zext;
7037 }
7038
7039 return L;
7040 }
7041
7042 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00007043 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00007044 return GetExprRange(C, BO->getRHS(), MaxWidth);
7045
John McCall2ce81ad2010-01-06 22:07:33 +00007046 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00007047 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00007048 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00007049 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007050 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007051
John McCall51431812011-07-14 22:39:48 +00007052 // The width of a division result is mostly determined by the size
7053 // of the LHS.
7054 case BO_Div: {
7055 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007056 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007057 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7058
7059 // If the divisor is constant, use that.
7060 llvm::APSInt divisor;
7061 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7062 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7063 if (log2 >= L.Width)
7064 L.Width = (L.NonNegative ? 0 : 1);
7065 else
7066 L.Width = std::min(L.Width - log2, MaxWidth);
7067 return L;
7068 }
7069
7070 // Otherwise, just use the LHS's width.
7071 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7072 return IntRange(L.Width, L.NonNegative && R.NonNegative);
7073 }
7074
7075 // The result of a remainder can't be larger than the result of
7076 // either side.
7077 case BO_Rem: {
7078 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007079 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007080 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7081 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7082
7083 IntRange meet = IntRange::meet(L, R);
7084 meet.Width = std::min(meet.Width, MaxWidth);
7085 return meet;
7086 }
7087
7088 // The default behavior is okay for these.
7089 case BO_Mul:
7090 case BO_Add:
7091 case BO_Xor:
7092 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00007093 break;
7094 }
7095
John McCall51431812011-07-14 22:39:48 +00007096 // The default case is to treat the operation as if it were closed
7097 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00007098 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7099 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7100 return IntRange::join(L, R);
7101 }
7102
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007103 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007104 switch (UO->getOpcode()) {
7105 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00007106 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00007107 return IntRange::forBoolType();
7108
7109 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007110 case UO_Deref:
7111 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00007112 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007113
7114 default:
7115 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7116 }
7117 }
7118
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007119 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00007120 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7121
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007122 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00007123 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00007124 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00007125
Eli Friedmane6d33952013-07-08 20:20:06 +00007126 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007127}
John McCall263a48b2010-01-04 23:31:57 +00007128
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007129IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007130 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00007131}
7132
John McCall263a48b2010-01-04 23:31:57 +00007133/// Checks whether the given value, which currently has the given
7134/// source semantics, has the same value when coerced through the
7135/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007136bool IsSameFloatAfterCast(const llvm::APFloat &value,
7137 const llvm::fltSemantics &Src,
7138 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007139 llvm::APFloat truncated = value;
7140
7141 bool ignored;
7142 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7143 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7144
7145 return truncated.bitwiseIsEqual(value);
7146}
7147
7148/// Checks whether the given value, which currently has the given
7149/// source semantics, has the same value when coerced through the
7150/// target semantics.
7151///
7152/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007153bool IsSameFloatAfterCast(const APValue &value,
7154 const llvm::fltSemantics &Src,
7155 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007156 if (value.isFloat())
7157 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7158
7159 if (value.isVector()) {
7160 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7161 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7162 return false;
7163 return true;
7164 }
7165
7166 assert(value.isComplexFloat());
7167 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7168 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7169}
7170
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007171void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007172
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007173bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00007174 // Suppress cases where we are comparing against an enum constant.
7175 if (const DeclRefExpr *DR =
7176 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7177 if (isa<EnumConstantDecl>(DR->getDecl()))
7178 return false;
7179
7180 // Suppress cases where the '0' value is expanded from a macro.
7181 if (E->getLocStart().isMacroID())
7182 return false;
7183
John McCallcc7e5bf2010-05-06 08:58:33 +00007184 llvm::APSInt Value;
7185 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7186}
7187
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007188bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00007189 // Strip off implicit integral promotions.
7190 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007191 if (ICE->getCastKind() != CK_IntegralCast &&
7192 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00007193 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007194 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00007195 }
7196
7197 return E->getType()->isEnumeralType();
7198}
7199
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007200void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00007201 // Disable warning in template instantiations.
7202 if (!S.ActiveTemplateInstantiations.empty())
7203 return;
7204
John McCalle3027922010-08-25 11:45:40 +00007205 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00007206 if (E->isValueDependent())
7207 return;
7208
John McCalle3027922010-08-25 11:45:40 +00007209 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007210 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007211 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007212 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007213 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007214 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007215 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007216 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007217 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007218 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007219 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007220 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007221 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007222 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007223 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007224 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7225 }
7226}
7227
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007228void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
7229 Expr *Constant, Expr *Other,
7230 llvm::APSInt Value,
7231 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00007232 // Disable warning in template instantiations.
7233 if (!S.ActiveTemplateInstantiations.empty())
7234 return;
7235
Richard Trieu0f097742014-04-04 04:13:47 +00007236 // TODO: Investigate using GetExprRange() to get tighter bounds
7237 // on the bit ranges.
7238 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00007239 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00007240 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00007241 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7242 unsigned OtherWidth = OtherRange.Width;
7243
7244 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7245
Richard Trieu560910c2012-11-14 22:50:24 +00007246 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00007247 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00007248 return;
7249
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007250 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00007251 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007252
Richard Trieu0f097742014-04-04 04:13:47 +00007253 // Used for diagnostic printout.
7254 enum {
7255 LiteralConstant = 0,
7256 CXXBoolLiteralTrue,
7257 CXXBoolLiteralFalse
7258 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007259
Richard Trieu0f097742014-04-04 04:13:47 +00007260 if (!OtherIsBooleanType) {
7261 QualType ConstantT = Constant->getType();
7262 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007263
Richard Trieu0f097742014-04-04 04:13:47 +00007264 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7265 return;
7266 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7267 "comparison with non-integer type");
7268
7269 bool ConstantSigned = ConstantT->isSignedIntegerType();
7270 bool CommonSigned = CommonT->isSignedIntegerType();
7271
7272 bool EqualityOnly = false;
7273
7274 if (CommonSigned) {
7275 // The common type is signed, therefore no signed to unsigned conversion.
7276 if (!OtherRange.NonNegative) {
7277 // Check that the constant is representable in type OtherT.
7278 if (ConstantSigned) {
7279 if (OtherWidth >= Value.getMinSignedBits())
7280 return;
7281 } else { // !ConstantSigned
7282 if (OtherWidth >= Value.getActiveBits() + 1)
7283 return;
7284 }
7285 } else { // !OtherSigned
7286 // Check that the constant is representable in type OtherT.
7287 // Negative values are out of range.
7288 if (ConstantSigned) {
7289 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7290 return;
7291 } else { // !ConstantSigned
7292 if (OtherWidth >= Value.getActiveBits())
7293 return;
7294 }
Richard Trieu560910c2012-11-14 22:50:24 +00007295 }
Richard Trieu0f097742014-04-04 04:13:47 +00007296 } else { // !CommonSigned
7297 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007298 if (OtherWidth >= Value.getActiveBits())
7299 return;
Craig Toppercf360162014-06-18 05:13:11 +00007300 } else { // OtherSigned
7301 assert(!ConstantSigned &&
7302 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007303 // Check to see if the constant is representable in OtherT.
7304 if (OtherWidth > Value.getActiveBits())
7305 return;
7306 // Check to see if the constant is equivalent to a negative value
7307 // cast to CommonT.
7308 if (S.Context.getIntWidth(ConstantT) ==
7309 S.Context.getIntWidth(CommonT) &&
7310 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7311 return;
7312 // The constant value rests between values that OtherT can represent
7313 // after conversion. Relational comparison still works, but equality
7314 // comparisons will be tautological.
7315 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007316 }
7317 }
Richard Trieu0f097742014-04-04 04:13:47 +00007318
7319 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7320
7321 if (op == BO_EQ || op == BO_NE) {
7322 IsTrue = op == BO_NE;
7323 } else if (EqualityOnly) {
7324 return;
7325 } else if (RhsConstant) {
7326 if (op == BO_GT || op == BO_GE)
7327 IsTrue = !PositiveConstant;
7328 else // op == BO_LT || op == BO_LE
7329 IsTrue = PositiveConstant;
7330 } else {
7331 if (op == BO_LT || op == BO_LE)
7332 IsTrue = !PositiveConstant;
7333 else // op == BO_GT || op == BO_GE
7334 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007335 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007336 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007337 // Other isKnownToHaveBooleanValue
7338 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7339 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7340 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7341
7342 static const struct LinkedConditions {
7343 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7344 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7345 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7346 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7347 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7348 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7349
7350 } TruthTable = {
7351 // Constant on LHS. | Constant on RHS. |
7352 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7353 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7354 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7355 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7356 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7357 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7358 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7359 };
7360
7361 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7362
7363 enum ConstantValue ConstVal = Zero;
7364 if (Value.isUnsigned() || Value.isNonNegative()) {
7365 if (Value == 0) {
7366 LiteralOrBoolConstant =
7367 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7368 ConstVal = Zero;
7369 } else if (Value == 1) {
7370 LiteralOrBoolConstant =
7371 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7372 ConstVal = One;
7373 } else {
7374 LiteralOrBoolConstant = LiteralConstant;
7375 ConstVal = GT_One;
7376 }
7377 } else {
7378 ConstVal = LT_Zero;
7379 }
7380
7381 CompareBoolWithConstantResult CmpRes;
7382
7383 switch (op) {
7384 case BO_LT:
7385 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7386 break;
7387 case BO_GT:
7388 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7389 break;
7390 case BO_LE:
7391 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7392 break;
7393 case BO_GE:
7394 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7395 break;
7396 case BO_EQ:
7397 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7398 break;
7399 case BO_NE:
7400 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7401 break;
7402 default:
7403 CmpRes = Unkwn;
7404 break;
7405 }
7406
7407 if (CmpRes == AFals) {
7408 IsTrue = false;
7409 } else if (CmpRes == ATrue) {
7410 IsTrue = true;
7411 } else {
7412 return;
7413 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007414 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007415
7416 // If this is a comparison to an enum constant, include that
7417 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007418 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007419 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7420 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7421
7422 SmallString<64> PrettySourceValue;
7423 llvm::raw_svector_ostream OS(PrettySourceValue);
7424 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007425 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007426 else
7427 OS << Value;
7428
Richard Trieu0f097742014-04-04 04:13:47 +00007429 S.DiagRuntimeBehavior(
7430 E->getOperatorLoc(), E,
7431 S.PDiag(diag::warn_out_of_range_compare)
7432 << OS.str() << LiteralOrBoolConstant
7433 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7434 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007435}
7436
John McCallcc7e5bf2010-05-06 08:58:33 +00007437/// Analyze the operands of the given comparison. Implements the
7438/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007439void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007440 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7441 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007442}
John McCall263a48b2010-01-04 23:31:57 +00007443
John McCallca01b222010-01-04 23:21:16 +00007444/// \brief Implements -Wsign-compare.
7445///
Richard Trieu82402a02011-09-15 21:56:47 +00007446/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007447void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007448 // The type the comparison is being performed in.
7449 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007450
7451 // Only analyze comparison operators where both sides have been converted to
7452 // the same type.
7453 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7454 return AnalyzeImpConvsInComparison(S, E);
7455
7456 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007457 if (E->isValueDependent())
7458 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007459
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007460 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7461 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007462
7463 bool IsComparisonConstant = false;
7464
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007465 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007466 // of 'true' or 'false'.
7467 if (T->isIntegralType(S.Context)) {
7468 llvm::APSInt RHSValue;
7469 bool IsRHSIntegralLiteral =
7470 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7471 llvm::APSInt LHSValue;
7472 bool IsLHSIntegralLiteral =
7473 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7474 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7475 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7476 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7477 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7478 else
7479 IsComparisonConstant =
7480 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007481 } else if (!T->hasUnsignedIntegerRepresentation())
7482 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007483
John McCallcc7e5bf2010-05-06 08:58:33 +00007484 // We don't do anything special if this isn't an unsigned integral
7485 // comparison: we're only interested in integral comparisons, and
7486 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007487 //
7488 // We also don't care about value-dependent expressions or expressions
7489 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007490 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007491 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007492
John McCallcc7e5bf2010-05-06 08:58:33 +00007493 // Check to see if one of the (unmodified) operands is of different
7494 // signedness.
7495 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007496 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7497 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007498 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007499 signedOperand = LHS;
7500 unsignedOperand = RHS;
7501 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7502 signedOperand = RHS;
7503 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007504 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007505 CheckTrivialUnsignedComparison(S, E);
7506 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007507 }
7508
John McCallcc7e5bf2010-05-06 08:58:33 +00007509 // Otherwise, calculate the effective range of the signed operand.
7510 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007511
John McCallcc7e5bf2010-05-06 08:58:33 +00007512 // Go ahead and analyze implicit conversions in the operands. Note
7513 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007514 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7515 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007516
John McCallcc7e5bf2010-05-06 08:58:33 +00007517 // If the signed range is non-negative, -Wsign-compare won't fire,
7518 // but we should still check for comparisons which are always true
7519 // or false.
7520 if (signedRange.NonNegative)
7521 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007522
7523 // For (in)equality comparisons, if the unsigned operand is a
7524 // constant which cannot collide with a overflowed signed operand,
7525 // then reinterpreting the signed operand as unsigned will not
7526 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007527 if (E->isEqualityOp()) {
7528 unsigned comparisonWidth = S.Context.getIntWidth(T);
7529 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007530
John McCallcc7e5bf2010-05-06 08:58:33 +00007531 // We should never be unable to prove that the unsigned operand is
7532 // non-negative.
7533 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7534
7535 if (unsignedRange.Width < comparisonWidth)
7536 return;
7537 }
7538
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007539 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7540 S.PDiag(diag::warn_mixed_sign_comparison)
7541 << LHS->getType() << RHS->getType()
7542 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007543}
7544
John McCall1f425642010-11-11 03:21:53 +00007545/// Analyzes an attempt to assign the given value to a bitfield.
7546///
7547/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007548bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7549 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007550 assert(Bitfield->isBitField());
7551 if (Bitfield->isInvalidDecl())
7552 return false;
7553
John McCalldeebbcf2010-11-11 05:33:51 +00007554 // White-list bool bitfields.
7555 if (Bitfield->getType()->isBooleanType())
7556 return false;
7557
Douglas Gregor789adec2011-02-04 13:09:01 +00007558 // Ignore value- or type-dependent expressions.
7559 if (Bitfield->getBitWidth()->isValueDependent() ||
7560 Bitfield->getBitWidth()->isTypeDependent() ||
7561 Init->isValueDependent() ||
7562 Init->isTypeDependent())
7563 return false;
7564
John McCall1f425642010-11-11 03:21:53 +00007565 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7566
Richard Smith5fab0c92011-12-28 19:48:30 +00007567 llvm::APSInt Value;
7568 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007569 return false;
7570
John McCall1f425642010-11-11 03:21:53 +00007571 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007572 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007573
7574 if (OriginalWidth <= FieldWidth)
7575 return false;
7576
Eli Friedmanc267a322012-01-26 23:11:39 +00007577 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007578 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007579 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007580
Eli Friedmanc267a322012-01-26 23:11:39 +00007581 // Check whether the stored value is equal to the original value.
7582 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007583 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007584 return false;
7585
Eli Friedmanc267a322012-01-26 23:11:39 +00007586 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007587 // therefore don't strictly fit into a signed bitfield of width 1.
7588 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007589 return false;
7590
John McCall1f425642010-11-11 03:21:53 +00007591 std::string PrettyValue = Value.toString(10);
7592 std::string PrettyTrunc = TruncatedValue.toString(10);
7593
7594 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7595 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7596 << Init->getSourceRange();
7597
7598 return true;
7599}
7600
John McCalld2a53122010-11-09 23:24:47 +00007601/// Analyze the given simple or compound assignment for warning-worthy
7602/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007603void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007604 // Just recurse on the LHS.
7605 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7606
7607 // We want to recurse on the RHS as normal unless we're assigning to
7608 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007609 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007610 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007611 E->getOperatorLoc())) {
7612 // Recurse, ignoring any implicit conversions on the RHS.
7613 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7614 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007615 }
7616 }
7617
7618 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7619}
7620
John McCall263a48b2010-01-04 23:31:57 +00007621/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007622void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7623 SourceLocation CContext, unsigned diag,
7624 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007625 if (pruneControlFlow) {
7626 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7627 S.PDiag(diag)
7628 << SourceType << T << E->getSourceRange()
7629 << SourceRange(CContext));
7630 return;
7631 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007632 S.Diag(E->getExprLoc(), diag)
7633 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7634}
7635
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007636/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007637void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7638 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007639 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007640}
7641
Richard Trieube234c32016-04-21 21:04:55 +00007642
7643/// Diagnose an implicit cast from a floating point value to an integer value.
7644void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
7645
7646 SourceLocation CContext) {
7647 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
7648 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
7649
7650 Expr *InnerE = E->IgnoreParenImpCasts();
7651 // We also want to warn on, e.g., "int i = -1.234"
7652 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7653 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7654 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7655
7656 const bool IsLiteral =
7657 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
7658
7659 llvm::APFloat Value(0.0);
7660 bool IsConstant =
7661 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
7662 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00007663 return DiagnoseImpCast(S, E, T, CContext,
7664 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00007665 }
7666
Chandler Carruth016ef402011-04-10 08:36:24 +00007667 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00007668
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007669 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7670 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00007671 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7672 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00007673 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00007674 if (IsLiteral) return;
7675 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7676 PruneWarnings);
7677 }
7678
7679 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00007680 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00007681 // Warn on floating point literal to integer.
7682 DiagID = diag::warn_impcast_literal_float_to_integer;
7683 } else if (IntegerValue == 0) {
7684 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
7685 return DiagnoseImpCast(S, E, T, CContext,
7686 diag::warn_impcast_float_integer, PruneWarnings);
7687 }
7688 // Warn on non-zero to zero conversion.
7689 DiagID = diag::warn_impcast_float_to_integer_zero;
7690 } else {
7691 if (IntegerValue.isUnsigned()) {
7692 if (!IntegerValue.isMaxValue()) {
7693 return DiagnoseImpCast(S, E, T, CContext,
7694 diag::warn_impcast_float_integer, PruneWarnings);
7695 }
7696 } else { // IntegerValue.isSigned()
7697 if (!IntegerValue.isMaxSignedValue() &&
7698 !IntegerValue.isMinSignedValue()) {
7699 return DiagnoseImpCast(S, E, T, CContext,
7700 diag::warn_impcast_float_integer, PruneWarnings);
7701 }
7702 }
7703 // Warn on evaluatable floating point expression to integer conversion.
7704 DiagID = diag::warn_impcast_float_to_integer;
7705 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007706
Eli Friedman07185912013-08-29 23:44:43 +00007707 // FIXME: Force the precision of the source value down so we don't print
7708 // digits which are usually useless (we don't really care here if we
7709 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7710 // would automatically print the shortest representation, but it's a bit
7711 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007712 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007713 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7714 precision = (precision * 59 + 195) / 196;
7715 Value.toString(PrettySourceValue, precision);
7716
David Blaikie9b88cc02012-05-15 17:18:27 +00007717 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00007718 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007719 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007720 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007721 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007722
Richard Trieube234c32016-04-21 21:04:55 +00007723 if (PruneWarnings) {
7724 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7725 S.PDiag(DiagID)
7726 << E->getType() << T.getUnqualifiedType()
7727 << PrettySourceValue << PrettyTargetValue
7728 << E->getSourceRange() << SourceRange(CContext));
7729 } else {
7730 S.Diag(E->getExprLoc(), DiagID)
7731 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
7732 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
7733 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007734}
7735
John McCall18a2c2c2010-11-09 22:22:12 +00007736std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7737 if (!Range.Width) return "0";
7738
7739 llvm::APSInt ValueInRange = Value;
7740 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007741 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007742 return ValueInRange.toString(10);
7743}
7744
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007745bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007746 if (!isa<ImplicitCastExpr>(Ex))
7747 return false;
7748
7749 Expr *InnerE = Ex->IgnoreParenImpCasts();
7750 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7751 const Type *Source =
7752 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7753 if (Target->isDependentType())
7754 return false;
7755
7756 const BuiltinType *FloatCandidateBT =
7757 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7758 const Type *BoolCandidateType = ToBool ? Target : Source;
7759
7760 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7761 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7762}
7763
7764void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7765 SourceLocation CC) {
7766 unsigned NumArgs = TheCall->getNumArgs();
7767 for (unsigned i = 0; i < NumArgs; ++i) {
7768 Expr *CurrA = TheCall->getArg(i);
7769 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7770 continue;
7771
7772 bool IsSwapped = ((i > 0) &&
7773 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7774 IsSwapped |= ((i < (NumArgs - 1)) &&
7775 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7776 if (IsSwapped) {
7777 // Warn on this floating-point to bool conversion.
7778 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7779 CurrA->getType(), CC,
7780 diag::warn_impcast_floating_point_to_bool);
7781 }
7782 }
7783}
7784
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007785void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007786 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7787 E->getExprLoc()))
7788 return;
7789
Richard Trieu09d6b802016-01-08 23:35:06 +00007790 // Don't warn on functions which have return type nullptr_t.
7791 if (isa<CallExpr>(E))
7792 return;
7793
Richard Trieu5b993502014-10-15 03:42:06 +00007794 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7795 const Expr::NullPointerConstantKind NullKind =
7796 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7797 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7798 return;
7799
7800 // Return if target type is a safe conversion.
7801 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7802 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7803 return;
7804
7805 SourceLocation Loc = E->getSourceRange().getBegin();
7806
Richard Trieu0a5e1662016-02-13 00:58:53 +00007807 // Venture through the macro stacks to get to the source of macro arguments.
7808 // The new location is a better location than the complete location that was
7809 // passed in.
7810 while (S.SourceMgr.isMacroArgExpansion(Loc))
7811 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
7812
7813 while (S.SourceMgr.isMacroArgExpansion(CC))
7814 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
7815
Richard Trieu5b993502014-10-15 03:42:06 +00007816 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00007817 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
7818 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7819 Loc, S.SourceMgr, S.getLangOpts());
7820 if (MacroName == "NULL")
7821 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00007822 }
7823
7824 // Only warn if the null and context location are in the same macro expansion.
7825 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7826 return;
7827
7828 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7829 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7830 << FixItHint::CreateReplacement(Loc,
7831 S.getFixItZeroLiteralForType(T, Loc));
7832}
7833
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007834void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7835 ObjCArrayLiteral *ArrayLiteral);
7836void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7837 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00007838
7839/// Check a single element within a collection literal against the
7840/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007841void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7842 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007843 // Skip a bitcast to 'id' or qualified 'id'.
7844 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7845 if (ICE->getCastKind() == CK_BitCast &&
7846 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7847 Element = ICE->getSubExpr();
7848 }
7849
7850 QualType ElementType = Element->getType();
7851 ExprResult ElementResult(Element);
7852 if (ElementType->getAs<ObjCObjectPointerType>() &&
7853 S.CheckSingleAssignmentConstraints(TargetElementType,
7854 ElementResult,
7855 false, false)
7856 != Sema::Compatible) {
7857 S.Diag(Element->getLocStart(),
7858 diag::warn_objc_collection_literal_element)
7859 << ElementType << ElementKind << TargetElementType
7860 << Element->getSourceRange();
7861 }
7862
7863 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7864 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7865 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7866 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7867}
7868
7869/// Check an Objective-C array literal being converted to the given
7870/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007871void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7872 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007873 if (!S.NSArrayDecl)
7874 return;
7875
7876 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7877 if (!TargetObjCPtr)
7878 return;
7879
7880 if (TargetObjCPtr->isUnspecialized() ||
7881 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7882 != S.NSArrayDecl->getCanonicalDecl())
7883 return;
7884
7885 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7886 if (TypeArgs.size() != 1)
7887 return;
7888
7889 QualType TargetElementType = TypeArgs[0];
7890 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7891 checkObjCCollectionLiteralElement(S, TargetElementType,
7892 ArrayLiteral->getElement(I),
7893 0);
7894 }
7895}
7896
7897/// Check an Objective-C dictionary literal being converted to the given
7898/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007899void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7900 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007901 if (!S.NSDictionaryDecl)
7902 return;
7903
7904 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7905 if (!TargetObjCPtr)
7906 return;
7907
7908 if (TargetObjCPtr->isUnspecialized() ||
7909 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7910 != S.NSDictionaryDecl->getCanonicalDecl())
7911 return;
7912
7913 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7914 if (TypeArgs.size() != 2)
7915 return;
7916
7917 QualType TargetKeyType = TypeArgs[0];
7918 QualType TargetObjectType = TypeArgs[1];
7919 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7920 auto Element = DictionaryLiteral->getKeyValueElement(I);
7921 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7922 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7923 }
7924}
7925
Richard Trieufc404c72016-02-05 23:02:38 +00007926// Helper function to filter out cases for constant width constant conversion.
7927// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007928bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7929 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00007930 // If initializing from a constant, and the constant starts with '0',
7931 // then it is a binary, octal, or hexadecimal. Allow these constants
7932 // to fill all the bits, even if there is a sign change.
7933 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7934 const char FirstLiteralCharacter =
7935 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7936 if (FirstLiteralCharacter == '0')
7937 return false;
7938 }
7939
7940 // If the CC location points to a '{', and the type is char, then assume
7941 // assume it is an array initialization.
7942 if (CC.isValid() && T->isCharType()) {
7943 const char FirstContextCharacter =
7944 S.getSourceManager().getCharacterData(CC)[0];
7945 if (FirstContextCharacter == '{')
7946 return false;
7947 }
7948
7949 return true;
7950}
7951
John McCallcc7e5bf2010-05-06 08:58:33 +00007952void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007953 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007954 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007955
John McCallcc7e5bf2010-05-06 08:58:33 +00007956 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7957 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7958 if (Source == Target) return;
7959 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007960
Chandler Carruthc22845a2011-07-26 05:40:03 +00007961 // If the conversion context location is invalid don't complain. We also
7962 // don't want to emit a warning if the issue occurs from the expansion of
7963 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7964 // delay this check as long as possible. Once we detect we are in that
7965 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007966 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007967 return;
7968
Richard Trieu021baa32011-09-23 20:10:00 +00007969 // Diagnose implicit casts to bool.
7970 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7971 if (isa<StringLiteral>(E))
7972 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007973 // and expressions, for instance, assert(0 && "error here"), are
7974 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007975 return DiagnoseImpCast(S, E, T, CC,
7976 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007977 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7978 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7979 // This covers the literal expressions that evaluate to Objective-C
7980 // objects.
7981 return DiagnoseImpCast(S, E, T, CC,
7982 diag::warn_impcast_objective_c_literal_to_bool);
7983 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007984 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7985 // Warn on pointer to bool conversion that is always true.
7986 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7987 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007988 }
Richard Trieu021baa32011-09-23 20:10:00 +00007989 }
John McCall263a48b2010-01-04 23:31:57 +00007990
Douglas Gregor5054cb02015-07-07 03:58:22 +00007991 // Check implicit casts from Objective-C collection literals to specialized
7992 // collection types, e.g., NSArray<NSString *> *.
7993 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7994 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7995 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7996 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7997
John McCall263a48b2010-01-04 23:31:57 +00007998 // Strip vector types.
7999 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008000 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008001 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008002 return;
John McCallacf0ee52010-10-08 02:01:28 +00008003 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008004 }
Chris Lattneree7286f2011-06-14 04:51:15 +00008005
8006 // If the vector cast is cast between two vectors of the same size, it is
8007 // a bitcast, not a conversion.
8008 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8009 return;
John McCall263a48b2010-01-04 23:31:57 +00008010
8011 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8012 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8013 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00008014 if (auto VecTy = dyn_cast<VectorType>(Target))
8015 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00008016
8017 // Strip complex types.
8018 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008019 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008020 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008021 return;
8022
John McCallacf0ee52010-10-08 02:01:28 +00008023 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008024 }
John McCall263a48b2010-01-04 23:31:57 +00008025
8026 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8027 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8028 }
8029
8030 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8031 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8032
8033 // If the source is floating point...
8034 if (SourceBT && SourceBT->isFloatingPoint()) {
8035 // ...and the target is floating point...
8036 if (TargetBT && TargetBT->isFloatingPoint()) {
8037 // ...then warn if we're dropping FP rank.
8038
8039 // Builtin FP kinds are ordered by increasing FP rank.
8040 if (SourceBT->getKind() > TargetBT->getKind()) {
8041 // Don't warn about float constants that are precisely
8042 // representable in the target type.
8043 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008044 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00008045 // Value might be a float, a float vector, or a float complex.
8046 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00008047 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8048 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00008049 return;
8050 }
8051
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008052 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008053 return;
8054
John McCallacf0ee52010-10-08 02:01:28 +00008055 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00008056 }
8057 // ... or possibly if we're increasing rank, too
8058 else if (TargetBT->getKind() > SourceBT->getKind()) {
8059 if (S.SourceMgr.isInSystemMacro(CC))
8060 return;
8061
8062 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00008063 }
8064 return;
8065 }
8066
Richard Trieube234c32016-04-21 21:04:55 +00008067 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00008068 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008069 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008070 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00008071
Richard Trieube234c32016-04-21 21:04:55 +00008072 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00008073 }
John McCall263a48b2010-01-04 23:31:57 +00008074
Richard Smith54894fd2015-12-30 01:06:52 +00008075 // Detect the case where a call result is converted from floating-point to
8076 // to bool, and the final argument to the call is converted from bool, to
8077 // discover this typo:
8078 //
8079 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
8080 //
8081 // FIXME: This is an incredibly special case; is there some more general
8082 // way to detect this class of misplaced-parentheses bug?
8083 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008084 // Check last argument of function call to see if it is an
8085 // implicit cast from a type matching the type the result
8086 // is being cast to.
8087 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00008088 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008089 Expr *LastA = CEx->getArg(NumArgs - 1);
8090 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00008091 if (isa<ImplicitCastExpr>(LastA) &&
8092 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008093 // Warn on this floating-point to bool conversion
8094 DiagnoseImpCast(S, E, T, CC,
8095 diag::warn_impcast_floating_point_to_bool);
8096 }
8097 }
8098 }
John McCall263a48b2010-01-04 23:31:57 +00008099 return;
8100 }
8101
Richard Trieu5b993502014-10-15 03:42:06 +00008102 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00008103
David Blaikie9366d2b2012-06-19 21:19:06 +00008104 if (!Source->isIntegerType() || !Target->isIntegerType())
8105 return;
8106
David Blaikie7555b6a2012-05-15 16:56:36 +00008107 // TODO: remove this early return once the false positives for constant->bool
8108 // in templates, macros, etc, are reduced or removed.
8109 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8110 return;
8111
John McCallcc7e5bf2010-05-06 08:58:33 +00008112 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00008113 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00008114
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008115 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00008116 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008117 // TODO: this should happen for bitfield stores, too.
8118 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00008119 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008120 if (S.SourceMgr.isInSystemMacro(CC))
8121 return;
8122
John McCall18a2c2c2010-11-09 22:22:12 +00008123 std::string PrettySourceValue = Value.toString(10);
8124 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008125
Ted Kremenek33ba9952011-10-22 02:37:33 +00008126 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8127 S.PDiag(diag::warn_impcast_integer_precision_constant)
8128 << PrettySourceValue << PrettyTargetValue
8129 << E->getType() << T << E->getSourceRange()
8130 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00008131 return;
8132 }
8133
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008134 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8135 if (S.SourceMgr.isInSystemMacro(CC))
8136 return;
8137
David Blaikie9455da02012-04-12 22:40:54 +00008138 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00008139 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8140 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00008141 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00008142 }
8143
Richard Trieudcb55572016-01-29 23:51:16 +00008144 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8145 SourceRange.NonNegative && Source->isSignedIntegerType()) {
8146 // Warn when doing a signed to signed conversion, warn if the positive
8147 // source value is exactly the width of the target type, which will
8148 // cause a negative value to be stored.
8149
8150 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00008151 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8152 !S.SourceMgr.isInSystemMacro(CC)) {
8153 if (isSameWidthConstantConversion(S, E, T, CC)) {
8154 std::string PrettySourceValue = Value.toString(10);
8155 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00008156
Richard Trieufc404c72016-02-05 23:02:38 +00008157 S.DiagRuntimeBehavior(
8158 E->getExprLoc(), E,
8159 S.PDiag(diag::warn_impcast_integer_precision_constant)
8160 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8161 << E->getSourceRange() << clang::SourceRange(CC));
8162 return;
Richard Trieudcb55572016-01-29 23:51:16 +00008163 }
8164 }
Richard Trieufc404c72016-02-05 23:02:38 +00008165
Richard Trieudcb55572016-01-29 23:51:16 +00008166 // Fall through for non-constants to give a sign conversion warning.
8167 }
8168
John McCallcc7e5bf2010-05-06 08:58:33 +00008169 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8170 (!TargetRange.NonNegative && SourceRange.NonNegative &&
8171 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008172 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008173 return;
8174
John McCallcc7e5bf2010-05-06 08:58:33 +00008175 unsigned DiagID = diag::warn_impcast_integer_sign;
8176
8177 // Traditionally, gcc has warned about this under -Wsign-compare.
8178 // We also want to warn about it in -Wconversion.
8179 // So if -Wconversion is off, use a completely identical diagnostic
8180 // in the sign-compare group.
8181 // The conditional-checking code will
8182 if (ICContext) {
8183 DiagID = diag::warn_impcast_integer_sign_conditional;
8184 *ICContext = true;
8185 }
8186
John McCallacf0ee52010-10-08 02:01:28 +00008187 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00008188 }
8189
Douglas Gregora78f1932011-02-22 02:45:07 +00008190 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00008191 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8192 // type, to give us better diagnostics.
8193 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008194 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00008195 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8196 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8197 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8198 SourceType = S.Context.getTypeDeclType(Enum);
8199 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8200 }
8201 }
8202
Douglas Gregora78f1932011-02-22 02:45:07 +00008203 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8204 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00008205 if (SourceEnum->getDecl()->hasNameForLinkage() &&
8206 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008207 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008208 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008209 return;
8210
Douglas Gregor364f7db2011-03-12 00:14:31 +00008211 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00008212 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008213 }
John McCall263a48b2010-01-04 23:31:57 +00008214}
8215
David Blaikie18e9ac72012-05-15 21:57:38 +00008216void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8217 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008218
8219void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00008220 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008221 E = E->IgnoreParenImpCasts();
8222
8223 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00008224 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008225
John McCallacf0ee52010-10-08 02:01:28 +00008226 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008227 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008228 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00008229}
8230
David Blaikie18e9ac72012-05-15 21:57:38 +00008231void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8232 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00008233 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008234
8235 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00008236 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8237 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008238
8239 // If -Wconversion would have warned about either of the candidates
8240 // for a signedness conversion to the context type...
8241 if (!Suspicious) return;
8242
8243 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008244 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00008245 return;
8246
John McCallcc7e5bf2010-05-06 08:58:33 +00008247 // ...then check whether it would have warned about either of the
8248 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00008249 if (E->getType() == T) return;
8250
8251 Suspicious = false;
8252 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8253 E->getType(), CC, &Suspicious);
8254 if (!Suspicious)
8255 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00008256 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008257}
8258
Richard Trieu65724892014-11-15 06:37:39 +00008259/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8260/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008261void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00008262 if (S.getLangOpts().Bool)
8263 return;
8264 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8265}
8266
John McCallcc7e5bf2010-05-06 08:58:33 +00008267/// AnalyzeImplicitConversions - Find and report any interesting
8268/// implicit conversions in the given expression. There are a couple
8269/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008270void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00008271 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00008272 Expr *E = OrigE->IgnoreParenImpCasts();
8273
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00008274 if (E->isTypeDependent() || E->isValueDependent())
8275 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00008276
John McCallcc7e5bf2010-05-06 08:58:33 +00008277 // For conditional operators, we analyze the arguments as if they
8278 // were being fed directly into the output.
8279 if (isa<ConditionalOperator>(E)) {
8280 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00008281 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008282 return;
8283 }
8284
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008285 // Check implicit argument conversions for function calls.
8286 if (CallExpr *Call = dyn_cast<CallExpr>(E))
8287 CheckImplicitArgumentConversions(S, Call, CC);
8288
John McCallcc7e5bf2010-05-06 08:58:33 +00008289 // Go ahead and check any implicit conversions we might have skipped.
8290 // The non-canonical typecheck is just an optimization;
8291 // CheckImplicitConversion will filter out dead implicit conversions.
8292 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008293 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008294
8295 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00008296
8297 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8298 // The bound subexpressions in a PseudoObjectExpr are not reachable
8299 // as transitive children.
8300 // FIXME: Use a more uniform representation for this.
8301 for (auto *SE : POE->semantics())
8302 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8303 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00008304 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00008305
John McCallcc7e5bf2010-05-06 08:58:33 +00008306 // Skip past explicit casts.
8307 if (isa<ExplicitCastExpr>(E)) {
8308 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00008309 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008310 }
8311
John McCalld2a53122010-11-09 23:24:47 +00008312 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8313 // Do a somewhat different check with comparison operators.
8314 if (BO->isComparisonOp())
8315 return AnalyzeComparison(S, BO);
8316
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008317 // And with simple assignments.
8318 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008319 return AnalyzeAssignment(S, BO);
8320 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008321
8322 // These break the otherwise-useful invariant below. Fortunately,
8323 // we don't really need to recurse into them, because any internal
8324 // expressions should have been analyzed already when they were
8325 // built into statements.
8326 if (isa<StmtExpr>(E)) return;
8327
8328 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008329 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008330
8331 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008332 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008333 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008334 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008335 for (Stmt *SubStmt : E->children()) {
8336 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008337 if (!ChildExpr)
8338 continue;
8339
Richard Trieu955231d2014-01-25 01:10:35 +00008340 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008341 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008342 // Ignore checking string literals that are in logical and operators.
8343 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008344 continue;
8345 AnalyzeImplicitConversions(S, ChildExpr, CC);
8346 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008347
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008348 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008349 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8350 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008351 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008352
8353 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8354 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008355 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008356 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008357
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008358 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8359 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008360 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008361}
8362
8363} // end anonymous namespace
8364
Richard Trieuc1888e02014-06-28 23:25:37 +00008365// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8366// Returns true when emitting a warning about taking the address of a reference.
8367static bool CheckForReference(Sema &SemaRef, const Expr *E,
8368 PartialDiagnostic PD) {
8369 E = E->IgnoreParenImpCasts();
8370
8371 const FunctionDecl *FD = nullptr;
8372
8373 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8374 if (!DRE->getDecl()->getType()->isReferenceType())
8375 return false;
8376 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8377 if (!M->getMemberDecl()->getType()->isReferenceType())
8378 return false;
8379 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008380 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008381 return false;
8382 FD = Call->getDirectCallee();
8383 } else {
8384 return false;
8385 }
8386
8387 SemaRef.Diag(E->getExprLoc(), PD);
8388
8389 // If possible, point to location of function.
8390 if (FD) {
8391 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8392 }
8393
8394 return true;
8395}
8396
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008397// Returns true if the SourceLocation is expanded from any macro body.
8398// Returns false if the SourceLocation is invalid, is from not in a macro
8399// expansion, or is from expanded from a top-level macro argument.
8400static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8401 if (Loc.isInvalid())
8402 return false;
8403
8404 while (Loc.isMacroID()) {
8405 if (SM.isMacroBodyExpansion(Loc))
8406 return true;
8407 Loc = SM.getImmediateMacroCallerLoc(Loc);
8408 }
8409
8410 return false;
8411}
8412
Richard Trieu3bb8b562014-02-26 02:36:06 +00008413/// \brief Diagnose pointers that are always non-null.
8414/// \param E the expression containing the pointer
8415/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8416/// compared to a null pointer
8417/// \param IsEqual True when the comparison is equal to a null pointer
8418/// \param Range Extra SourceRange to highlight in the diagnostic
8419void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8420 Expr::NullPointerConstantKind NullKind,
8421 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008422 if (!E)
8423 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008424
8425 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008426 if (E->getExprLoc().isMacroID()) {
8427 const SourceManager &SM = getSourceManager();
8428 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8429 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008430 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008431 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008432 E = E->IgnoreImpCasts();
8433
8434 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8435
Richard Trieuf7432752014-06-06 21:39:26 +00008436 if (isa<CXXThisExpr>(E)) {
8437 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8438 : diag::warn_this_bool_conversion;
8439 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8440 return;
8441 }
8442
Richard Trieu3bb8b562014-02-26 02:36:06 +00008443 bool IsAddressOf = false;
8444
8445 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8446 if (UO->getOpcode() != UO_AddrOf)
8447 return;
8448 IsAddressOf = true;
8449 E = UO->getSubExpr();
8450 }
8451
Richard Trieuc1888e02014-06-28 23:25:37 +00008452 if (IsAddressOf) {
8453 unsigned DiagID = IsCompare
8454 ? diag::warn_address_of_reference_null_compare
8455 : diag::warn_address_of_reference_bool_conversion;
8456 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8457 << IsEqual;
8458 if (CheckForReference(*this, E, PD)) {
8459 return;
8460 }
8461 }
8462
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008463 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
8464 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00008465 std::string Str;
8466 llvm::raw_string_ostream S(Str);
8467 E->printPretty(S, nullptr, getPrintingPolicy());
8468 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8469 : diag::warn_cast_nonnull_to_bool;
8470 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8471 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008472 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00008473 };
8474
8475 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8476 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8477 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008478 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
8479 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008480 return;
8481 }
8482 }
8483 }
8484
Richard Trieu3bb8b562014-02-26 02:36:06 +00008485 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008486 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008487 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8488 D = R->getDecl();
8489 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8490 D = M->getMemberDecl();
8491 }
8492
8493 // Weak Decls can be null.
8494 if (!D || D->isWeak())
8495 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008496
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008497 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008498 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8499 if (getCurFunction() &&
8500 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008501 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
8502 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008503 return;
8504 }
8505
8506 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8507 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
8508 assert(ParamIter != FD->param_end());
8509 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8510
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008511 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8512 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008513 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00008514 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008515 }
George Burgess IV850269a2015-12-08 22:02:00 +00008516
8517 for (unsigned ArgNo : NonNull->args()) {
8518 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008519 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008520 return;
8521 }
George Burgess IV850269a2015-12-08 22:02:00 +00008522 }
8523 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008524 }
8525 }
George Burgess IV850269a2015-12-08 22:02:00 +00008526 }
8527
Richard Trieu3bb8b562014-02-26 02:36:06 +00008528 QualType T = D->getType();
8529 const bool IsArray = T->isArrayType();
8530 const bool IsFunction = T->isFunctionType();
8531
Richard Trieuc1888e02014-06-28 23:25:37 +00008532 // Address of function is used to silence the function warning.
8533 if (IsAddressOf && IsFunction) {
8534 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008535 }
8536
8537 // Found nothing.
8538 if (!IsAddressOf && !IsFunction && !IsArray)
8539 return;
8540
8541 // Pretty print the expression for the diagnostic.
8542 std::string Str;
8543 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008544 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008545
8546 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8547 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008548 enum {
8549 AddressOf,
8550 FunctionPointer,
8551 ArrayPointer
8552 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008553 if (IsAddressOf)
8554 DiagType = AddressOf;
8555 else if (IsFunction)
8556 DiagType = FunctionPointer;
8557 else if (IsArray)
8558 DiagType = ArrayPointer;
8559 else
8560 llvm_unreachable("Could not determine diagnostic.");
8561 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8562 << Range << IsEqual;
8563
8564 if (!IsFunction)
8565 return;
8566
8567 // Suggest '&' to silence the function warning.
8568 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8569 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8570
8571 // Check to see if '()' fixit should be emitted.
8572 QualType ReturnType;
8573 UnresolvedSet<4> NonTemplateOverloads;
8574 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8575 if (ReturnType.isNull())
8576 return;
8577
8578 if (IsCompare) {
8579 // There are two cases here. If there is null constant, the only suggest
8580 // for a pointer return type. If the null is 0, then suggest if the return
8581 // type is a pointer or an integer type.
8582 if (!ReturnType->isPointerType()) {
8583 if (NullKind == Expr::NPCK_ZeroExpression ||
8584 NullKind == Expr::NPCK_ZeroLiteral) {
8585 if (!ReturnType->isIntegerType())
8586 return;
8587 } else {
8588 return;
8589 }
8590 }
8591 } else { // !IsCompare
8592 // For function to bool, only suggest if the function pointer has bool
8593 // return type.
8594 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8595 return;
8596 }
8597 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008598 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008599}
8600
John McCallcc7e5bf2010-05-06 08:58:33 +00008601/// Diagnoses "dangerous" implicit conversions within the given
8602/// expression (which is a full expression). Implements -Wconversion
8603/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008604///
8605/// \param CC the "context" location of the implicit conversion, i.e.
8606/// the most location of the syntactic entity requiring the implicit
8607/// conversion
8608void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008609 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008610 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008611 return;
8612
8613 // Don't diagnose for value- or type-dependent expressions.
8614 if (E->isTypeDependent() || E->isValueDependent())
8615 return;
8616
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008617 // Check for array bounds violations in cases where the check isn't triggered
8618 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8619 // ArraySubscriptExpr is on the RHS of a variable initialization.
8620 CheckArrayAccess(E);
8621
John McCallacf0ee52010-10-08 02:01:28 +00008622 // This is not the right CC for (e.g.) a variable initialization.
8623 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008624}
8625
Richard Trieu65724892014-11-15 06:37:39 +00008626/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8627/// Input argument E is a logical expression.
8628void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8629 ::CheckBoolLikeConversion(*this, E, CC);
8630}
8631
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008632/// Diagnose when expression is an integer constant expression and its evaluation
8633/// results in integer overflow
8634void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008635 // Use a work list to deal with nested struct initializers.
8636 SmallVector<Expr *, 2> Exprs(1, E);
8637
8638 do {
8639 Expr *E = Exprs.pop_back_val();
8640
8641 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8642 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8643 continue;
8644 }
8645
8646 if (auto InitList = dyn_cast<InitListExpr>(E))
8647 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8648 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008649}
8650
Richard Smithc406cb72013-01-17 01:17:56 +00008651namespace {
8652/// \brief Visitor for expressions which looks for unsequenced operations on the
8653/// same object.
8654class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008655 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8656
Richard Smithc406cb72013-01-17 01:17:56 +00008657 /// \brief A tree of sequenced regions within an expression. Two regions are
8658 /// unsequenced if one is an ancestor or a descendent of the other. When we
8659 /// finish processing an expression with sequencing, such as a comma
8660 /// expression, we fold its tree nodes into its parent, since they are
8661 /// unsequenced with respect to nodes we will visit later.
8662 class SequenceTree {
8663 struct Value {
8664 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8665 unsigned Parent : 31;
8666 bool Merged : 1;
8667 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008668 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008669
8670 public:
8671 /// \brief A region within an expression which may be sequenced with respect
8672 /// to some other region.
8673 class Seq {
8674 explicit Seq(unsigned N) : Index(N) {}
8675 unsigned Index;
8676 friend class SequenceTree;
8677 public:
8678 Seq() : Index(0) {}
8679 };
8680
8681 SequenceTree() { Values.push_back(Value(0)); }
8682 Seq root() const { return Seq(0); }
8683
8684 /// \brief Create a new sequence of operations, which is an unsequenced
8685 /// subset of \p Parent. This sequence of operations is sequenced with
8686 /// respect to other children of \p Parent.
8687 Seq allocate(Seq Parent) {
8688 Values.push_back(Value(Parent.Index));
8689 return Seq(Values.size() - 1);
8690 }
8691
8692 /// \brief Merge a sequence of operations into its parent.
8693 void merge(Seq S) {
8694 Values[S.Index].Merged = true;
8695 }
8696
8697 /// \brief Determine whether two operations are unsequenced. This operation
8698 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8699 /// should have been merged into its parent as appropriate.
8700 bool isUnsequenced(Seq Cur, Seq Old) {
8701 unsigned C = representative(Cur.Index);
8702 unsigned Target = representative(Old.Index);
8703 while (C >= Target) {
8704 if (C == Target)
8705 return true;
8706 C = Values[C].Parent;
8707 }
8708 return false;
8709 }
8710
8711 private:
8712 /// \brief Pick a representative for a sequence.
8713 unsigned representative(unsigned K) {
8714 if (Values[K].Merged)
8715 // Perform path compression as we go.
8716 return Values[K].Parent = representative(Values[K].Parent);
8717 return K;
8718 }
8719 };
8720
8721 /// An object for which we can track unsequenced uses.
8722 typedef NamedDecl *Object;
8723
8724 /// Different flavors of object usage which we track. We only track the
8725 /// least-sequenced usage of each kind.
8726 enum UsageKind {
8727 /// A read of an object. Multiple unsequenced reads are OK.
8728 UK_Use,
8729 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008730 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008731 UK_ModAsValue,
8732 /// A modification of an object which is not sequenced before the value
8733 /// computation of the expression, such as n++.
8734 UK_ModAsSideEffect,
8735
8736 UK_Count = UK_ModAsSideEffect + 1
8737 };
8738
8739 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008740 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008741 Expr *Use;
8742 SequenceTree::Seq Seq;
8743 };
8744
8745 struct UsageInfo {
8746 UsageInfo() : Diagnosed(false) {}
8747 Usage Uses[UK_Count];
8748 /// Have we issued a diagnostic for this variable already?
8749 bool Diagnosed;
8750 };
8751 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8752
8753 Sema &SemaRef;
8754 /// Sequenced regions within the expression.
8755 SequenceTree Tree;
8756 /// Declaration modifications and references which we have seen.
8757 UsageInfoMap UsageMap;
8758 /// The region we are currently within.
8759 SequenceTree::Seq Region;
8760 /// Filled in with declarations which were modified as a side-effect
8761 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008762 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008763 /// Expressions to check later. We defer checking these to reduce
8764 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008765 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008766
8767 /// RAII object wrapping the visitation of a sequenced subexpression of an
8768 /// expression. At the end of this process, the side-effects of the evaluation
8769 /// become sequenced with respect to the value computation of the result, so
8770 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8771 /// UK_ModAsValue.
8772 struct SequencedSubexpression {
8773 SequencedSubexpression(SequenceChecker &Self)
8774 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8775 Self.ModAsSideEffect = &ModAsSideEffect;
8776 }
8777 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00008778 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8779 MI != ME; ++MI) {
8780 UsageInfo &U = Self.UsageMap[MI->first];
8781 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8782 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8783 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00008784 }
8785 Self.ModAsSideEffect = OldModAsSideEffect;
8786 }
8787
8788 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008789 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8790 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008791 };
8792
Richard Smith40238f02013-06-20 22:21:56 +00008793 /// RAII object wrapping the visitation of a subexpression which we might
8794 /// choose to evaluate as a constant. If any subexpression is evaluated and
8795 /// found to be non-constant, this allows us to suppress the evaluation of
8796 /// the outer expression.
8797 class EvaluationTracker {
8798 public:
8799 EvaluationTracker(SequenceChecker &Self)
8800 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8801 Self.EvalTracker = this;
8802 }
8803 ~EvaluationTracker() {
8804 Self.EvalTracker = Prev;
8805 if (Prev)
8806 Prev->EvalOK &= EvalOK;
8807 }
8808
8809 bool evaluate(const Expr *E, bool &Result) {
8810 if (!EvalOK || E->isValueDependent())
8811 return false;
8812 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8813 return EvalOK;
8814 }
8815
8816 private:
8817 SequenceChecker &Self;
8818 EvaluationTracker *Prev;
8819 bool EvalOK;
8820 } *EvalTracker;
8821
Richard Smithc406cb72013-01-17 01:17:56 +00008822 /// \brief Find the object which is produced by the specified expression,
8823 /// if any.
8824 Object getObject(Expr *E, bool Mod) const {
8825 E = E->IgnoreParenCasts();
8826 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8827 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8828 return getObject(UO->getSubExpr(), Mod);
8829 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8830 if (BO->getOpcode() == BO_Comma)
8831 return getObject(BO->getRHS(), Mod);
8832 if (Mod && BO->isAssignmentOp())
8833 return getObject(BO->getLHS(), Mod);
8834 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8835 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8836 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8837 return ME->getMemberDecl();
8838 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8839 // FIXME: If this is a reference, map through to its value.
8840 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008841 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008842 }
8843
8844 /// \brief Note that an object was modified or used by an expression.
8845 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8846 Usage &U = UI.Uses[UK];
8847 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8848 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8849 ModAsSideEffect->push_back(std::make_pair(O, U));
8850 U.Use = Ref;
8851 U.Seq = Region;
8852 }
8853 }
8854 /// \brief Check whether a modification or use conflicts with a prior usage.
8855 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8856 bool IsModMod) {
8857 if (UI.Diagnosed)
8858 return;
8859
8860 const Usage &U = UI.Uses[OtherKind];
8861 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8862 return;
8863
8864 Expr *Mod = U.Use;
8865 Expr *ModOrUse = Ref;
8866 if (OtherKind == UK_Use)
8867 std::swap(Mod, ModOrUse);
8868
8869 SemaRef.Diag(Mod->getExprLoc(),
8870 IsModMod ? diag::warn_unsequenced_mod_mod
8871 : diag::warn_unsequenced_mod_use)
8872 << O << SourceRange(ModOrUse->getExprLoc());
8873 UI.Diagnosed = true;
8874 }
8875
8876 void notePreUse(Object O, Expr *Use) {
8877 UsageInfo &U = UsageMap[O];
8878 // Uses conflict with other modifications.
8879 checkUsage(O, U, Use, UK_ModAsValue, false);
8880 }
8881 void notePostUse(Object O, Expr *Use) {
8882 UsageInfo &U = UsageMap[O];
8883 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8884 addUsage(U, O, Use, UK_Use);
8885 }
8886
8887 void notePreMod(Object O, Expr *Mod) {
8888 UsageInfo &U = UsageMap[O];
8889 // Modifications conflict with other modifications and with uses.
8890 checkUsage(O, U, Mod, UK_ModAsValue, true);
8891 checkUsage(O, U, Mod, UK_Use, false);
8892 }
8893 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8894 UsageInfo &U = UsageMap[O];
8895 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8896 addUsage(U, O, Use, UK);
8897 }
8898
8899public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008900 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008901 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8902 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008903 Visit(E);
8904 }
8905
8906 void VisitStmt(Stmt *S) {
8907 // Skip all statements which aren't expressions for now.
8908 }
8909
8910 void VisitExpr(Expr *E) {
8911 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008912 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008913 }
8914
8915 void VisitCastExpr(CastExpr *E) {
8916 Object O = Object();
8917 if (E->getCastKind() == CK_LValueToRValue)
8918 O = getObject(E->getSubExpr(), false);
8919
8920 if (O)
8921 notePreUse(O, E);
8922 VisitExpr(E);
8923 if (O)
8924 notePostUse(O, E);
8925 }
8926
8927 void VisitBinComma(BinaryOperator *BO) {
8928 // C++11 [expr.comma]p1:
8929 // Every value computation and side effect associated with the left
8930 // expression is sequenced before every value computation and side
8931 // effect associated with the right expression.
8932 SequenceTree::Seq LHS = Tree.allocate(Region);
8933 SequenceTree::Seq RHS = Tree.allocate(Region);
8934 SequenceTree::Seq OldRegion = Region;
8935
8936 {
8937 SequencedSubexpression SeqLHS(*this);
8938 Region = LHS;
8939 Visit(BO->getLHS());
8940 }
8941
8942 Region = RHS;
8943 Visit(BO->getRHS());
8944
8945 Region = OldRegion;
8946
8947 // Forget that LHS and RHS are sequenced. They are both unsequenced
8948 // with respect to other stuff.
8949 Tree.merge(LHS);
8950 Tree.merge(RHS);
8951 }
8952
8953 void VisitBinAssign(BinaryOperator *BO) {
8954 // The modification is sequenced after the value computation of the LHS
8955 // and RHS, so check it before inspecting the operands and update the
8956 // map afterwards.
8957 Object O = getObject(BO->getLHS(), true);
8958 if (!O)
8959 return VisitExpr(BO);
8960
8961 notePreMod(O, BO);
8962
8963 // C++11 [expr.ass]p7:
8964 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8965 // only once.
8966 //
8967 // Therefore, for a compound assignment operator, O is considered used
8968 // everywhere except within the evaluation of E1 itself.
8969 if (isa<CompoundAssignOperator>(BO))
8970 notePreUse(O, BO);
8971
8972 Visit(BO->getLHS());
8973
8974 if (isa<CompoundAssignOperator>(BO))
8975 notePostUse(O, BO);
8976
8977 Visit(BO->getRHS());
8978
Richard Smith83e37bee2013-06-26 23:16:51 +00008979 // C++11 [expr.ass]p1:
8980 // the assignment is sequenced [...] before the value computation of the
8981 // assignment expression.
8982 // C11 6.5.16/3 has no such rule.
8983 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8984 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008985 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008986
Richard Smithc406cb72013-01-17 01:17:56 +00008987 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8988 VisitBinAssign(CAO);
8989 }
8990
8991 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8992 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8993 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8994 Object O = getObject(UO->getSubExpr(), true);
8995 if (!O)
8996 return VisitExpr(UO);
8997
8998 notePreMod(O, UO);
8999 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00009000 // C++11 [expr.pre.incr]p1:
9001 // the expression ++x is equivalent to x+=1
9002 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9003 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009004 }
9005
9006 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9007 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9008 void VisitUnaryPostIncDec(UnaryOperator *UO) {
9009 Object O = getObject(UO->getSubExpr(), true);
9010 if (!O)
9011 return VisitExpr(UO);
9012
9013 notePreMod(O, UO);
9014 Visit(UO->getSubExpr());
9015 notePostMod(O, UO, UK_ModAsSideEffect);
9016 }
9017
9018 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9019 void VisitBinLOr(BinaryOperator *BO) {
9020 // The side-effects of the LHS of an '&&' are sequenced before the
9021 // value computation of the RHS, and hence before the value computation
9022 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9023 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00009024 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009025 {
9026 SequencedSubexpression Sequenced(*this);
9027 Visit(BO->getLHS());
9028 }
9029
9030 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009031 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009032 if (!Result)
9033 Visit(BO->getRHS());
9034 } else {
9035 // Check for unsequenced operations in the RHS, treating it as an
9036 // entirely separate evaluation.
9037 //
9038 // FIXME: If there are operations in the RHS which are unsequenced
9039 // with respect to operations outside the RHS, and those operations
9040 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00009041 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009042 }
Richard Smithc406cb72013-01-17 01:17:56 +00009043 }
9044 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00009045 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009046 {
9047 SequencedSubexpression Sequenced(*this);
9048 Visit(BO->getLHS());
9049 }
9050
9051 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009052 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009053 if (Result)
9054 Visit(BO->getRHS());
9055 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00009056 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009057 }
Richard Smithc406cb72013-01-17 01:17:56 +00009058 }
9059
9060 // Only visit the condition, unless we can be sure which subexpression will
9061 // be chosen.
9062 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00009063 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00009064 {
9065 SequencedSubexpression Sequenced(*this);
9066 Visit(CO->getCond());
9067 }
Richard Smithc406cb72013-01-17 01:17:56 +00009068
9069 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009070 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00009071 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009072 else {
Richard Smithd33f5202013-01-17 23:18:09 +00009073 WorkList.push_back(CO->getTrueExpr());
9074 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009075 }
Richard Smithc406cb72013-01-17 01:17:56 +00009076 }
9077
Richard Smithe3dbfe02013-06-30 10:40:20 +00009078 void VisitCallExpr(CallExpr *CE) {
9079 // C++11 [intro.execution]p15:
9080 // When calling a function [...], every value computation and side effect
9081 // associated with any argument expression, or with the postfix expression
9082 // designating the called function, is sequenced before execution of every
9083 // expression or statement in the body of the function [and thus before
9084 // the value computation of its result].
9085 SequencedSubexpression Sequenced(*this);
9086 Base::VisitCallExpr(CE);
9087
9088 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9089 }
9090
Richard Smithc406cb72013-01-17 01:17:56 +00009091 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009092 // This is a call, so all subexpressions are sequenced before the result.
9093 SequencedSubexpression Sequenced(*this);
9094
Richard Smithc406cb72013-01-17 01:17:56 +00009095 if (!CCE->isListInitialization())
9096 return VisitExpr(CCE);
9097
9098 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009099 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009100 SequenceTree::Seq Parent = Region;
9101 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9102 E = CCE->arg_end();
9103 I != E; ++I) {
9104 Region = Tree.allocate(Parent);
9105 Elts.push_back(Region);
9106 Visit(*I);
9107 }
9108
9109 // Forget that the initializers are sequenced.
9110 Region = Parent;
9111 for (unsigned I = 0; I < Elts.size(); ++I)
9112 Tree.merge(Elts[I]);
9113 }
9114
9115 void VisitInitListExpr(InitListExpr *ILE) {
9116 if (!SemaRef.getLangOpts().CPlusPlus11)
9117 return VisitExpr(ILE);
9118
9119 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009120 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009121 SequenceTree::Seq Parent = Region;
9122 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9123 Expr *E = ILE->getInit(I);
9124 if (!E) continue;
9125 Region = Tree.allocate(Parent);
9126 Elts.push_back(Region);
9127 Visit(E);
9128 }
9129
9130 // Forget that the initializers are sequenced.
9131 Region = Parent;
9132 for (unsigned I = 0; I < Elts.size(); ++I)
9133 Tree.merge(Elts[I]);
9134 }
9135};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009136} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00009137
9138void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009139 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00009140 WorkList.push_back(E);
9141 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00009142 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00009143 SequenceChecker(*this, Item, WorkList);
9144 }
Richard Smithc406cb72013-01-17 01:17:56 +00009145}
9146
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009147void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9148 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009149 CheckImplicitConversions(E, CheckLoc);
9150 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009151 if (!IsConstexpr && !E->isValueDependent())
9152 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009153}
9154
John McCall1f425642010-11-11 03:21:53 +00009155void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9156 FieldDecl *BitField,
9157 Expr *Init) {
9158 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9159}
9160
David Majnemer61a5bbf2015-04-07 22:08:51 +00009161static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9162 SourceLocation Loc) {
9163 if (!PType->isVariablyModifiedType())
9164 return;
9165 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9166 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9167 return;
9168 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00009169 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9170 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9171 return;
9172 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00009173 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9174 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9175 return;
9176 }
9177
9178 const ArrayType *AT = S.Context.getAsArrayType(PType);
9179 if (!AT)
9180 return;
9181
9182 if (AT->getSizeModifier() != ArrayType::Star) {
9183 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9184 return;
9185 }
9186
9187 S.Diag(Loc, diag::err_array_star_in_function_definition);
9188}
9189
Mike Stump0c2ec772010-01-21 03:59:47 +00009190/// CheckParmsForFunctionDef - Check that the parameters of the given
9191/// function are appropriate for the definition of a function. This
9192/// takes care of any checks that cannot be performed on the
9193/// declaration itself, e.g., that the types of each of the function
9194/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00009195bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
9196 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00009197 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009198 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00009199 for (; P != PEnd; ++P) {
9200 ParmVarDecl *Param = *P;
9201
Mike Stump0c2ec772010-01-21 03:59:47 +00009202 // C99 6.7.5.3p4: the parameters in a parameter type list in a
9203 // function declarator that is part of a function definition of
9204 // that function shall not have incomplete type.
9205 //
9206 // This is also C++ [dcl.fct]p6.
9207 if (!Param->isInvalidDecl() &&
9208 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009209 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009210 Param->setInvalidDecl();
9211 HasInvalidParm = true;
9212 }
9213
9214 // C99 6.9.1p5: If the declarator includes a parameter type list, the
9215 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00009216 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00009217 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00009218 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009219 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00009220 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00009221
9222 // C99 6.7.5.3p12:
9223 // If the function declarator is not part of a definition of that
9224 // function, parameters may have incomplete type and may use the [*]
9225 // notation in their sequences of declarator specifiers to specify
9226 // variable length array types.
9227 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00009228 // FIXME: This diagnostic should point the '[*]' if source-location
9229 // information is added for it.
9230 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009231
9232 // MSVC destroys objects passed by value in the callee. Therefore a
9233 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009234 // object's destructor. However, we don't perform any direct access check
9235 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00009236 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9237 .getCXXABI()
9238 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00009239 if (!Param->isInvalidDecl()) {
9240 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9241 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9242 if (!ClassDecl->isInvalidDecl() &&
9243 !ClassDecl->hasIrrelevantDestructor() &&
9244 !ClassDecl->isDependentContext()) {
9245 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9246 MarkFunctionReferenced(Param->getLocation(), Destructor);
9247 DiagnoseUseOfDecl(Destructor, Param->getLocation());
9248 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009249 }
9250 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009251 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009252
9253 // Parameters with the pass_object_size attribute only need to be marked
9254 // constant at function definitions. Because we lack information about
9255 // whether we're on a declaration or definition when we're instantiating the
9256 // attribute, we need to check for constness here.
9257 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9258 if (!Param->getType().isConstQualified())
9259 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9260 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00009261 }
9262
9263 return HasInvalidParm;
9264}
John McCall2b5c1b22010-08-12 21:44:57 +00009265
9266/// CheckCastAlign - Implements -Wcast-align, which warns when a
9267/// pointer cast increases the alignment requirements.
9268void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9269 // This is actually a lot of work to potentially be doing on every
9270 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009271 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00009272 return;
9273
9274 // Ignore dependent types.
9275 if (T->isDependentType() || Op->getType()->isDependentType())
9276 return;
9277
9278 // Require that the destination be a pointer type.
9279 const PointerType *DestPtr = T->getAs<PointerType>();
9280 if (!DestPtr) return;
9281
9282 // If the destination has alignment 1, we're done.
9283 QualType DestPointee = DestPtr->getPointeeType();
9284 if (DestPointee->isIncompleteType()) return;
9285 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9286 if (DestAlign.isOne()) return;
9287
9288 // Require that the source be a pointer type.
9289 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9290 if (!SrcPtr) return;
9291 QualType SrcPointee = SrcPtr->getPointeeType();
9292
9293 // Whitelist casts from cv void*. We already implicitly
9294 // whitelisted casts to cv void*, since they have alignment 1.
9295 // Also whitelist casts involving incomplete types, which implicitly
9296 // includes 'void'.
9297 if (SrcPointee->isIncompleteType()) return;
9298
9299 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9300 if (SrcAlign >= DestAlign) return;
9301
9302 Diag(TRange.getBegin(), diag::warn_cast_align)
9303 << Op->getType() << T
9304 << static_cast<unsigned>(SrcAlign.getQuantity())
9305 << static_cast<unsigned>(DestAlign.getQuantity())
9306 << TRange << Op->getSourceRange();
9307}
9308
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009309static const Type* getElementType(const Expr *BaseExpr) {
9310 const Type* EltType = BaseExpr->getType().getTypePtr();
9311 if (EltType->isAnyPointerType())
9312 return EltType->getPointeeType().getTypePtr();
9313 else if (EltType->isArrayType())
9314 return EltType->getBaseElementTypeUnsafe();
9315 return EltType;
9316}
9317
Chandler Carruth28389f02011-08-05 09:10:50 +00009318/// \brief Check whether this array fits the idiom of a size-one tail padded
9319/// array member of a struct.
9320///
9321/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9322/// commonly used to emulate flexible arrays in C89 code.
9323static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
9324 const NamedDecl *ND) {
9325 if (Size != 1 || !ND) return false;
9326
9327 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9328 if (!FD) return false;
9329
9330 // Don't consider sizes resulting from macro expansions or template argument
9331 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009332
9333 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009334 while (TInfo) {
9335 TypeLoc TL = TInfo->getTypeLoc();
9336 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009337 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9338 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009339 TInfo = TDL->getTypeSourceInfo();
9340 continue;
9341 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009342 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9343 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00009344 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9345 return false;
9346 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009347 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009348 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009349
9350 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009351 if (!RD) return false;
9352 if (RD->isUnion()) return false;
9353 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9354 if (!CRD->isStandardLayout()) return false;
9355 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009356
Benjamin Kramer8c543672011-08-06 03:04:42 +00009357 // See if this is the last field decl in the record.
9358 const Decl *D = FD;
9359 while ((D = D->getNextDeclInContext()))
9360 if (isa<FieldDecl>(D))
9361 return false;
9362 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009363}
9364
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009365void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009366 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009367 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009368 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009369 if (IndexExpr->isValueDependent())
9370 return;
9371
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00009372 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009373 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009374 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009375 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009376 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009377 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009378
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009379 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009380 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009381 return;
Richard Smith13f67182011-12-16 19:31:14 +00009382 if (IndexNegated)
9383 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009384
Craig Topperc3ec1492014-05-26 06:22:03 +00009385 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009386 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9387 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009388 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009389 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009390
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009391 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009392 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009393 if (!size.isStrictlyPositive())
9394 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009395
9396 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00009397 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009398 // Make sure we're comparing apples to apples when comparing index to size
9399 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9400 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009401 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009402 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009403 if (ptrarith_typesize != array_typesize) {
9404 // There's a cast to a different size type involved
9405 uint64_t ratio = array_typesize / ptrarith_typesize;
9406 // TODO: Be smarter about handling cases where array_typesize is not a
9407 // multiple of ptrarith_typesize
9408 if (ptrarith_typesize * ratio == array_typesize)
9409 size *= llvm::APInt(size.getBitWidth(), ratio);
9410 }
9411 }
9412
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009413 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009414 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009415 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009416 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009417
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009418 // For array subscripting the index must be less than size, but for pointer
9419 // arithmetic also allow the index (offset) to be equal to size since
9420 // computing the next address after the end of the array is legal and
9421 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009422 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009423 return;
9424
9425 // Also don't warn for arrays of size 1 which are members of some
9426 // structure. These are often used to approximate flexible arrays in C89
9427 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009428 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009429 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009430
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009431 // Suppress the warning if the subscript expression (as identified by the
9432 // ']' location) and the index expression are both from macro expansions
9433 // within a system header.
9434 if (ASE) {
9435 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9436 ASE->getRBracketLoc());
9437 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9438 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9439 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009440 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009441 return;
9442 }
9443 }
9444
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009445 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009446 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009447 DiagID = diag::warn_array_index_exceeds_bounds;
9448
9449 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9450 PDiag(DiagID) << index.toString(10, true)
9451 << size.toString(10, true)
9452 << (unsigned)size.getLimitedValue(~0U)
9453 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009454 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009455 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009456 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009457 DiagID = diag::warn_ptr_arith_precedes_bounds;
9458 if (index.isNegative()) index = -index;
9459 }
9460
9461 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9462 PDiag(DiagID) << index.toString(10, true)
9463 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009464 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009465
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009466 if (!ND) {
9467 // Try harder to find a NamedDecl to point at in the note.
9468 while (const ArraySubscriptExpr *ASE =
9469 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9470 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9471 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9472 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9473 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9474 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9475 }
9476
Chandler Carruth1af88f12011-02-17 21:10:52 +00009477 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009478 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9479 PDiag(diag::note_array_index_out_of_bounds)
9480 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009481}
9482
Ted Kremenekdf26df72011-03-01 18:41:00 +00009483void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009484 int AllowOnePastEnd = 0;
9485 while (expr) {
9486 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009487 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009488 case Stmt::ArraySubscriptExprClass: {
9489 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009490 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009491 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009492 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009493 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009494 case Stmt::OMPArraySectionExprClass: {
9495 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9496 if (ASE->getLowerBound())
9497 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9498 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9499 return;
9500 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009501 case Stmt::UnaryOperatorClass: {
9502 // Only unwrap the * and & unary operators
9503 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9504 expr = UO->getSubExpr();
9505 switch (UO->getOpcode()) {
9506 case UO_AddrOf:
9507 AllowOnePastEnd++;
9508 break;
9509 case UO_Deref:
9510 AllowOnePastEnd--;
9511 break;
9512 default:
9513 return;
9514 }
9515 break;
9516 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009517 case Stmt::ConditionalOperatorClass: {
9518 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9519 if (const Expr *lhs = cond->getLHS())
9520 CheckArrayAccess(lhs);
9521 if (const Expr *rhs = cond->getRHS())
9522 CheckArrayAccess(rhs);
9523 return;
9524 }
9525 default:
9526 return;
9527 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009528 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009529}
John McCall31168b02011-06-15 23:02:42 +00009530
9531//===--- CHECK: Objective-C retain cycles ----------------------------------//
9532
9533namespace {
9534 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009535 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009536 VarDecl *Variable;
9537 SourceRange Range;
9538 SourceLocation Loc;
9539 bool Indirect;
9540
9541 void setLocsFrom(Expr *e) {
9542 Loc = e->getExprLoc();
9543 Range = e->getSourceRange();
9544 }
9545 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009546} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009547
9548/// Consider whether capturing the given variable can possibly lead to
9549/// a retain cycle.
9550static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009551 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009552 // lifetime. In MRR, it's captured strongly if the variable is
9553 // __block and has an appropriate type.
9554 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9555 return false;
9556
9557 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009558 if (ref)
9559 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009560 return true;
9561}
9562
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009563static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009564 while (true) {
9565 e = e->IgnoreParens();
9566 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9567 switch (cast->getCastKind()) {
9568 case CK_BitCast:
9569 case CK_LValueBitCast:
9570 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009571 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009572 e = cast->getSubExpr();
9573 continue;
9574
John McCall31168b02011-06-15 23:02:42 +00009575 default:
9576 return false;
9577 }
9578 }
9579
9580 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9581 ObjCIvarDecl *ivar = ref->getDecl();
9582 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9583 return false;
9584
9585 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009586 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009587 return false;
9588
9589 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9590 owner.Indirect = true;
9591 return true;
9592 }
9593
9594 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9595 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9596 if (!var) return false;
9597 return considerVariable(var, ref, owner);
9598 }
9599
John McCall31168b02011-06-15 23:02:42 +00009600 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9601 if (member->isArrow()) return false;
9602
9603 // Don't count this as an indirect ownership.
9604 e = member->getBase();
9605 continue;
9606 }
9607
John McCallfe96e0b2011-11-06 09:01:30 +00009608 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9609 // Only pay attention to pseudo-objects on property references.
9610 ObjCPropertyRefExpr *pre
9611 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9612 ->IgnoreParens());
9613 if (!pre) return false;
9614 if (pre->isImplicitProperty()) return false;
9615 ObjCPropertyDecl *property = pre->getExplicitProperty();
9616 if (!property->isRetaining() &&
9617 !(property->getPropertyIvarDecl() &&
9618 property->getPropertyIvarDecl()->getType()
9619 .getObjCLifetime() == Qualifiers::OCL_Strong))
9620 return false;
9621
9622 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009623 if (pre->isSuperReceiver()) {
9624 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9625 if (!owner.Variable)
9626 return false;
9627 owner.Loc = pre->getLocation();
9628 owner.Range = pre->getSourceRange();
9629 return true;
9630 }
John McCallfe96e0b2011-11-06 09:01:30 +00009631 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9632 ->getSourceExpr());
9633 continue;
9634 }
9635
John McCall31168b02011-06-15 23:02:42 +00009636 // Array ivars?
9637
9638 return false;
9639 }
9640}
9641
9642namespace {
9643 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9644 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9645 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009646 Context(Context), Variable(variable), Capturer(nullptr),
9647 VarWillBeReased(false) {}
9648 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009649 VarDecl *Variable;
9650 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009651 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009652
9653 void VisitDeclRefExpr(DeclRefExpr *ref) {
9654 if (ref->getDecl() == Variable && !Capturer)
9655 Capturer = ref;
9656 }
9657
John McCall31168b02011-06-15 23:02:42 +00009658 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9659 if (Capturer) return;
9660 Visit(ref->getBase());
9661 if (Capturer && ref->isFreeIvar())
9662 Capturer = ref;
9663 }
9664
9665 void VisitBlockExpr(BlockExpr *block) {
9666 // Look inside nested blocks
9667 if (block->getBlockDecl()->capturesVariable(Variable))
9668 Visit(block->getBlockDecl()->getBody());
9669 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009670
9671 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9672 if (Capturer) return;
9673 if (OVE->getSourceExpr())
9674 Visit(OVE->getSourceExpr());
9675 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009676 void VisitBinaryOperator(BinaryOperator *BinOp) {
9677 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9678 return;
9679 Expr *LHS = BinOp->getLHS();
9680 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9681 if (DRE->getDecl() != Variable)
9682 return;
9683 if (Expr *RHS = BinOp->getRHS()) {
9684 RHS = RHS->IgnoreParenCasts();
9685 llvm::APSInt Value;
9686 VarWillBeReased =
9687 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9688 }
9689 }
9690 }
John McCall31168b02011-06-15 23:02:42 +00009691 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009692} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009693
9694/// Check whether the given argument is a block which captures a
9695/// variable.
9696static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9697 assert(owner.Variable && owner.Loc.isValid());
9698
9699 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009700
9701 // Look through [^{...} copy] and Block_copy(^{...}).
9702 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9703 Selector Cmd = ME->getSelector();
9704 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9705 e = ME->getInstanceReceiver();
9706 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009707 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009708 e = e->IgnoreParenCasts();
9709 }
9710 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9711 if (CE->getNumArgs() == 1) {
9712 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009713 if (Fn) {
9714 const IdentifierInfo *FnI = Fn->getIdentifier();
9715 if (FnI && FnI->isStr("_Block_copy")) {
9716 e = CE->getArg(0)->IgnoreParenCasts();
9717 }
9718 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009719 }
9720 }
9721
John McCall31168b02011-06-15 23:02:42 +00009722 BlockExpr *block = dyn_cast<BlockExpr>(e);
9723 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009724 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009725
9726 FindCaptureVisitor visitor(S.Context, owner.Variable);
9727 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009728 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009729}
9730
9731static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9732 RetainCycleOwner &owner) {
9733 assert(capturer);
9734 assert(owner.Variable && owner.Loc.isValid());
9735
9736 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9737 << owner.Variable << capturer->getSourceRange();
9738 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9739 << owner.Indirect << owner.Range;
9740}
9741
9742/// Check for a keyword selector that starts with the word 'add' or
9743/// 'set'.
9744static bool isSetterLikeSelector(Selector sel) {
9745 if (sel.isUnarySelector()) return false;
9746
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009747 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009748 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009749 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009750 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009751 else if (str.startswith("add")) {
9752 // Specially whitelist 'addOperationWithBlock:'.
9753 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9754 return false;
9755 str = str.substr(3);
9756 }
John McCall31168b02011-06-15 23:02:42 +00009757 else
9758 return false;
9759
9760 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009761 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009762}
9763
Benjamin Kramer3a743452015-03-09 15:03:32 +00009764static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9765 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009766 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9767 Message->getReceiverInterface(),
9768 NSAPI::ClassId_NSMutableArray);
9769 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009770 return None;
9771 }
9772
9773 Selector Sel = Message->getSelector();
9774
9775 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9776 S.NSAPIObj->getNSArrayMethodKind(Sel);
9777 if (!MKOpt) {
9778 return None;
9779 }
9780
9781 NSAPI::NSArrayMethodKind MK = *MKOpt;
9782
9783 switch (MK) {
9784 case NSAPI::NSMutableArr_addObject:
9785 case NSAPI::NSMutableArr_insertObjectAtIndex:
9786 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9787 return 0;
9788 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9789 return 1;
9790
9791 default:
9792 return None;
9793 }
9794
9795 return None;
9796}
9797
9798static
9799Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9800 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009801 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9802 Message->getReceiverInterface(),
9803 NSAPI::ClassId_NSMutableDictionary);
9804 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009805 return None;
9806 }
9807
9808 Selector Sel = Message->getSelector();
9809
9810 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9811 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9812 if (!MKOpt) {
9813 return None;
9814 }
9815
9816 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9817
9818 switch (MK) {
9819 case NSAPI::NSMutableDict_setObjectForKey:
9820 case NSAPI::NSMutableDict_setValueForKey:
9821 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9822 return 0;
9823
9824 default:
9825 return None;
9826 }
9827
9828 return None;
9829}
9830
9831static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009832 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9833 Message->getReceiverInterface(),
9834 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009835
Alex Denisov5dfac812015-08-06 04:51:14 +00009836 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9837 Message->getReceiverInterface(),
9838 NSAPI::ClassId_NSMutableOrderedSet);
9839 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009840 return None;
9841 }
9842
9843 Selector Sel = Message->getSelector();
9844
9845 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9846 if (!MKOpt) {
9847 return None;
9848 }
9849
9850 NSAPI::NSSetMethodKind MK = *MKOpt;
9851
9852 switch (MK) {
9853 case NSAPI::NSMutableSet_addObject:
9854 case NSAPI::NSOrderedSet_setObjectAtIndex:
9855 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9856 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9857 return 0;
9858 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9859 return 1;
9860 }
9861
9862 return None;
9863}
9864
9865void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9866 if (!Message->isInstanceMessage()) {
9867 return;
9868 }
9869
9870 Optional<int> ArgOpt;
9871
9872 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9873 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9874 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9875 return;
9876 }
9877
9878 int ArgIndex = *ArgOpt;
9879
Alex Denisove1d882c2015-03-04 17:55:52 +00009880 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9881 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9882 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9883 }
9884
Alex Denisov5dfac812015-08-06 04:51:14 +00009885 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009886 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009887 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009888 Diag(Message->getSourceRange().getBegin(),
9889 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009890 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009891 }
9892 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009893 } else {
9894 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9895
9896 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9897 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9898 }
9899
9900 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9901 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9902 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9903 ValueDecl *Decl = ReceiverRE->getDecl();
9904 Diag(Message->getSourceRange().getBegin(),
9905 diag::warn_objc_circular_container)
9906 << Decl->getName() << Decl->getName();
9907 if (!ArgRE->isObjCSelfExpr()) {
9908 Diag(Decl->getLocation(),
9909 diag::note_objc_circular_container_declared_here)
9910 << Decl->getName();
9911 }
9912 }
9913 }
9914 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9915 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9916 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9917 ObjCIvarDecl *Decl = IvarRE->getDecl();
9918 Diag(Message->getSourceRange().getBegin(),
9919 diag::warn_objc_circular_container)
9920 << Decl->getName() << Decl->getName();
9921 Diag(Decl->getLocation(),
9922 diag::note_objc_circular_container_declared_here)
9923 << Decl->getName();
9924 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009925 }
9926 }
9927 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009928}
9929
John McCall31168b02011-06-15 23:02:42 +00009930/// Check a message send to see if it's likely to cause a retain cycle.
9931void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9932 // Only check instance methods whose selector looks like a setter.
9933 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9934 return;
9935
9936 // Try to find a variable that the receiver is strongly owned by.
9937 RetainCycleOwner owner;
9938 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009939 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009940 return;
9941 } else {
9942 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9943 owner.Variable = getCurMethodDecl()->getSelfDecl();
9944 owner.Loc = msg->getSuperLoc();
9945 owner.Range = msg->getSuperLoc();
9946 }
9947
9948 // Check whether the receiver is captured by any of the arguments.
9949 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9950 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9951 return diagnoseRetainCycle(*this, capturer, owner);
9952}
9953
9954/// Check a property assign to see if it's likely to cause a retain cycle.
9955void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9956 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009957 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009958 return;
9959
9960 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9961 diagnoseRetainCycle(*this, capturer, owner);
9962}
9963
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009964void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9965 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009966 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009967 return;
9968
9969 // Because we don't have an expression for the variable, we have to set the
9970 // location explicitly here.
9971 Owner.Loc = Var->getLocation();
9972 Owner.Range = Var->getSourceRange();
9973
9974 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9975 diagnoseRetainCycle(*this, Capturer, Owner);
9976}
9977
Ted Kremenek9304da92012-12-21 08:04:28 +00009978static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9979 Expr *RHS, bool isProperty) {
9980 // Check if RHS is an Objective-C object literal, which also can get
9981 // immediately zapped in a weak reference. Note that we explicitly
9982 // allow ObjCStringLiterals, since those are designed to never really die.
9983 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009984
Ted Kremenek64873352012-12-21 22:46:35 +00009985 // This enum needs to match with the 'select' in
9986 // warn_objc_arc_literal_assign (off-by-1).
9987 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9988 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9989 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009990
9991 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009992 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009993 << (isProperty ? 0 : 1)
9994 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009995
9996 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009997}
9998
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009999static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10000 Qualifiers::ObjCLifetime LT,
10001 Expr *RHS, bool isProperty) {
10002 // Strip off any implicit cast added to get to the one ARC-specific.
10003 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10004 if (cast->getCastKind() == CK_ARCConsumeObject) {
10005 S.Diag(Loc, diag::warn_arc_retained_assign)
10006 << (LT == Qualifiers::OCL_ExplicitNone)
10007 << (isProperty ? 0 : 1)
10008 << RHS->getSourceRange();
10009 return true;
10010 }
10011 RHS = cast->getSubExpr();
10012 }
10013
10014 if (LT == Qualifiers::OCL_Weak &&
10015 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10016 return true;
10017
10018 return false;
10019}
10020
Ted Kremenekb36234d2012-12-21 08:04:20 +000010021bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10022 QualType LHS, Expr *RHS) {
10023 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10024
10025 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10026 return false;
10027
10028 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10029 return true;
10030
10031 return false;
10032}
10033
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010034void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10035 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010036 QualType LHSType;
10037 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010038 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010039 ObjCPropertyRefExpr *PRE
10040 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10041 if (PRE && !PRE->isImplicitProperty()) {
10042 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10043 if (PD)
10044 LHSType = PD->getType();
10045 }
10046
10047 if (LHSType.isNull())
10048 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000010049
10050 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10051
10052 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010053 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000010054 getCurFunction()->markSafeWeakUse(LHS);
10055 }
10056
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010057 if (checkUnsafeAssigns(Loc, LHSType, RHS))
10058 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000010059
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010060 // FIXME. Check for other life times.
10061 if (LT != Qualifiers::OCL_None)
10062 return;
10063
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010064 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010065 if (PRE->isImplicitProperty())
10066 return;
10067 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10068 if (!PD)
10069 return;
10070
Bill Wendling44426052012-12-20 19:22:21 +000010071 unsigned Attributes = PD->getPropertyAttributes();
10072 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010073 // when 'assign' attribute was not explicitly specified
10074 // by user, ignore it and rely on property type itself
10075 // for lifetime info.
10076 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10077 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10078 LHSType->isObjCRetainableType())
10079 return;
10080
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010081 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000010082 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010083 Diag(Loc, diag::warn_arc_retained_property_assign)
10084 << RHS->getSourceRange();
10085 return;
10086 }
10087 RHS = cast->getSubExpr();
10088 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010089 }
Bill Wendling44426052012-12-20 19:22:21 +000010090 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000010091 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10092 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000010093 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010094 }
10095}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010096
10097//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10098
10099namespace {
10100bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10101 SourceLocation StmtLoc,
10102 const NullStmt *Body) {
10103 // Do not warn if the body is a macro that expands to nothing, e.g:
10104 //
10105 // #define CALL(x)
10106 // if (condition)
10107 // CALL(0);
10108 //
10109 if (Body->hasLeadingEmptyMacro())
10110 return false;
10111
10112 // Get line numbers of statement and body.
10113 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000010114 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010115 &StmtLineInvalid);
10116 if (StmtLineInvalid)
10117 return false;
10118
10119 bool BodyLineInvalid;
10120 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10121 &BodyLineInvalid);
10122 if (BodyLineInvalid)
10123 return false;
10124
10125 // Warn if null statement and body are on the same line.
10126 if (StmtLine != BodyLine)
10127 return false;
10128
10129 return true;
10130}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010131} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010132
10133void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10134 const Stmt *Body,
10135 unsigned DiagID) {
10136 // Since this is a syntactic check, don't emit diagnostic for template
10137 // instantiations, this just adds noise.
10138 if (CurrentInstantiationScope)
10139 return;
10140
10141 // The body should be a null statement.
10142 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10143 if (!NBody)
10144 return;
10145
10146 // Do the usual checks.
10147 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10148 return;
10149
10150 Diag(NBody->getSemiLoc(), DiagID);
10151 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10152}
10153
10154void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10155 const Stmt *PossibleBody) {
10156 assert(!CurrentInstantiationScope); // Ensured by caller
10157
10158 SourceLocation StmtLoc;
10159 const Stmt *Body;
10160 unsigned DiagID;
10161 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10162 StmtLoc = FS->getRParenLoc();
10163 Body = FS->getBody();
10164 DiagID = diag::warn_empty_for_body;
10165 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10166 StmtLoc = WS->getCond()->getSourceRange().getEnd();
10167 Body = WS->getBody();
10168 DiagID = diag::warn_empty_while_body;
10169 } else
10170 return; // Neither `for' nor `while'.
10171
10172 // The body should be a null statement.
10173 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10174 if (!NBody)
10175 return;
10176
10177 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010178 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010179 return;
10180
10181 // Do the usual checks.
10182 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10183 return;
10184
10185 // `for(...);' and `while(...);' are popular idioms, so in order to keep
10186 // noise level low, emit diagnostics only if for/while is followed by a
10187 // CompoundStmt, e.g.:
10188 // for (int i = 0; i < n; i++);
10189 // {
10190 // a(i);
10191 // }
10192 // or if for/while is followed by a statement with more indentation
10193 // than for/while itself:
10194 // for (int i = 0; i < n; i++);
10195 // a(i);
10196 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10197 if (!ProbableTypo) {
10198 bool BodyColInvalid;
10199 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10200 PossibleBody->getLocStart(),
10201 &BodyColInvalid);
10202 if (BodyColInvalid)
10203 return;
10204
10205 bool StmtColInvalid;
10206 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10207 S->getLocStart(),
10208 &StmtColInvalid);
10209 if (StmtColInvalid)
10210 return;
10211
10212 if (BodyCol > StmtCol)
10213 ProbableTypo = true;
10214 }
10215
10216 if (ProbableTypo) {
10217 Diag(NBody->getSemiLoc(), DiagID);
10218 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10219 }
10220}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010221
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010222//===--- CHECK: Warn on self move with std::move. -------------------------===//
10223
10224/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10225void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10226 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010227 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10228 return;
10229
10230 if (!ActiveTemplateInstantiations.empty())
10231 return;
10232
10233 // Strip parens and casts away.
10234 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10235 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10236
10237 // Check for a call expression
10238 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10239 if (!CE || CE->getNumArgs() != 1)
10240 return;
10241
10242 // Check for a call to std::move
10243 const FunctionDecl *FD = CE->getDirectCallee();
10244 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10245 !FD->getIdentifier()->isStr("move"))
10246 return;
10247
10248 // Get argument from std::move
10249 RHSExpr = CE->getArg(0);
10250
10251 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10252 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10253
10254 // Two DeclRefExpr's, check that the decls are the same.
10255 if (LHSDeclRef && RHSDeclRef) {
10256 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10257 return;
10258 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10259 RHSDeclRef->getDecl()->getCanonicalDecl())
10260 return;
10261
10262 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10263 << LHSExpr->getSourceRange()
10264 << RHSExpr->getSourceRange();
10265 return;
10266 }
10267
10268 // Member variables require a different approach to check for self moves.
10269 // MemberExpr's are the same if every nested MemberExpr refers to the same
10270 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10271 // the base Expr's are CXXThisExpr's.
10272 const Expr *LHSBase = LHSExpr;
10273 const Expr *RHSBase = RHSExpr;
10274 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10275 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10276 if (!LHSME || !RHSME)
10277 return;
10278
10279 while (LHSME && RHSME) {
10280 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10281 RHSME->getMemberDecl()->getCanonicalDecl())
10282 return;
10283
10284 LHSBase = LHSME->getBase();
10285 RHSBase = RHSME->getBase();
10286 LHSME = dyn_cast<MemberExpr>(LHSBase);
10287 RHSME = dyn_cast<MemberExpr>(RHSBase);
10288 }
10289
10290 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10291 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10292 if (LHSDeclRef && RHSDeclRef) {
10293 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10294 return;
10295 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10296 RHSDeclRef->getDecl()->getCanonicalDecl())
10297 return;
10298
10299 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10300 << LHSExpr->getSourceRange()
10301 << RHSExpr->getSourceRange();
10302 return;
10303 }
10304
10305 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10306 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10307 << LHSExpr->getSourceRange()
10308 << RHSExpr->getSourceRange();
10309}
10310
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010311//===--- Layout compatibility ----------------------------------------------//
10312
10313namespace {
10314
10315bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10316
10317/// \brief Check if two enumeration types are layout-compatible.
10318bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10319 // C++11 [dcl.enum] p8:
10320 // Two enumeration types are layout-compatible if they have the same
10321 // underlying type.
10322 return ED1->isComplete() && ED2->isComplete() &&
10323 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10324}
10325
10326/// \brief Check if two fields are layout-compatible.
10327bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10328 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10329 return false;
10330
10331 if (Field1->isBitField() != Field2->isBitField())
10332 return false;
10333
10334 if (Field1->isBitField()) {
10335 // Make sure that the bit-fields are the same length.
10336 unsigned Bits1 = Field1->getBitWidthValue(C);
10337 unsigned Bits2 = Field2->getBitWidthValue(C);
10338
10339 if (Bits1 != Bits2)
10340 return false;
10341 }
10342
10343 return true;
10344}
10345
10346/// \brief Check if two standard-layout structs are layout-compatible.
10347/// (C++11 [class.mem] p17)
10348bool isLayoutCompatibleStruct(ASTContext &C,
10349 RecordDecl *RD1,
10350 RecordDecl *RD2) {
10351 // If both records are C++ classes, check that base classes match.
10352 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10353 // If one of records is a CXXRecordDecl we are in C++ mode,
10354 // thus the other one is a CXXRecordDecl, too.
10355 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10356 // Check number of base classes.
10357 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10358 return false;
10359
10360 // Check the base classes.
10361 for (CXXRecordDecl::base_class_const_iterator
10362 Base1 = D1CXX->bases_begin(),
10363 BaseEnd1 = D1CXX->bases_end(),
10364 Base2 = D2CXX->bases_begin();
10365 Base1 != BaseEnd1;
10366 ++Base1, ++Base2) {
10367 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10368 return false;
10369 }
10370 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10371 // If only RD2 is a C++ class, it should have zero base classes.
10372 if (D2CXX->getNumBases() > 0)
10373 return false;
10374 }
10375
10376 // Check the fields.
10377 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10378 Field2End = RD2->field_end(),
10379 Field1 = RD1->field_begin(),
10380 Field1End = RD1->field_end();
10381 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10382 if (!isLayoutCompatible(C, *Field1, *Field2))
10383 return false;
10384 }
10385 if (Field1 != Field1End || Field2 != Field2End)
10386 return false;
10387
10388 return true;
10389}
10390
10391/// \brief Check if two standard-layout unions are layout-compatible.
10392/// (C++11 [class.mem] p18)
10393bool isLayoutCompatibleUnion(ASTContext &C,
10394 RecordDecl *RD1,
10395 RecordDecl *RD2) {
10396 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010397 for (auto *Field2 : RD2->fields())
10398 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010399
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010400 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010401 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10402 I = UnmatchedFields.begin(),
10403 E = UnmatchedFields.end();
10404
10405 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010406 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010407 bool Result = UnmatchedFields.erase(*I);
10408 (void) Result;
10409 assert(Result);
10410 break;
10411 }
10412 }
10413 if (I == E)
10414 return false;
10415 }
10416
10417 return UnmatchedFields.empty();
10418}
10419
10420bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10421 if (RD1->isUnion() != RD2->isUnion())
10422 return false;
10423
10424 if (RD1->isUnion())
10425 return isLayoutCompatibleUnion(C, RD1, RD2);
10426 else
10427 return isLayoutCompatibleStruct(C, RD1, RD2);
10428}
10429
10430/// \brief Check if two types are layout-compatible in C++11 sense.
10431bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10432 if (T1.isNull() || T2.isNull())
10433 return false;
10434
10435 // C++11 [basic.types] p11:
10436 // If two types T1 and T2 are the same type, then T1 and T2 are
10437 // layout-compatible types.
10438 if (C.hasSameType(T1, T2))
10439 return true;
10440
10441 T1 = T1.getCanonicalType().getUnqualifiedType();
10442 T2 = T2.getCanonicalType().getUnqualifiedType();
10443
10444 const Type::TypeClass TC1 = T1->getTypeClass();
10445 const Type::TypeClass TC2 = T2->getTypeClass();
10446
10447 if (TC1 != TC2)
10448 return false;
10449
10450 if (TC1 == Type::Enum) {
10451 return isLayoutCompatible(C,
10452 cast<EnumType>(T1)->getDecl(),
10453 cast<EnumType>(T2)->getDecl());
10454 } else if (TC1 == Type::Record) {
10455 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10456 return false;
10457
10458 return isLayoutCompatible(C,
10459 cast<RecordType>(T1)->getDecl(),
10460 cast<RecordType>(T2)->getDecl());
10461 }
10462
10463 return false;
10464}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010465} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010466
10467//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10468
10469namespace {
10470/// \brief Given a type tag expression find the type tag itself.
10471///
10472/// \param TypeExpr Type tag expression, as it appears in user's code.
10473///
10474/// \param VD Declaration of an identifier that appears in a type tag.
10475///
10476/// \param MagicValue Type tag magic value.
10477bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10478 const ValueDecl **VD, uint64_t *MagicValue) {
10479 while(true) {
10480 if (!TypeExpr)
10481 return false;
10482
10483 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10484
10485 switch (TypeExpr->getStmtClass()) {
10486 case Stmt::UnaryOperatorClass: {
10487 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10488 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10489 TypeExpr = UO->getSubExpr();
10490 continue;
10491 }
10492 return false;
10493 }
10494
10495 case Stmt::DeclRefExprClass: {
10496 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10497 *VD = DRE->getDecl();
10498 return true;
10499 }
10500
10501 case Stmt::IntegerLiteralClass: {
10502 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10503 llvm::APInt MagicValueAPInt = IL->getValue();
10504 if (MagicValueAPInt.getActiveBits() <= 64) {
10505 *MagicValue = MagicValueAPInt.getZExtValue();
10506 return true;
10507 } else
10508 return false;
10509 }
10510
10511 case Stmt::BinaryConditionalOperatorClass:
10512 case Stmt::ConditionalOperatorClass: {
10513 const AbstractConditionalOperator *ACO =
10514 cast<AbstractConditionalOperator>(TypeExpr);
10515 bool Result;
10516 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10517 if (Result)
10518 TypeExpr = ACO->getTrueExpr();
10519 else
10520 TypeExpr = ACO->getFalseExpr();
10521 continue;
10522 }
10523 return false;
10524 }
10525
10526 case Stmt::BinaryOperatorClass: {
10527 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10528 if (BO->getOpcode() == BO_Comma) {
10529 TypeExpr = BO->getRHS();
10530 continue;
10531 }
10532 return false;
10533 }
10534
10535 default:
10536 return false;
10537 }
10538 }
10539}
10540
10541/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10542///
10543/// \param TypeExpr Expression that specifies a type tag.
10544///
10545/// \param MagicValues Registered magic values.
10546///
10547/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10548/// kind.
10549///
10550/// \param TypeInfo Information about the corresponding C type.
10551///
10552/// \returns true if the corresponding C type was found.
10553bool GetMatchingCType(
10554 const IdentifierInfo *ArgumentKind,
10555 const Expr *TypeExpr, const ASTContext &Ctx,
10556 const llvm::DenseMap<Sema::TypeTagMagicValue,
10557 Sema::TypeTagData> *MagicValues,
10558 bool &FoundWrongKind,
10559 Sema::TypeTagData &TypeInfo) {
10560 FoundWrongKind = false;
10561
10562 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010563 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010564
10565 uint64_t MagicValue;
10566
10567 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10568 return false;
10569
10570 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010571 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010572 if (I->getArgumentKind() != ArgumentKind) {
10573 FoundWrongKind = true;
10574 return false;
10575 }
10576 TypeInfo.Type = I->getMatchingCType();
10577 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10578 TypeInfo.MustBeNull = I->getMustBeNull();
10579 return true;
10580 }
10581 return false;
10582 }
10583
10584 if (!MagicValues)
10585 return false;
10586
10587 llvm::DenseMap<Sema::TypeTagMagicValue,
10588 Sema::TypeTagData>::const_iterator I =
10589 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10590 if (I == MagicValues->end())
10591 return false;
10592
10593 TypeInfo = I->second;
10594 return true;
10595}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010596} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010597
10598void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10599 uint64_t MagicValue, QualType Type,
10600 bool LayoutCompatible,
10601 bool MustBeNull) {
10602 if (!TypeTagForDatatypeMagicValues)
10603 TypeTagForDatatypeMagicValues.reset(
10604 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10605
10606 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10607 (*TypeTagForDatatypeMagicValues)[Magic] =
10608 TypeTagData(Type, LayoutCompatible, MustBeNull);
10609}
10610
10611namespace {
10612bool IsSameCharType(QualType T1, QualType T2) {
10613 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10614 if (!BT1)
10615 return false;
10616
10617 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10618 if (!BT2)
10619 return false;
10620
10621 BuiltinType::Kind T1Kind = BT1->getKind();
10622 BuiltinType::Kind T2Kind = BT2->getKind();
10623
10624 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10625 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10626 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10627 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10628}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010629} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010630
10631void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10632 const Expr * const *ExprArgs) {
10633 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10634 bool IsPointerAttr = Attr->getIsPointer();
10635
10636 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10637 bool FoundWrongKind;
10638 TypeTagData TypeInfo;
10639 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10640 TypeTagForDatatypeMagicValues.get(),
10641 FoundWrongKind, TypeInfo)) {
10642 if (FoundWrongKind)
10643 Diag(TypeTagExpr->getExprLoc(),
10644 diag::warn_type_tag_for_datatype_wrong_kind)
10645 << TypeTagExpr->getSourceRange();
10646 return;
10647 }
10648
10649 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10650 if (IsPointerAttr) {
10651 // Skip implicit cast of pointer to `void *' (as a function argument).
10652 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010653 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010654 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010655 ArgumentExpr = ICE->getSubExpr();
10656 }
10657 QualType ArgumentType = ArgumentExpr->getType();
10658
10659 // Passing a `void*' pointer shouldn't trigger a warning.
10660 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10661 return;
10662
10663 if (TypeInfo.MustBeNull) {
10664 // Type tag with matching void type requires a null pointer.
10665 if (!ArgumentExpr->isNullPointerConstant(Context,
10666 Expr::NPC_ValueDependentIsNotNull)) {
10667 Diag(ArgumentExpr->getExprLoc(),
10668 diag::warn_type_safety_null_pointer_required)
10669 << ArgumentKind->getName()
10670 << ArgumentExpr->getSourceRange()
10671 << TypeTagExpr->getSourceRange();
10672 }
10673 return;
10674 }
10675
10676 QualType RequiredType = TypeInfo.Type;
10677 if (IsPointerAttr)
10678 RequiredType = Context.getPointerType(RequiredType);
10679
10680 bool mismatch = false;
10681 if (!TypeInfo.LayoutCompatible) {
10682 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10683
10684 // C++11 [basic.fundamental] p1:
10685 // Plain char, signed char, and unsigned char are three distinct types.
10686 //
10687 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10688 // char' depending on the current char signedness mode.
10689 if (mismatch)
10690 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10691 RequiredType->getPointeeType())) ||
10692 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10693 mismatch = false;
10694 } else
10695 if (IsPointerAttr)
10696 mismatch = !isLayoutCompatible(Context,
10697 ArgumentType->getPointeeType(),
10698 RequiredType->getPointeeType());
10699 else
10700 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10701
10702 if (mismatch)
10703 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010704 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010705 << TypeInfo.LayoutCompatible << RequiredType
10706 << ArgumentExpr->getSourceRange()
10707 << TypeTagExpr->getSourceRange();
10708}