blob: 134248dbe22571c1f4c167e0a268ad025571b6fa [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000024#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000025#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000028#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000031#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000039#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000041#include <limits>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000042
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000044using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000045
Chris Lattnera26fb342009-02-18 17:49:48 +000046SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
47 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000048 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
49 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000050}
51
John McCallbebede42011-02-26 05:39:39 +000052/// Checks that a call expression's argument count is the desired number.
53/// This is useful when doing custom type-checking. Returns true on error.
54static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
55 unsigned argCount = call->getNumArgs();
56 if (argCount == desiredArgCount) return false;
57
58 if (argCount < desiredArgCount)
59 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
60 << 0 /*function call*/ << desiredArgCount << argCount
61 << call->getSourceRange();
62
63 // Highlight all the excess arguments.
64 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
65 call->getArg(argCount - 1)->getLocEnd());
66
67 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
68 << 0 /*function call*/ << desiredArgCount << argCount
69 << call->getArg(1)->getSourceRange();
70}
71
Julien Lerouge4a5b4442012-04-28 17:39:16 +000072/// Check that the first argument to __builtin_annotation is an integer
73/// and the second argument is a non-wide string literal.
74static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
75 if (checkArgCount(S, TheCall, 2))
76 return true;
77
78 // First argument should be an integer.
79 Expr *ValArg = TheCall->getArg(0);
80 QualType Ty = ValArg->getType();
81 if (!Ty->isIntegerType()) {
82 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
83 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000084 return true;
85 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000086
87 // Second argument should be a constant string.
88 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
89 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
90 if (!Literal || !Literal->isAscii()) {
91 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
92 << StrArg->getSourceRange();
93 return true;
94 }
95
96 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000097 return false;
98}
99
Richard Smith6cbd65d2013-07-11 02:27:57 +0000100/// Check that the argument to __builtin_addressof is a glvalue, and set the
101/// result type to the corresponding pointer type.
102static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
103 if (checkArgCount(S, TheCall, 1))
104 return true;
105
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000106 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000107 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
108 if (ResultType.isNull())
109 return true;
110
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000111 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000112 TheCall->setType(ResultType);
113 return false;
114}
115
John McCall03107a42015-10-29 20:48:01 +0000116static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
117 if (checkArgCount(S, TheCall, 3))
118 return true;
119
120 // First two arguments should be integers.
121 for (unsigned I = 0; I < 2; ++I) {
122 Expr *Arg = TheCall->getArg(I);
123 QualType Ty = Arg->getType();
124 if (!Ty->isIntegerType()) {
125 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
126 << Ty << Arg->getSourceRange();
127 return true;
128 }
129 }
130
131 // Third argument should be a pointer to a non-const integer.
132 // IRGen correctly handles volatile, restrict, and address spaces, and
133 // the other qualifiers aren't possible.
134 {
135 Expr *Arg = TheCall->getArg(2);
136 QualType Ty = Arg->getType();
137 const auto *PtrTy = Ty->getAs<PointerType>();
138 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
139 !PtrTy->getPointeeType().isConstQualified())) {
140 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
141 << Ty << Arg->getSourceRange();
142 return true;
143 }
144 }
145
146 return false;
147}
148
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000149static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
150 CallExpr *TheCall, unsigned SizeIdx,
151 unsigned DstSizeIdx) {
152 if (TheCall->getNumArgs() <= SizeIdx ||
153 TheCall->getNumArgs() <= DstSizeIdx)
154 return;
155
156 const Expr *SizeArg = TheCall->getArg(SizeIdx);
157 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
158
159 llvm::APSInt Size, DstSize;
160
161 // find out if both sizes are known at compile time
162 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
163 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
164 return;
165
166 if (Size.ule(DstSize))
167 return;
168
169 // confirmed overflow so generate the diagnostic.
170 IdentifierInfo *FnName = FDecl->getIdentifier();
171 SourceLocation SL = TheCall->getLocStart();
172 SourceRange SR = TheCall->getSourceRange();
173
174 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
175}
176
Peter Collingbournef7706832014-12-12 23:41:25 +0000177static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
178 if (checkArgCount(S, BuiltinCall, 2))
179 return true;
180
181 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
182 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
183 Expr *Call = BuiltinCall->getArg(0);
184 Expr *Chain = BuiltinCall->getArg(1);
185
186 if (Call->getStmtClass() != Stmt::CallExprClass) {
187 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
188 << Call->getSourceRange();
189 return true;
190 }
191
192 auto CE = cast<CallExpr>(Call);
193 if (CE->getCallee()->getType()->isBlockPointerType()) {
194 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
195 << Call->getSourceRange();
196 return true;
197 }
198
199 const Decl *TargetDecl = CE->getCalleeDecl();
200 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
201 if (FD->getBuiltinID()) {
202 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
203 << Call->getSourceRange();
204 return true;
205 }
206
207 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
208 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
209 << Call->getSourceRange();
210 return true;
211 }
212
213 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
214 if (ChainResult.isInvalid())
215 return true;
216 if (!ChainResult.get()->getType()->isPointerType()) {
217 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
218 << Chain->getSourceRange();
219 return true;
220 }
221
David Majnemerced8bdf2015-02-25 17:36:15 +0000222 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000223 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
224 QualType BuiltinTy = S.Context.getFunctionType(
225 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
226 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
227
228 Builtin =
229 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
230
231 BuiltinCall->setType(CE->getType());
232 BuiltinCall->setValueKind(CE->getValueKind());
233 BuiltinCall->setObjectKind(CE->getObjectKind());
234 BuiltinCall->setCallee(Builtin);
235 BuiltinCall->setArg(1, ChainResult.get());
236
237 return false;
238}
239
Reid Kleckner1d59f992015-01-22 01:36:17 +0000240static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
241 Scope::ScopeFlags NeededScopeFlags,
242 unsigned DiagID) {
243 // Scopes aren't available during instantiation. Fortunately, builtin
244 // functions cannot be template args so they cannot be formed through template
245 // instantiation. Therefore checking once during the parse is sufficient.
246 if (!SemaRef.ActiveTemplateInstantiations.empty())
247 return false;
248
249 Scope *S = SemaRef.getCurScope();
250 while (S && !S->isSEHExceptScope())
251 S = S->getParent();
252 if (!S || !(S->getFlags() & NeededScopeFlags)) {
253 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
254 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
255 << DRE->getDecl()->getIdentifier();
256 return true;
257 }
258
259 return false;
260}
261
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000262/// Returns readable name for a call.
263static StringRef getFunctionName(CallExpr *Call) {
264 return cast<FunctionDecl>(Call->getCalleeDecl())->getName();
265}
266
267/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000268static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
269 if (D->hasAttr<OpenCLAccessAttr>())
270 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000271 return nullptr;
272}
273
274/// Returns true if pipe element type is different from the pointer.
275static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
276 const Expr *Arg0 = Call->getArg(0);
277 // First argument type should always be pipe.
278 if (!Arg0->getType()->isPipeType()) {
279 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
280 << getFunctionName(Call) << Arg0->getSourceRange();
281 return true;
282 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000283 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000284 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
285 // Validates the access qualifier is compatible with the call.
286 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
287 // read_only and write_only, and assumed to be read_only if no qualifier is
288 // specified.
289 bool isValid = true;
290 bool ReadOnly = getFunctionName(Call).find("read") != StringRef::npos;
291 if (ReadOnly)
292 isValid = AccessQual == nullptr || AccessQual->isReadOnly();
293 else
294 isValid = AccessQual != nullptr && AccessQual->isWriteOnly();
295 if (!isValid) {
296 const char *AM = ReadOnly ? "read_only" : "write_only";
297 S.Diag(Arg0->getLocStart(),
298 diag::err_opencl_builtin_pipe_invalid_access_modifier)
299 << AM << Arg0->getSourceRange();
300 return true;
301 }
302
303 return false;
304}
305
306/// Returns true if pipe element type is different from the pointer.
307static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
308 const Expr *Arg0 = Call->getArg(0);
309 const Expr *ArgIdx = Call->getArg(Idx);
310 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
311 const Type *EltTy = PipeTy->getElementType().getTypePtr();
312 const PointerType *ArgTy =
313 dyn_cast<PointerType>(ArgIdx->getType().getTypePtr());
314 // The Idx argument should be a pointer and the type of the pointer and
315 // the type of pipe element should also be the same.
316 if (!ArgTy || EltTy != ArgTy->getPointeeType().getTypePtr()) {
317 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
318 << getFunctionName(Call)
319 << S.Context.getPointerType(PipeTy->getElementType())
320 << ArgIdx->getSourceRange();
321 return true;
322 }
323 return false;
324}
325
326// \brief Performs semantic analysis for the read/write_pipe call.
327// \param S Reference to the semantic analyzer.
328// \param Call A pointer to the builtin call.
329// \return True if a semantic error has been found, false otherwise.
330static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
331 // Two kinds of read/write pipe
332 // From OpenCL C Specification 6.13.16.2 the built-in read/write
333 // functions have following forms.
334 switch (Call->getNumArgs()) {
335 case 2: {
336 if (checkOpenCLPipeArg(S, Call))
337 return true;
338 // The call with 2 arguments should be
339 // read/write_pipe(pipe T, T*)
340 // check packet type T
341 if (checkOpenCLPipePacketType(S, Call, 1))
342 return true;
343 } break;
344
345 case 4: {
346 if (checkOpenCLPipeArg(S, Call))
347 return true;
348 // The call with 4 arguments should be
349 // read/write_pipe(pipe T, reserve_id_t, uint, T*)
350 // check reserve_id_t
351 if (!Call->getArg(1)->getType()->isReserveIDT()) {
352 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
353 << getFunctionName(Call) << S.Context.OCLReserveIDTy
354 << Call->getArg(1)->getSourceRange();
355 return true;
356 }
357
358 // check the index
359 const Expr *Arg2 = Call->getArg(2);
360 if (!Arg2->getType()->isIntegerType() &&
361 !Arg2->getType()->isUnsignedIntegerType()) {
362 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
363 << getFunctionName(Call) << S.Context.UnsignedIntTy
364 << Arg2->getSourceRange();
365 return true;
366 }
367
368 // check packet type T
369 if (checkOpenCLPipePacketType(S, Call, 3))
370 return true;
371 } break;
372 default:
373 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
374 << getFunctionName(Call) << Call->getSourceRange();
375 return true;
376 }
377
378 return false;
379}
380
381// \brief Performs a semantic analysis on the {work_group_/sub_group_
382// /_}reserve_{read/write}_pipe
383// \param S Reference to the semantic analyzer.
384// \param Call The call to the builtin function to be analyzed.
385// \return True if a semantic error was found, false otherwise.
386static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
387 if (checkArgCount(S, Call, 2))
388 return true;
389
390 if (checkOpenCLPipeArg(S, Call))
391 return true;
392
393 // check the reserve size
394 if (!Call->getArg(1)->getType()->isIntegerType() &&
395 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
396 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
397 << getFunctionName(Call) << S.Context.UnsignedIntTy
398 << Call->getArg(1)->getSourceRange();
399 return true;
400 }
401
402 return false;
403}
404
405// \brief Performs a semantic analysis on {work_group_/sub_group_
406// /_}commit_{read/write}_pipe
407// \param S Reference to the semantic analyzer.
408// \param Call The call to the builtin function to be analyzed.
409// \return True if a semantic error was found, false otherwise.
410static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
411 if (checkArgCount(S, Call, 2))
412 return true;
413
414 if (checkOpenCLPipeArg(S, Call))
415 return true;
416
417 // check reserve_id_t
418 if (!Call->getArg(1)->getType()->isReserveIDT()) {
419 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
420 << getFunctionName(Call) << S.Context.OCLReserveIDTy
421 << Call->getArg(1)->getSourceRange();
422 return true;
423 }
424
425 return false;
426}
427
428// \brief Performs a semantic analysis on the call to built-in Pipe
429// Query Functions.
430// \param S Reference to the semantic analyzer.
431// \param Call The call to the builtin function to be analyzed.
432// \return True if a semantic error was found, false otherwise.
433static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
434 if (checkArgCount(S, Call, 1))
435 return true;
436
437 if (!Call->getArg(0)->getType()->isPipeType()) {
438 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
439 << getFunctionName(Call) << Call->getArg(0)->getSourceRange();
440 return true;
441 }
442
443 return false;
444}
445
John McCalldadc5752010-08-24 06:29:42 +0000446ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000447Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
448 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000449 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000450
Chris Lattner3be167f2010-10-01 23:23:24 +0000451 // Find out if any arguments are required to be integer constant expressions.
452 unsigned ICEArguments = 0;
453 ASTContext::GetBuiltinTypeError Error;
454 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
455 if (Error != ASTContext::GE_None)
456 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
457
458 // If any arguments are required to be ICE's, check and diagnose.
459 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
460 // Skip arguments not required to be ICE's.
461 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
462
463 llvm::APSInt Result;
464 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
465 return true;
466 ICEArguments &= ~(1 << ArgNo);
467 }
468
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000469 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000470 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000471 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000472 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000473 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000474 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000475 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000476 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000477 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000478 if (SemaBuiltinVAStart(TheCall))
479 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000480 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000481 case Builtin::BI__va_start: {
482 switch (Context.getTargetInfo().getTriple().getArch()) {
483 case llvm::Triple::arm:
484 case llvm::Triple::thumb:
485 if (SemaBuiltinVAStartARM(TheCall))
486 return ExprError();
487 break;
488 default:
489 if (SemaBuiltinVAStart(TheCall))
490 return ExprError();
491 break;
492 }
493 break;
494 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000495 case Builtin::BI__builtin_isgreater:
496 case Builtin::BI__builtin_isgreaterequal:
497 case Builtin::BI__builtin_isless:
498 case Builtin::BI__builtin_islessequal:
499 case Builtin::BI__builtin_islessgreater:
500 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000501 if (SemaBuiltinUnorderedCompare(TheCall))
502 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000503 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000504 case Builtin::BI__builtin_fpclassify:
505 if (SemaBuiltinFPClassification(TheCall, 6))
506 return ExprError();
507 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000508 case Builtin::BI__builtin_isfinite:
509 case Builtin::BI__builtin_isinf:
510 case Builtin::BI__builtin_isinf_sign:
511 case Builtin::BI__builtin_isnan:
512 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000513 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000514 return ExprError();
515 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000516 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000517 return SemaBuiltinShuffleVector(TheCall);
518 // TheCall will be freed by the smart pointer here, but that's fine, since
519 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000520 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000521 if (SemaBuiltinPrefetch(TheCall))
522 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000523 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000524 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000525 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000526 if (SemaBuiltinAssume(TheCall))
527 return ExprError();
528 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000529 case Builtin::BI__builtin_assume_aligned:
530 if (SemaBuiltinAssumeAligned(TheCall))
531 return ExprError();
532 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000533 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000534 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000535 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000536 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000537 case Builtin::BI__builtin_longjmp:
538 if (SemaBuiltinLongjmp(TheCall))
539 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000540 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000541 case Builtin::BI__builtin_setjmp:
542 if (SemaBuiltinSetjmp(TheCall))
543 return ExprError();
544 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000545 case Builtin::BI_setjmp:
546 case Builtin::BI_setjmpex:
547 if (checkArgCount(*this, TheCall, 1))
548 return true;
549 break;
John McCallbebede42011-02-26 05:39:39 +0000550
551 case Builtin::BI__builtin_classify_type:
552 if (checkArgCount(*this, TheCall, 1)) return true;
553 TheCall->setType(Context.IntTy);
554 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000555 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000556 if (checkArgCount(*this, TheCall, 1)) return true;
557 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000558 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000559 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000560 case Builtin::BI__sync_fetch_and_add_1:
561 case Builtin::BI__sync_fetch_and_add_2:
562 case Builtin::BI__sync_fetch_and_add_4:
563 case Builtin::BI__sync_fetch_and_add_8:
564 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000565 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000566 case Builtin::BI__sync_fetch_and_sub_1:
567 case Builtin::BI__sync_fetch_and_sub_2:
568 case Builtin::BI__sync_fetch_and_sub_4:
569 case Builtin::BI__sync_fetch_and_sub_8:
570 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000571 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000572 case Builtin::BI__sync_fetch_and_or_1:
573 case Builtin::BI__sync_fetch_and_or_2:
574 case Builtin::BI__sync_fetch_and_or_4:
575 case Builtin::BI__sync_fetch_and_or_8:
576 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000577 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000578 case Builtin::BI__sync_fetch_and_and_1:
579 case Builtin::BI__sync_fetch_and_and_2:
580 case Builtin::BI__sync_fetch_and_and_4:
581 case Builtin::BI__sync_fetch_and_and_8:
582 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000583 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000584 case Builtin::BI__sync_fetch_and_xor_1:
585 case Builtin::BI__sync_fetch_and_xor_2:
586 case Builtin::BI__sync_fetch_and_xor_4:
587 case Builtin::BI__sync_fetch_and_xor_8:
588 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000589 case Builtin::BI__sync_fetch_and_nand:
590 case Builtin::BI__sync_fetch_and_nand_1:
591 case Builtin::BI__sync_fetch_and_nand_2:
592 case Builtin::BI__sync_fetch_and_nand_4:
593 case Builtin::BI__sync_fetch_and_nand_8:
594 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000595 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000596 case Builtin::BI__sync_add_and_fetch_1:
597 case Builtin::BI__sync_add_and_fetch_2:
598 case Builtin::BI__sync_add_and_fetch_4:
599 case Builtin::BI__sync_add_and_fetch_8:
600 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000601 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000602 case Builtin::BI__sync_sub_and_fetch_1:
603 case Builtin::BI__sync_sub_and_fetch_2:
604 case Builtin::BI__sync_sub_and_fetch_4:
605 case Builtin::BI__sync_sub_and_fetch_8:
606 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000607 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000608 case Builtin::BI__sync_and_and_fetch_1:
609 case Builtin::BI__sync_and_and_fetch_2:
610 case Builtin::BI__sync_and_and_fetch_4:
611 case Builtin::BI__sync_and_and_fetch_8:
612 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000613 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000614 case Builtin::BI__sync_or_and_fetch_1:
615 case Builtin::BI__sync_or_and_fetch_2:
616 case Builtin::BI__sync_or_and_fetch_4:
617 case Builtin::BI__sync_or_and_fetch_8:
618 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000619 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000620 case Builtin::BI__sync_xor_and_fetch_1:
621 case Builtin::BI__sync_xor_and_fetch_2:
622 case Builtin::BI__sync_xor_and_fetch_4:
623 case Builtin::BI__sync_xor_and_fetch_8:
624 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000625 case Builtin::BI__sync_nand_and_fetch:
626 case Builtin::BI__sync_nand_and_fetch_1:
627 case Builtin::BI__sync_nand_and_fetch_2:
628 case Builtin::BI__sync_nand_and_fetch_4:
629 case Builtin::BI__sync_nand_and_fetch_8:
630 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000631 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000632 case Builtin::BI__sync_val_compare_and_swap_1:
633 case Builtin::BI__sync_val_compare_and_swap_2:
634 case Builtin::BI__sync_val_compare_and_swap_4:
635 case Builtin::BI__sync_val_compare_and_swap_8:
636 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000637 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000638 case Builtin::BI__sync_bool_compare_and_swap_1:
639 case Builtin::BI__sync_bool_compare_and_swap_2:
640 case Builtin::BI__sync_bool_compare_and_swap_4:
641 case Builtin::BI__sync_bool_compare_and_swap_8:
642 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000643 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000644 case Builtin::BI__sync_lock_test_and_set_1:
645 case Builtin::BI__sync_lock_test_and_set_2:
646 case Builtin::BI__sync_lock_test_and_set_4:
647 case Builtin::BI__sync_lock_test_and_set_8:
648 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000649 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000650 case Builtin::BI__sync_lock_release_1:
651 case Builtin::BI__sync_lock_release_2:
652 case Builtin::BI__sync_lock_release_4:
653 case Builtin::BI__sync_lock_release_8:
654 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000655 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000656 case Builtin::BI__sync_swap_1:
657 case Builtin::BI__sync_swap_2:
658 case Builtin::BI__sync_swap_4:
659 case Builtin::BI__sync_swap_8:
660 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000661 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000662 case Builtin::BI__builtin_nontemporal_load:
663 case Builtin::BI__builtin_nontemporal_store:
664 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000665#define BUILTIN(ID, TYPE, ATTRS)
666#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
667 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000668 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000669#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000670 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000671 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000672 return ExprError();
673 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000674 case Builtin::BI__builtin_addressof:
675 if (SemaBuiltinAddressof(*this, TheCall))
676 return ExprError();
677 break;
John McCall03107a42015-10-29 20:48:01 +0000678 case Builtin::BI__builtin_add_overflow:
679 case Builtin::BI__builtin_sub_overflow:
680 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000681 if (SemaBuiltinOverflow(*this, TheCall))
682 return ExprError();
683 break;
Richard Smith760520b2014-06-03 23:27:44 +0000684 case Builtin::BI__builtin_operator_new:
685 case Builtin::BI__builtin_operator_delete:
686 if (!getLangOpts().CPlusPlus) {
687 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
688 << (BuiltinID == Builtin::BI__builtin_operator_new
689 ? "__builtin_operator_new"
690 : "__builtin_operator_delete")
691 << "C++";
692 return ExprError();
693 }
694 // CodeGen assumes it can find the global new and delete to call,
695 // so ensure that they are declared.
696 DeclareGlobalNewDelete();
697 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000698
699 // check secure string manipulation functions where overflows
700 // are detectable at compile time
701 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000702 case Builtin::BI__builtin___memmove_chk:
703 case Builtin::BI__builtin___memset_chk:
704 case Builtin::BI__builtin___strlcat_chk:
705 case Builtin::BI__builtin___strlcpy_chk:
706 case Builtin::BI__builtin___strncat_chk:
707 case Builtin::BI__builtin___strncpy_chk:
708 case Builtin::BI__builtin___stpncpy_chk:
709 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
710 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000711 case Builtin::BI__builtin___memccpy_chk:
712 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
713 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000714 case Builtin::BI__builtin___snprintf_chk:
715 case Builtin::BI__builtin___vsnprintf_chk:
716 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
717 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000718 case Builtin::BI__builtin_call_with_static_chain:
719 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
720 return ExprError();
721 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000722 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000723 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000724 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
725 diag::err_seh___except_block))
726 return ExprError();
727 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000728 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000729 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000730 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
731 diag::err_seh___except_filter))
732 return ExprError();
733 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +0000734 case Builtin::BI__GetExceptionInfo:
735 if (checkArgCount(*this, TheCall, 1))
736 return ExprError();
737
738 if (CheckCXXThrowOperand(
739 TheCall->getLocStart(),
740 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
741 TheCall))
742 return ExprError();
743
744 TheCall->setType(Context.VoidPtrTy);
745 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000746 case Builtin::BIread_pipe:
747 case Builtin::BIwrite_pipe:
748 // Since those two functions are declared with var args, we need a semantic
749 // check for the argument.
750 if (SemaBuiltinRWPipe(*this, TheCall))
751 return ExprError();
752 break;
753 case Builtin::BIreserve_read_pipe:
754 case Builtin::BIreserve_write_pipe:
755 case Builtin::BIwork_group_reserve_read_pipe:
756 case Builtin::BIwork_group_reserve_write_pipe:
757 case Builtin::BIsub_group_reserve_read_pipe:
758 case Builtin::BIsub_group_reserve_write_pipe:
759 if (SemaBuiltinReserveRWPipe(*this, TheCall))
760 return ExprError();
761 // Since return type of reserve_read/write_pipe built-in function is
762 // reserve_id_t, which is not defined in the builtin def file , we used int
763 // as return type and need to override the return type of these functions.
764 TheCall->setType(Context.OCLReserveIDTy);
765 break;
766 case Builtin::BIcommit_read_pipe:
767 case Builtin::BIcommit_write_pipe:
768 case Builtin::BIwork_group_commit_read_pipe:
769 case Builtin::BIwork_group_commit_write_pipe:
770 case Builtin::BIsub_group_commit_read_pipe:
771 case Builtin::BIsub_group_commit_write_pipe:
772 if (SemaBuiltinCommitRWPipe(*this, TheCall))
773 return ExprError();
774 break;
775 case Builtin::BIget_pipe_num_packets:
776 case Builtin::BIget_pipe_max_packets:
777 if (SemaBuiltinPipePackets(*this, TheCall))
778 return ExprError();
779 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000780 }
Richard Smith760520b2014-06-03 23:27:44 +0000781
Nate Begeman4904e322010-06-08 02:47:44 +0000782 // Since the target specific builtins for each arch overlap, only check those
783 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +0000784 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000785 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000786 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000787 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000788 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000789 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000790 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
791 return ExprError();
792 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000793 case llvm::Triple::aarch64:
794 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000795 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000796 return ExprError();
797 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000798 case llvm::Triple::mips:
799 case llvm::Triple::mipsel:
800 case llvm::Triple::mips64:
801 case llvm::Triple::mips64el:
802 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
803 return ExprError();
804 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000805 case llvm::Triple::systemz:
806 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
807 return ExprError();
808 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000809 case llvm::Triple::x86:
810 case llvm::Triple::x86_64:
811 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
812 return ExprError();
813 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000814 case llvm::Triple::ppc:
815 case llvm::Triple::ppc64:
816 case llvm::Triple::ppc64le:
817 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
818 return ExprError();
819 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000820 default:
821 break;
822 }
823 }
824
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000825 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000826}
827
Nate Begeman91e1fea2010-06-14 05:21:25 +0000828// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000829static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000830 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000831 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000832 switch (Type.getEltType()) {
833 case NeonTypeFlags::Int8:
834 case NeonTypeFlags::Poly8:
835 return shift ? 7 : (8 << IsQuad) - 1;
836 case NeonTypeFlags::Int16:
837 case NeonTypeFlags::Poly16:
838 return shift ? 15 : (4 << IsQuad) - 1;
839 case NeonTypeFlags::Int32:
840 return shift ? 31 : (2 << IsQuad) - 1;
841 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000842 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000843 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000844 case NeonTypeFlags::Poly128:
845 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000846 case NeonTypeFlags::Float16:
847 assert(!shift && "cannot shift float types!");
848 return (4 << IsQuad) - 1;
849 case NeonTypeFlags::Float32:
850 assert(!shift && "cannot shift float types!");
851 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000852 case NeonTypeFlags::Float64:
853 assert(!shift && "cannot shift float types!");
854 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000855 }
David Blaikie8a40f702012-01-17 06:56:22 +0000856 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000857}
858
Bob Wilsone4d77232011-11-08 05:04:11 +0000859/// getNeonEltType - Return the QualType corresponding to the elements of
860/// the vector type specified by the NeonTypeFlags. This is used to check
861/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000862static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000863 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000864 switch (Flags.getEltType()) {
865 case NeonTypeFlags::Int8:
866 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
867 case NeonTypeFlags::Int16:
868 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
869 case NeonTypeFlags::Int32:
870 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
871 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000872 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000873 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
874 else
875 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
876 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000877 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000878 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000879 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000880 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000881 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000882 if (IsInt64Long)
883 return Context.UnsignedLongTy;
884 else
885 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000886 case NeonTypeFlags::Poly128:
887 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000888 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000889 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000890 case NeonTypeFlags::Float32:
891 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000892 case NeonTypeFlags::Float64:
893 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000894 }
David Blaikie8a40f702012-01-17 06:56:22 +0000895 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000896}
897
Tim Northover12670412014-02-19 10:37:05 +0000898bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000899 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000900 uint64_t mask = 0;
901 unsigned TV = 0;
902 int PtrArgNum = -1;
903 bool HasConstPtr = false;
904 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000905#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000906#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000907#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000908 }
909
910 // For NEON intrinsics which are overloaded on vector element type, validate
911 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000912 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000913 if (mask) {
914 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
915 return true;
916
917 TV = Result.getLimitedValue(64);
918 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
919 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000920 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000921 }
922
923 if (PtrArgNum >= 0) {
924 // Check that pointer arguments have the specified type.
925 Expr *Arg = TheCall->getArg(PtrArgNum);
926 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
927 Arg = ICE->getSubExpr();
928 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
929 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000930
Tim Northovera2ee4332014-03-29 15:09:45 +0000931 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000932 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000933 bool IsInt64Long =
934 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
935 QualType EltTy =
936 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000937 if (HasConstPtr)
938 EltTy = EltTy.withConst();
939 QualType LHSTy = Context.getPointerType(EltTy);
940 AssignConvertType ConvTy;
941 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
942 if (RHS.isInvalid())
943 return true;
944 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
945 RHS.get(), AA_Assigning))
946 return true;
947 }
948
949 // For NEON intrinsics which take an immediate value as part of the
950 // instruction, range check them here.
951 unsigned i = 0, l = 0, u = 0;
952 switch (BuiltinID) {
953 default:
954 return false;
Tim Northover12670412014-02-19 10:37:05 +0000955#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000956#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000957#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000958 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000959
Richard Sandiford28940af2014-04-16 08:47:51 +0000960 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000961}
962
Tim Northovera2ee4332014-03-29 15:09:45 +0000963bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
964 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000965 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000966 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000967 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000968 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000969 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000970 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
971 BuiltinID == AArch64::BI__builtin_arm_strex ||
972 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000973 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000974 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000975 BuiltinID == ARM::BI__builtin_arm_ldaex ||
976 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
977 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000978
979 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
980
981 // Ensure that we have the proper number of arguments.
982 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
983 return true;
984
985 // Inspect the pointer argument of the atomic builtin. This should always be
986 // a pointer type, whose element is an integral scalar or pointer type.
987 // Because it is a pointer type, we don't have to worry about any implicit
988 // casts here.
989 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
990 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
991 if (PointerArgRes.isInvalid())
992 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000993 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000994
995 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
996 if (!pointerType) {
997 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
998 << PointerArg->getType() << PointerArg->getSourceRange();
999 return true;
1000 }
1001
1002 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1003 // task is to insert the appropriate casts into the AST. First work out just
1004 // what the appropriate type is.
1005 QualType ValType = pointerType->getPointeeType();
1006 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1007 if (IsLdrex)
1008 AddrType.addConst();
1009
1010 // Issue a warning if the cast is dodgy.
1011 CastKind CastNeeded = CK_NoOp;
1012 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1013 CastNeeded = CK_BitCast;
1014 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1015 << PointerArg->getType()
1016 << Context.getPointerType(AddrType)
1017 << AA_Passing << PointerArg->getSourceRange();
1018 }
1019
1020 // Finally, do the cast and replace the argument with the corrected version.
1021 AddrType = Context.getPointerType(AddrType);
1022 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1023 if (PointerArgRes.isInvalid())
1024 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001025 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001026
1027 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1028
1029 // In general, we allow ints, floats and pointers to be loaded and stored.
1030 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1031 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1032 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1033 << PointerArg->getType() << PointerArg->getSourceRange();
1034 return true;
1035 }
1036
1037 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001038 if (Context.getTypeSize(ValType) > MaxWidth) {
1039 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001040 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1041 << PointerArg->getType() << PointerArg->getSourceRange();
1042 return true;
1043 }
1044
1045 switch (ValType.getObjCLifetime()) {
1046 case Qualifiers::OCL_None:
1047 case Qualifiers::OCL_ExplicitNone:
1048 // okay
1049 break;
1050
1051 case Qualifiers::OCL_Weak:
1052 case Qualifiers::OCL_Strong:
1053 case Qualifiers::OCL_Autoreleasing:
1054 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1055 << ValType << PointerArg->getSourceRange();
1056 return true;
1057 }
1058
Tim Northover6aacd492013-07-16 09:47:53 +00001059 if (IsLdrex) {
1060 TheCall->setType(ValType);
1061 return false;
1062 }
1063
1064 // Initialize the argument to be stored.
1065 ExprResult ValArg = TheCall->getArg(0);
1066 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1067 Context, ValType, /*consume*/ false);
1068 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1069 if (ValArg.isInvalid())
1070 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001071 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001072
1073 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1074 // but the custom checker bypasses all default analysis.
1075 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001076 return false;
1077}
1078
Nate Begeman4904e322010-06-08 02:47:44 +00001079bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001080 llvm::APSInt Result;
1081
Tim Northover6aacd492013-07-16 09:47:53 +00001082 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001083 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1084 BuiltinID == ARM::BI__builtin_arm_strex ||
1085 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001086 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001087 }
1088
Yi Kong26d104a2014-08-13 19:18:14 +00001089 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1090 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1091 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1092 }
1093
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001094 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1095 BuiltinID == ARM::BI__builtin_arm_wsr64)
1096 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1097
1098 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1099 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1100 BuiltinID == ARM::BI__builtin_arm_wsr ||
1101 BuiltinID == ARM::BI__builtin_arm_wsrp)
1102 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1103
Tim Northover12670412014-02-19 10:37:05 +00001104 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1105 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001106
Yi Kong4efadfb2014-07-03 16:01:25 +00001107 // For intrinsics which take an immediate value as part of the instruction,
1108 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001109 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001110 switch (BuiltinID) {
1111 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001112 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1113 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001114 case ARM::BI__builtin_arm_vcvtr_f:
1115 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001116 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001117 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001118 case ARM::BI__builtin_arm_isb:
1119 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001120 }
Nate Begemand773fe62010-06-13 04:47:52 +00001121
Nate Begemanf568b072010-08-03 21:32:34 +00001122 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001123 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001124}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001125
Tim Northover573cbee2014-05-24 12:52:07 +00001126bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001127 CallExpr *TheCall) {
1128 llvm::APSInt Result;
1129
Tim Northover573cbee2014-05-24 12:52:07 +00001130 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001131 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1132 BuiltinID == AArch64::BI__builtin_arm_strex ||
1133 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001134 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1135 }
1136
Yi Konga5548432014-08-13 19:18:20 +00001137 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1138 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1139 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1140 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1141 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1142 }
1143
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001144 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1145 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1146 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
1147
1148 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1149 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1150 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1151 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1152 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1153
Tim Northovera2ee4332014-03-29 15:09:45 +00001154 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1155 return true;
1156
Yi Kong19a29ac2014-07-17 10:52:06 +00001157 // For intrinsics which take an immediate value as part of the instruction,
1158 // range check them here.
1159 unsigned i = 0, l = 0, u = 0;
1160 switch (BuiltinID) {
1161 default: return false;
1162 case AArch64::BI__builtin_arm_dmb:
1163 case AArch64::BI__builtin_arm_dsb:
1164 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1165 }
1166
Yi Kong19a29ac2014-07-17 10:52:06 +00001167 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001168}
1169
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001170bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1171 unsigned i = 0, l = 0, u = 0;
1172 switch (BuiltinID) {
1173 default: return false;
1174 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1175 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001176 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1177 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1178 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1179 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1180 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001181 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001182
Richard Sandiford28940af2014-04-16 08:47:51 +00001183 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001184}
1185
Kit Bartone50adcb2015-03-30 19:40:59 +00001186bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1187 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001188 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1189 BuiltinID == PPC::BI__builtin_divdeu ||
1190 BuiltinID == PPC::BI__builtin_bpermd;
1191 bool IsTarget64Bit = Context.getTargetInfo()
1192 .getTypeWidth(Context
1193 .getTargetInfo()
1194 .getIntPtrType()) == 64;
1195 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1196 BuiltinID == PPC::BI__builtin_divweu ||
1197 BuiltinID == PPC::BI__builtin_divde ||
1198 BuiltinID == PPC::BI__builtin_divdeu;
1199
1200 if (Is64BitBltin && !IsTarget64Bit)
1201 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1202 << TheCall->getSourceRange();
1203
1204 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1205 (BuiltinID == PPC::BI__builtin_bpermd &&
1206 !Context.getTargetInfo().hasFeature("bpermd")))
1207 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1208 << TheCall->getSourceRange();
1209
Kit Bartone50adcb2015-03-30 19:40:59 +00001210 switch (BuiltinID) {
1211 default: return false;
1212 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1213 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1214 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1215 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1216 case PPC::BI__builtin_tbegin:
1217 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1218 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1219 case PPC::BI__builtin_tabortwc:
1220 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1221 case PPC::BI__builtin_tabortwci:
1222 case PPC::BI__builtin_tabortdci:
1223 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1224 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1225 }
1226 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1227}
1228
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001229bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1230 CallExpr *TheCall) {
1231 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1232 Expr *Arg = TheCall->getArg(0);
1233 llvm::APSInt AbortCode(32);
1234 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1235 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1236 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1237 << Arg->getSourceRange();
1238 }
1239
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001240 // For intrinsics which take an immediate value as part of the instruction,
1241 // range check them here.
1242 unsigned i = 0, l = 0, u = 0;
1243 switch (BuiltinID) {
1244 default: return false;
1245 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1246 case SystemZ::BI__builtin_s390_verimb:
1247 case SystemZ::BI__builtin_s390_verimh:
1248 case SystemZ::BI__builtin_s390_verimf:
1249 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1250 case SystemZ::BI__builtin_s390_vfaeb:
1251 case SystemZ::BI__builtin_s390_vfaeh:
1252 case SystemZ::BI__builtin_s390_vfaef:
1253 case SystemZ::BI__builtin_s390_vfaebs:
1254 case SystemZ::BI__builtin_s390_vfaehs:
1255 case SystemZ::BI__builtin_s390_vfaefs:
1256 case SystemZ::BI__builtin_s390_vfaezb:
1257 case SystemZ::BI__builtin_s390_vfaezh:
1258 case SystemZ::BI__builtin_s390_vfaezf:
1259 case SystemZ::BI__builtin_s390_vfaezbs:
1260 case SystemZ::BI__builtin_s390_vfaezhs:
1261 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1262 case SystemZ::BI__builtin_s390_vfidb:
1263 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1264 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1265 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1266 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1267 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1268 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1269 case SystemZ::BI__builtin_s390_vstrcb:
1270 case SystemZ::BI__builtin_s390_vstrch:
1271 case SystemZ::BI__builtin_s390_vstrcf:
1272 case SystemZ::BI__builtin_s390_vstrczb:
1273 case SystemZ::BI__builtin_s390_vstrczh:
1274 case SystemZ::BI__builtin_s390_vstrczf:
1275 case SystemZ::BI__builtin_s390_vstrcbs:
1276 case SystemZ::BI__builtin_s390_vstrchs:
1277 case SystemZ::BI__builtin_s390_vstrcfs:
1278 case SystemZ::BI__builtin_s390_vstrczbs:
1279 case SystemZ::BI__builtin_s390_vstrczhs:
1280 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1281 }
1282 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001283}
1284
Craig Topper5ba2c502015-11-07 08:08:31 +00001285/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1286/// This checks that the target supports __builtin_cpu_supports and
1287/// that the string argument is constant and valid.
1288static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1289 Expr *Arg = TheCall->getArg(0);
1290
1291 // Check if the argument is a string literal.
1292 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1293 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1294 << Arg->getSourceRange();
1295
1296 // Check the contents of the string.
1297 StringRef Feature =
1298 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1299 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1300 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1301 << Arg->getSourceRange();
1302 return false;
1303}
1304
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001305bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001306 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001307 switch (BuiltinID) {
Richard Trieucc3949d2016-02-18 22:34:54 +00001308 default:
1309 return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001310 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001311 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001312 case X86::BI__builtin_ms_va_start:
1313 return SemaBuiltinMSVAStart(TheCall);
Richard Trieucc3949d2016-02-18 22:34:54 +00001314 case X86::BI_mm_prefetch:
1315 i = 1;
1316 l = 0;
1317 u = 3;
1318 break;
1319 case X86::BI__builtin_ia32_sha1rnds4:
1320 i = 2;
1321 l = 0;
1322 u = 3;
1323 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001324 case X86::BI__builtin_ia32_vpermil2pd:
1325 case X86::BI__builtin_ia32_vpermil2pd256:
1326 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001327 case X86::BI__builtin_ia32_vpermil2ps256:
1328 i = 3;
1329 l = 0;
1330 u = 3;
1331 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001332 case X86::BI__builtin_ia32_cmpb128_mask:
1333 case X86::BI__builtin_ia32_cmpw128_mask:
1334 case X86::BI__builtin_ia32_cmpd128_mask:
1335 case X86::BI__builtin_ia32_cmpq128_mask:
1336 case X86::BI__builtin_ia32_cmpb256_mask:
1337 case X86::BI__builtin_ia32_cmpw256_mask:
1338 case X86::BI__builtin_ia32_cmpd256_mask:
1339 case X86::BI__builtin_ia32_cmpq256_mask:
1340 case X86::BI__builtin_ia32_cmpb512_mask:
1341 case X86::BI__builtin_ia32_cmpw512_mask:
1342 case X86::BI__builtin_ia32_cmpd512_mask:
1343 case X86::BI__builtin_ia32_cmpq512_mask:
1344 case X86::BI__builtin_ia32_ucmpb128_mask:
1345 case X86::BI__builtin_ia32_ucmpw128_mask:
1346 case X86::BI__builtin_ia32_ucmpd128_mask:
1347 case X86::BI__builtin_ia32_ucmpq128_mask:
1348 case X86::BI__builtin_ia32_ucmpb256_mask:
1349 case X86::BI__builtin_ia32_ucmpw256_mask:
1350 case X86::BI__builtin_ia32_ucmpd256_mask:
1351 case X86::BI__builtin_ia32_ucmpq256_mask:
1352 case X86::BI__builtin_ia32_ucmpb512_mask:
1353 case X86::BI__builtin_ia32_ucmpw512_mask:
1354 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001355 case X86::BI__builtin_ia32_ucmpq512_mask:
1356 i = 2;
1357 l = 0;
1358 u = 7;
1359 break;
Craig Topper16015252015-01-31 06:31:23 +00001360 case X86::BI__builtin_ia32_roundps:
1361 case X86::BI__builtin_ia32_roundpd:
1362 case X86::BI__builtin_ia32_roundps256:
Richard Trieucc3949d2016-02-18 22:34:54 +00001363 case X86::BI__builtin_ia32_roundpd256:
1364 i = 1;
1365 l = 0;
1366 u = 15;
1367 break;
Craig Topper16015252015-01-31 06:31:23 +00001368 case X86::BI__builtin_ia32_roundss:
Richard Trieucc3949d2016-02-18 22:34:54 +00001369 case X86::BI__builtin_ia32_roundsd:
1370 i = 2;
1371 l = 0;
1372 u = 15;
1373 break;
Craig Topper16015252015-01-31 06:31:23 +00001374 case X86::BI__builtin_ia32_cmpps:
1375 case X86::BI__builtin_ia32_cmpss:
1376 case X86::BI__builtin_ia32_cmppd:
1377 case X86::BI__builtin_ia32_cmpsd:
1378 case X86::BI__builtin_ia32_cmpps256:
1379 case X86::BI__builtin_ia32_cmppd256:
1380 case X86::BI__builtin_ia32_cmpps512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001381 case X86::BI__builtin_ia32_cmppd512_mask:
1382 i = 2;
1383 l = 0;
1384 u = 31;
1385 break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001386 case X86::BI__builtin_ia32_vpcomub:
1387 case X86::BI__builtin_ia32_vpcomuw:
1388 case X86::BI__builtin_ia32_vpcomud:
1389 case X86::BI__builtin_ia32_vpcomuq:
1390 case X86::BI__builtin_ia32_vpcomb:
1391 case X86::BI__builtin_ia32_vpcomw:
1392 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001393 case X86::BI__builtin_ia32_vpcomq:
1394 i = 2;
1395 l = 0;
1396 u = 7;
1397 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001398 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001399 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001400}
1401
Richard Smith55ce3522012-06-25 20:30:08 +00001402/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1403/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1404/// Returns true when the format fits the function and the FormatStringInfo has
1405/// been populated.
1406bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1407 FormatStringInfo *FSI) {
1408 FSI->HasVAListArg = Format->getFirstArg() == 0;
1409 FSI->FormatIdx = Format->getFormatIdx() - 1;
1410 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001411
Richard Smith55ce3522012-06-25 20:30:08 +00001412 // The way the format attribute works in GCC, the implicit this argument
1413 // of member functions is counted. However, it doesn't appear in our own
1414 // lists, so decrement format_idx in that case.
1415 if (IsCXXMember) {
1416 if(FSI->FormatIdx == 0)
1417 return false;
1418 --FSI->FormatIdx;
1419 if (FSI->FirstDataArg != 0)
1420 --FSI->FirstDataArg;
1421 }
1422 return true;
1423}
Mike Stump11289f42009-09-09 15:08:12 +00001424
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001425/// Checks if a the given expression evaluates to null.
1426///
1427/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001428static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001429 // If the expression has non-null type, it doesn't evaluate to null.
1430 if (auto nullability
1431 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1432 if (*nullability == NullabilityKind::NonNull)
1433 return false;
1434 }
1435
Ted Kremeneka146db32014-01-17 06:24:47 +00001436 // As a special case, transparent unions initialized with zero are
1437 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001438 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001439 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1440 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001441 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001442 if (const InitListExpr *ILE =
1443 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001444 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001445 }
1446
1447 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001448 return (!Expr->isValueDependent() &&
1449 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1450 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001451}
1452
1453static void CheckNonNullArgument(Sema &S,
1454 const Expr *ArgExpr,
1455 SourceLocation CallSiteLoc) {
1456 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001457 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1458 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001459}
1460
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001461bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1462 FormatStringInfo FSI;
1463 if ((GetFormatStringType(Format) == FST_NSString) &&
1464 getFormatStringInfo(Format, false, &FSI)) {
1465 Idx = FSI.FormatIdx;
1466 return true;
1467 }
1468 return false;
1469}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001470/// \brief Diagnose use of %s directive in an NSString which is being passed
1471/// as formatting string to formatting method.
1472static void
1473DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1474 const NamedDecl *FDecl,
1475 Expr **Args,
1476 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001477 unsigned Idx = 0;
1478 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001479 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1480 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001481 Idx = 2;
1482 Format = true;
1483 }
1484 else
1485 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1486 if (S.GetFormatNSStringIdx(I, Idx)) {
1487 Format = true;
1488 break;
1489 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001490 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001491 if (!Format || NumArgs <= Idx)
1492 return;
1493 const Expr *FormatExpr = Args[Idx];
1494 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1495 FormatExpr = CSCE->getSubExpr();
1496 const StringLiteral *FormatString;
1497 if (const ObjCStringLiteral *OSL =
1498 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1499 FormatString = OSL->getString();
1500 else
1501 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1502 if (!FormatString)
1503 return;
1504 if (S.FormatStringHasSArg(FormatString)) {
1505 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1506 << "%s" << 1 << 1;
1507 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1508 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001509 }
1510}
1511
Douglas Gregorb4866e82015-06-19 18:13:19 +00001512/// Determine whether the given type has a non-null nullability annotation.
1513static bool isNonNullType(ASTContext &ctx, QualType type) {
1514 if (auto nullability = type->getNullability(ctx))
1515 return *nullability == NullabilityKind::NonNull;
1516
1517 return false;
1518}
1519
Ted Kremenek2bc73332014-01-17 06:24:43 +00001520static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001521 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001522 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001523 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001524 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001525 assert((FDecl || Proto) && "Need a function declaration or prototype");
1526
Ted Kremenek9aedc152014-01-17 06:24:56 +00001527 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001528 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001529 if (FDecl) {
1530 // Handle the nonnull attribute on the function/method declaration itself.
1531 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1532 if (!NonNull->args_size()) {
1533 // Easy case: all pointer arguments are nonnull.
1534 for (const auto *Arg : Args)
1535 if (S.isValidPointerAttrType(Arg->getType()))
1536 CheckNonNullArgument(S, Arg, CallSiteLoc);
1537 return;
1538 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001539
Douglas Gregorb4866e82015-06-19 18:13:19 +00001540 for (unsigned Val : NonNull->args()) {
1541 if (Val >= Args.size())
1542 continue;
1543 if (NonNullArgs.empty())
1544 NonNullArgs.resize(Args.size());
1545 NonNullArgs.set(Val);
1546 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001547 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001548 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001549
Douglas Gregorb4866e82015-06-19 18:13:19 +00001550 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1551 // Handle the nonnull attribute on the parameters of the
1552 // function/method.
1553 ArrayRef<ParmVarDecl*> parms;
1554 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1555 parms = FD->parameters();
1556 else
1557 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1558
1559 unsigned ParamIndex = 0;
1560 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1561 I != E; ++I, ++ParamIndex) {
1562 const ParmVarDecl *PVD = *I;
1563 if (PVD->hasAttr<NonNullAttr>() ||
1564 isNonNullType(S.Context, PVD->getType())) {
1565 if (NonNullArgs.empty())
1566 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001567
Douglas Gregorb4866e82015-06-19 18:13:19 +00001568 NonNullArgs.set(ParamIndex);
1569 }
1570 }
1571 } else {
1572 // If we have a non-function, non-method declaration but no
1573 // function prototype, try to dig out the function prototype.
1574 if (!Proto) {
1575 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1576 QualType type = VD->getType().getNonReferenceType();
1577 if (auto pointerType = type->getAs<PointerType>())
1578 type = pointerType->getPointeeType();
1579 else if (auto blockType = type->getAs<BlockPointerType>())
1580 type = blockType->getPointeeType();
1581 // FIXME: data member pointers?
1582
1583 // Dig out the function prototype, if there is one.
1584 Proto = type->getAs<FunctionProtoType>();
1585 }
1586 }
1587
1588 // Fill in non-null argument information from the nullability
1589 // information on the parameter types (if we have them).
1590 if (Proto) {
1591 unsigned Index = 0;
1592 for (auto paramType : Proto->getParamTypes()) {
1593 if (isNonNullType(S.Context, paramType)) {
1594 if (NonNullArgs.empty())
1595 NonNullArgs.resize(Args.size());
1596
1597 NonNullArgs.set(Index);
1598 }
1599
1600 ++Index;
1601 }
1602 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001603 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001604
Douglas Gregorb4866e82015-06-19 18:13:19 +00001605 // Check for non-null arguments.
1606 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1607 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001608 if (NonNullArgs[ArgIndex])
1609 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001610 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001611}
1612
Richard Smith55ce3522012-06-25 20:30:08 +00001613/// Handles the checks for format strings, non-POD arguments to vararg
1614/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001615void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1616 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001617 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001618 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001619 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001620 if (CurContext->isDependentContext())
1621 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001622
Ted Kremenekb8176da2010-09-09 04:33:05 +00001623 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001624 llvm::SmallBitVector CheckedVarArgs;
1625 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001626 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001627 // Only create vector if there are format attributes.
1628 CheckedVarArgs.resize(Args.size());
1629
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001630 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001631 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001632 }
Richard Smithd7293d72013-08-05 18:49:43 +00001633 }
Richard Smith55ce3522012-06-25 20:30:08 +00001634
1635 // Refuse POD arguments that weren't caught by the format string
1636 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001637 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001638 unsigned NumParams = Proto ? Proto->getNumParams()
1639 : FDecl && isa<FunctionDecl>(FDecl)
1640 ? cast<FunctionDecl>(FDecl)->getNumParams()
1641 : FDecl && isa<ObjCMethodDecl>(FDecl)
1642 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1643 : 0;
1644
Alp Toker9cacbab2014-01-20 20:26:09 +00001645 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001646 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001647 if (const Expr *Arg = Args[ArgIdx]) {
1648 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1649 checkVariadicArgument(Arg, CallType);
1650 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001651 }
Richard Smithd7293d72013-08-05 18:49:43 +00001652 }
Mike Stump11289f42009-09-09 15:08:12 +00001653
Douglas Gregorb4866e82015-06-19 18:13:19 +00001654 if (FDecl || Proto) {
1655 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001656
Richard Trieu41bc0992013-06-22 00:20:41 +00001657 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001658 if (FDecl) {
1659 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1660 CheckArgumentWithTypeTag(I, Args.data());
1661 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001662 }
Richard Smith55ce3522012-06-25 20:30:08 +00001663}
1664
1665/// CheckConstructorCall - Check a constructor call for correctness and safety
1666/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001667void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1668 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001669 const FunctionProtoType *Proto,
1670 SourceLocation Loc) {
1671 VariadicCallType CallType =
1672 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001673 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1674 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001675}
1676
1677/// CheckFunctionCall - Check a direct function call for various correctness
1678/// and safety properties not strictly enforced by the C type system.
1679bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1680 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001681 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1682 isa<CXXMethodDecl>(FDecl);
1683 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1684 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001685 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1686 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001687 Expr** Args = TheCall->getArgs();
1688 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001689 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001690 // If this is a call to a member operator, hide the first argument
1691 // from checkCall.
1692 // FIXME: Our choice of AST representation here is less than ideal.
1693 ++Args;
1694 --NumArgs;
1695 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001696 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001697 IsMemberFunction, TheCall->getRParenLoc(),
1698 TheCall->getCallee()->getSourceRange(), CallType);
1699
1700 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1701 // None of the checks below are needed for functions that don't have
1702 // simple names (e.g., C++ conversion functions).
1703 if (!FnInfo)
1704 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001705
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001706 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001707 if (getLangOpts().ObjC1)
1708 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001709
Anna Zaks22122702012-01-17 00:37:07 +00001710 unsigned CMId = FDecl->getMemoryFunctionKind();
1711 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001712 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001713
Anna Zaks201d4892012-01-13 21:52:01 +00001714 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001715 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001716 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001717 else if (CMId == Builtin::BIstrncat)
1718 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001719 else
Anna Zaks22122702012-01-17 00:37:07 +00001720 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001721
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001722 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001723}
1724
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001725bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001726 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001727 VariadicCallType CallType =
1728 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001729
Douglas Gregorb4866e82015-06-19 18:13:19 +00001730 checkCall(Method, nullptr, Args,
1731 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1732 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001733
1734 return false;
1735}
1736
Richard Trieu664c4c62013-06-20 21:03:13 +00001737bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1738 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001739 QualType Ty;
1740 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001741 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001742 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001743 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001744 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001745 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001746
Douglas Gregorb4866e82015-06-19 18:13:19 +00001747 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1748 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001749 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001750
Richard Trieu664c4c62013-06-20 21:03:13 +00001751 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001752 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001753 CallType = VariadicDoesNotApply;
1754 } else if (Ty->isBlockPointerType()) {
1755 CallType = VariadicBlock;
1756 } else { // Ty->isFunctionPointerType()
1757 CallType = VariadicFunction;
1758 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001759
Douglas Gregorb4866e82015-06-19 18:13:19 +00001760 checkCall(NDecl, Proto,
1761 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1762 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001763 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001764
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001765 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001766}
1767
Richard Trieu41bc0992013-06-22 00:20:41 +00001768/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1769/// such as function pointers returned from functions.
1770bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001771 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001772 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001773 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001774 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001775 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001776 TheCall->getCallee()->getSourceRange(), CallType);
1777
1778 return false;
1779}
1780
Tim Northovere94a34c2014-03-11 10:49:14 +00001781static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1782 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1783 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1784 return false;
1785
1786 switch (Op) {
1787 case AtomicExpr::AO__c11_atomic_init:
1788 llvm_unreachable("There is no ordering argument for an init");
1789
1790 case AtomicExpr::AO__c11_atomic_load:
1791 case AtomicExpr::AO__atomic_load_n:
1792 case AtomicExpr::AO__atomic_load:
1793 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1794 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1795
1796 case AtomicExpr::AO__c11_atomic_store:
1797 case AtomicExpr::AO__atomic_store:
1798 case AtomicExpr::AO__atomic_store_n:
1799 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1800 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1801 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1802
1803 default:
1804 return true;
1805 }
1806}
1807
Richard Smithfeea8832012-04-12 05:08:17 +00001808ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1809 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001810 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1811 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001812
Richard Smithfeea8832012-04-12 05:08:17 +00001813 // All these operations take one of the following forms:
1814 enum {
1815 // C __c11_atomic_init(A *, C)
1816 Init,
1817 // C __c11_atomic_load(A *, int)
1818 Load,
1819 // void __atomic_load(A *, CP, int)
1820 Copy,
1821 // C __c11_atomic_add(A *, M, int)
1822 Arithmetic,
1823 // C __atomic_exchange_n(A *, CP, int)
1824 Xchg,
1825 // void __atomic_exchange(A *, C *, CP, int)
1826 GNUXchg,
1827 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1828 C11CmpXchg,
1829 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1830 GNUCmpXchg
1831 } Form = Init;
1832 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1833 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1834 // where:
1835 // C is an appropriate type,
1836 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1837 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1838 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1839 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001840
Gabor Horvath98bd0982015-03-16 09:59:54 +00001841 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1842 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1843 AtomicExpr::AO__atomic_load,
1844 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001845 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1846 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1847 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1848 Op == AtomicExpr::AO__atomic_store_n ||
1849 Op == AtomicExpr::AO__atomic_exchange_n ||
1850 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1851 bool IsAddSub = false;
1852
1853 switch (Op) {
1854 case AtomicExpr::AO__c11_atomic_init:
1855 Form = Init;
1856 break;
1857
1858 case AtomicExpr::AO__c11_atomic_load:
1859 case AtomicExpr::AO__atomic_load_n:
1860 Form = Load;
1861 break;
1862
1863 case AtomicExpr::AO__c11_atomic_store:
1864 case AtomicExpr::AO__atomic_load:
1865 case AtomicExpr::AO__atomic_store:
1866 case AtomicExpr::AO__atomic_store_n:
1867 Form = Copy;
1868 break;
1869
1870 case AtomicExpr::AO__c11_atomic_fetch_add:
1871 case AtomicExpr::AO__c11_atomic_fetch_sub:
1872 case AtomicExpr::AO__atomic_fetch_add:
1873 case AtomicExpr::AO__atomic_fetch_sub:
1874 case AtomicExpr::AO__atomic_add_fetch:
1875 case AtomicExpr::AO__atomic_sub_fetch:
1876 IsAddSub = true;
1877 // Fall through.
1878 case AtomicExpr::AO__c11_atomic_fetch_and:
1879 case AtomicExpr::AO__c11_atomic_fetch_or:
1880 case AtomicExpr::AO__c11_atomic_fetch_xor:
1881 case AtomicExpr::AO__atomic_fetch_and:
1882 case AtomicExpr::AO__atomic_fetch_or:
1883 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001884 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001885 case AtomicExpr::AO__atomic_and_fetch:
1886 case AtomicExpr::AO__atomic_or_fetch:
1887 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001888 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001889 Form = Arithmetic;
1890 break;
1891
1892 case AtomicExpr::AO__c11_atomic_exchange:
1893 case AtomicExpr::AO__atomic_exchange_n:
1894 Form = Xchg;
1895 break;
1896
1897 case AtomicExpr::AO__atomic_exchange:
1898 Form = GNUXchg;
1899 break;
1900
1901 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1902 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1903 Form = C11CmpXchg;
1904 break;
1905
1906 case AtomicExpr::AO__atomic_compare_exchange:
1907 case AtomicExpr::AO__atomic_compare_exchange_n:
1908 Form = GNUCmpXchg;
1909 break;
1910 }
1911
1912 // Check we have the right number of arguments.
1913 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001914 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001915 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001916 << TheCall->getCallee()->getSourceRange();
1917 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001918 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1919 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001920 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001921 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001922 << TheCall->getCallee()->getSourceRange();
1923 return ExprError();
1924 }
1925
Richard Smithfeea8832012-04-12 05:08:17 +00001926 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001927 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001928 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1929 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1930 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001931 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001932 << Ptr->getType() << Ptr->getSourceRange();
1933 return ExprError();
1934 }
1935
Richard Smithfeea8832012-04-12 05:08:17 +00001936 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1937 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1938 QualType ValType = AtomTy; // 'C'
1939 if (IsC11) {
1940 if (!AtomTy->isAtomicType()) {
1941 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1942 << Ptr->getType() << Ptr->getSourceRange();
1943 return ExprError();
1944 }
Richard Smithe00921a2012-09-15 06:09:58 +00001945 if (AtomTy.isConstQualified()) {
1946 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1947 << Ptr->getType() << Ptr->getSourceRange();
1948 return ExprError();
1949 }
Richard Smithfeea8832012-04-12 05:08:17 +00001950 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001951 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1952 if (ValType.isConstQualified()) {
1953 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1954 << Ptr->getType() << Ptr->getSourceRange();
1955 return ExprError();
1956 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001957 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001958
Richard Smithfeea8832012-04-12 05:08:17 +00001959 // For an arithmetic operation, the implied arithmetic must be well-formed.
1960 if (Form == Arithmetic) {
1961 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1962 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1963 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1964 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1965 return ExprError();
1966 }
1967 if (!IsAddSub && !ValType->isIntegerType()) {
1968 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1969 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1970 return ExprError();
1971 }
David Majnemere85cff82015-01-28 05:48:06 +00001972 if (IsC11 && ValType->isPointerType() &&
1973 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1974 diag::err_incomplete_type)) {
1975 return ExprError();
1976 }
Richard Smithfeea8832012-04-12 05:08:17 +00001977 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1978 // For __atomic_*_n operations, the value type must be a scalar integral or
1979 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001980 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001981 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1982 return ExprError();
1983 }
1984
Eli Friedmanaa769812013-09-11 03:49:34 +00001985 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1986 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001987 // For GNU atomics, require a trivially-copyable type. This is not part of
1988 // the GNU atomics specification, but we enforce it for sanity.
1989 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001990 << Ptr->getType() << Ptr->getSourceRange();
1991 return ExprError();
1992 }
1993
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001994 switch (ValType.getObjCLifetime()) {
1995 case Qualifiers::OCL_None:
1996 case Qualifiers::OCL_ExplicitNone:
1997 // okay
1998 break;
1999
2000 case Qualifiers::OCL_Weak:
2001 case Qualifiers::OCL_Strong:
2002 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002003 // FIXME: Can this happen? By this point, ValType should be known
2004 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002005 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2006 << ValType << Ptr->getSourceRange();
2007 return ExprError();
2008 }
2009
David Majnemerc6eb6502015-06-03 00:26:35 +00002010 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2011 // volatile-ness of the pointee-type inject itself into the result or the
2012 // other operands.
2013 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002014 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00002015 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002016 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002017 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002018 ResultType = Context.BoolTy;
2019
Richard Smithfeea8832012-04-12 05:08:17 +00002020 // The type of a parameter passed 'by value'. In the GNU atomics, such
2021 // arguments are actually passed as pointers.
2022 QualType ByValType = ValType; // 'CP'
2023 if (!IsC11 && !IsN)
2024 ByValType = Ptr->getType();
2025
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002026 // FIXME: __atomic_load allows the first argument to be a a pointer to const
2027 // but not the second argument. We need to manually remove possible const
2028 // qualifiers.
2029
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002030 // The first argument --- the pointer --- has a fixed type; we
2031 // deduce the types of the rest of the arguments accordingly. Walk
2032 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002033 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002034 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002035 if (i < NumVals[Form] + 1) {
2036 switch (i) {
2037 case 1:
2038 // The second argument is the non-atomic operand. For arithmetic, this
2039 // is always passed by value, and for a compare_exchange it is always
2040 // passed by address. For the rest, GNU uses by-address and C11 uses
2041 // by-value.
2042 assert(Form != Load);
2043 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2044 Ty = ValType;
2045 else if (Form == Copy || Form == Xchg)
2046 Ty = ByValType;
2047 else if (Form == Arithmetic)
2048 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002049 else {
2050 Expr *ValArg = TheCall->getArg(i);
2051 unsigned AS = 0;
2052 // Keep address space of non-atomic pointer type.
2053 if (const PointerType *PtrTy =
2054 ValArg->getType()->getAs<PointerType>()) {
2055 AS = PtrTy->getPointeeType().getAddressSpace();
2056 }
2057 Ty = Context.getPointerType(
2058 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2059 }
Richard Smithfeea8832012-04-12 05:08:17 +00002060 break;
2061 case 2:
2062 // The third argument to compare_exchange / GNU exchange is a
2063 // (pointer to a) desired value.
2064 Ty = ByValType;
2065 break;
2066 case 3:
2067 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2068 Ty = Context.BoolTy;
2069 break;
2070 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002071 } else {
2072 // The order(s) are always converted to int.
2073 Ty = Context.IntTy;
2074 }
Richard Smithfeea8832012-04-12 05:08:17 +00002075
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002076 InitializedEntity Entity =
2077 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002078 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002079 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2080 if (Arg.isInvalid())
2081 return true;
2082 TheCall->setArg(i, Arg.get());
2083 }
2084
Richard Smithfeea8832012-04-12 05:08:17 +00002085 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002086 SmallVector<Expr*, 5> SubExprs;
2087 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002088 switch (Form) {
2089 case Init:
2090 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002091 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002092 break;
2093 case Load:
2094 SubExprs.push_back(TheCall->getArg(1)); // Order
2095 break;
2096 case Copy:
2097 case Arithmetic:
2098 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002099 SubExprs.push_back(TheCall->getArg(2)); // Order
2100 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002101 break;
2102 case GNUXchg:
2103 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2104 SubExprs.push_back(TheCall->getArg(3)); // Order
2105 SubExprs.push_back(TheCall->getArg(1)); // Val1
2106 SubExprs.push_back(TheCall->getArg(2)); // Val2
2107 break;
2108 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002109 SubExprs.push_back(TheCall->getArg(3)); // Order
2110 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002111 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002112 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002113 break;
2114 case GNUCmpXchg:
2115 SubExprs.push_back(TheCall->getArg(4)); // Order
2116 SubExprs.push_back(TheCall->getArg(1)); // Val1
2117 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2118 SubExprs.push_back(TheCall->getArg(2)); // Val2
2119 SubExprs.push_back(TheCall->getArg(3)); // Weak
2120 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002121 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002122
2123 if (SubExprs.size() >= 2 && Form != Init) {
2124 llvm::APSInt Result(32);
2125 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2126 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002127 Diag(SubExprs[1]->getLocStart(),
2128 diag::warn_atomic_op_has_invalid_memory_order)
2129 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002130 }
2131
Fariborz Jahanian615de762013-05-28 17:37:39 +00002132 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2133 SubExprs, ResultType, Op,
2134 TheCall->getRParenLoc());
2135
2136 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2137 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2138 Context.AtomicUsesUnsupportedLibcall(AE))
2139 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2140 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002141
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002142 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002143}
2144
John McCall29ad95b2011-08-27 01:09:30 +00002145/// checkBuiltinArgument - Given a call to a builtin function, perform
2146/// normal type-checking on the given argument, updating the call in
2147/// place. This is useful when a builtin function requires custom
2148/// type-checking for some of its arguments but not necessarily all of
2149/// them.
2150///
2151/// Returns true on error.
2152static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2153 FunctionDecl *Fn = E->getDirectCallee();
2154 assert(Fn && "builtin call without direct callee!");
2155
2156 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2157 InitializedEntity Entity =
2158 InitializedEntity::InitializeParameter(S.Context, Param);
2159
2160 ExprResult Arg = E->getArg(0);
2161 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2162 if (Arg.isInvalid())
2163 return true;
2164
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002165 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002166 return false;
2167}
2168
Chris Lattnerdc046542009-05-08 06:58:22 +00002169/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2170/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2171/// type of its first argument. The main ActOnCallExpr routines have already
2172/// promoted the types of arguments because all of these calls are prototyped as
2173/// void(...).
2174///
2175/// This function goes through and does final semantic checking for these
2176/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002177ExprResult
2178Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002179 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002180 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2181 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2182
2183 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002184 if (TheCall->getNumArgs() < 1) {
2185 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2186 << 0 << 1 << TheCall->getNumArgs()
2187 << TheCall->getCallee()->getSourceRange();
2188 return ExprError();
2189 }
Mike Stump11289f42009-09-09 15:08:12 +00002190
Chris Lattnerdc046542009-05-08 06:58:22 +00002191 // Inspect the first argument of the atomic builtin. This should always be
2192 // a pointer type, whose element is an integral scalar or pointer type.
2193 // Because it is a pointer type, we don't have to worry about any implicit
2194 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002195 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002196 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002197 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2198 if (FirstArgResult.isInvalid())
2199 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002200 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002201 TheCall->setArg(0, FirstArg);
2202
John McCall31168b02011-06-15 23:02:42 +00002203 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2204 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002205 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2206 << FirstArg->getType() << FirstArg->getSourceRange();
2207 return ExprError();
2208 }
Mike Stump11289f42009-09-09 15:08:12 +00002209
John McCall31168b02011-06-15 23:02:42 +00002210 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002211 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002212 !ValType->isBlockPointerType()) {
2213 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2214 << FirstArg->getType() << FirstArg->getSourceRange();
2215 return ExprError();
2216 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002217
John McCall31168b02011-06-15 23:02:42 +00002218 switch (ValType.getObjCLifetime()) {
2219 case Qualifiers::OCL_None:
2220 case Qualifiers::OCL_ExplicitNone:
2221 // okay
2222 break;
2223
2224 case Qualifiers::OCL_Weak:
2225 case Qualifiers::OCL_Strong:
2226 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002227 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002228 << ValType << FirstArg->getSourceRange();
2229 return ExprError();
2230 }
2231
John McCallb50451a2011-10-05 07:41:44 +00002232 // Strip any qualifiers off ValType.
2233 ValType = ValType.getUnqualifiedType();
2234
Chandler Carruth3973af72010-07-18 20:54:12 +00002235 // The majority of builtins return a value, but a few have special return
2236 // types, so allow them to override appropriately below.
2237 QualType ResultType = ValType;
2238
Chris Lattnerdc046542009-05-08 06:58:22 +00002239 // We need to figure out which concrete builtin this maps onto. For example,
2240 // __sync_fetch_and_add with a 2 byte object turns into
2241 // __sync_fetch_and_add_2.
2242#define BUILTIN_ROW(x) \
2243 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2244 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002245
Chris Lattnerdc046542009-05-08 06:58:22 +00002246 static const unsigned BuiltinIndices[][5] = {
2247 BUILTIN_ROW(__sync_fetch_and_add),
2248 BUILTIN_ROW(__sync_fetch_and_sub),
2249 BUILTIN_ROW(__sync_fetch_and_or),
2250 BUILTIN_ROW(__sync_fetch_and_and),
2251 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002252 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002253
Chris Lattnerdc046542009-05-08 06:58:22 +00002254 BUILTIN_ROW(__sync_add_and_fetch),
2255 BUILTIN_ROW(__sync_sub_and_fetch),
2256 BUILTIN_ROW(__sync_and_and_fetch),
2257 BUILTIN_ROW(__sync_or_and_fetch),
2258 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002259 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002260
Chris Lattnerdc046542009-05-08 06:58:22 +00002261 BUILTIN_ROW(__sync_val_compare_and_swap),
2262 BUILTIN_ROW(__sync_bool_compare_and_swap),
2263 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002264 BUILTIN_ROW(__sync_lock_release),
2265 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002266 };
Mike Stump11289f42009-09-09 15:08:12 +00002267#undef BUILTIN_ROW
2268
Chris Lattnerdc046542009-05-08 06:58:22 +00002269 // Determine the index of the size.
2270 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002271 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002272 case 1: SizeIndex = 0; break;
2273 case 2: SizeIndex = 1; break;
2274 case 4: SizeIndex = 2; break;
2275 case 8: SizeIndex = 3; break;
2276 case 16: SizeIndex = 4; break;
2277 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002278 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2279 << FirstArg->getType() << FirstArg->getSourceRange();
2280 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002281 }
Mike Stump11289f42009-09-09 15:08:12 +00002282
Chris Lattnerdc046542009-05-08 06:58:22 +00002283 // Each of these builtins has one pointer argument, followed by some number of
2284 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2285 // that we ignore. Find out which row of BuiltinIndices to read from as well
2286 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002287 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002288 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002289 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002290 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002291 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002292 case Builtin::BI__sync_fetch_and_add:
2293 case Builtin::BI__sync_fetch_and_add_1:
2294 case Builtin::BI__sync_fetch_and_add_2:
2295 case Builtin::BI__sync_fetch_and_add_4:
2296 case Builtin::BI__sync_fetch_and_add_8:
2297 case Builtin::BI__sync_fetch_and_add_16:
2298 BuiltinIndex = 0;
2299 break;
2300
2301 case Builtin::BI__sync_fetch_and_sub:
2302 case Builtin::BI__sync_fetch_and_sub_1:
2303 case Builtin::BI__sync_fetch_and_sub_2:
2304 case Builtin::BI__sync_fetch_and_sub_4:
2305 case Builtin::BI__sync_fetch_and_sub_8:
2306 case Builtin::BI__sync_fetch_and_sub_16:
2307 BuiltinIndex = 1;
2308 break;
2309
2310 case Builtin::BI__sync_fetch_and_or:
2311 case Builtin::BI__sync_fetch_and_or_1:
2312 case Builtin::BI__sync_fetch_and_or_2:
2313 case Builtin::BI__sync_fetch_and_or_4:
2314 case Builtin::BI__sync_fetch_and_or_8:
2315 case Builtin::BI__sync_fetch_and_or_16:
2316 BuiltinIndex = 2;
2317 break;
2318
2319 case Builtin::BI__sync_fetch_and_and:
2320 case Builtin::BI__sync_fetch_and_and_1:
2321 case Builtin::BI__sync_fetch_and_and_2:
2322 case Builtin::BI__sync_fetch_and_and_4:
2323 case Builtin::BI__sync_fetch_and_and_8:
2324 case Builtin::BI__sync_fetch_and_and_16:
2325 BuiltinIndex = 3;
2326 break;
Mike Stump11289f42009-09-09 15:08:12 +00002327
Douglas Gregor73722482011-11-28 16:30:08 +00002328 case Builtin::BI__sync_fetch_and_xor:
2329 case Builtin::BI__sync_fetch_and_xor_1:
2330 case Builtin::BI__sync_fetch_and_xor_2:
2331 case Builtin::BI__sync_fetch_and_xor_4:
2332 case Builtin::BI__sync_fetch_and_xor_8:
2333 case Builtin::BI__sync_fetch_and_xor_16:
2334 BuiltinIndex = 4;
2335 break;
2336
Hal Finkeld2208b52014-10-02 20:53:50 +00002337 case Builtin::BI__sync_fetch_and_nand:
2338 case Builtin::BI__sync_fetch_and_nand_1:
2339 case Builtin::BI__sync_fetch_and_nand_2:
2340 case Builtin::BI__sync_fetch_and_nand_4:
2341 case Builtin::BI__sync_fetch_and_nand_8:
2342 case Builtin::BI__sync_fetch_and_nand_16:
2343 BuiltinIndex = 5;
2344 WarnAboutSemanticsChange = true;
2345 break;
2346
Douglas Gregor73722482011-11-28 16:30:08 +00002347 case Builtin::BI__sync_add_and_fetch:
2348 case Builtin::BI__sync_add_and_fetch_1:
2349 case Builtin::BI__sync_add_and_fetch_2:
2350 case Builtin::BI__sync_add_and_fetch_4:
2351 case Builtin::BI__sync_add_and_fetch_8:
2352 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002353 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002354 break;
2355
2356 case Builtin::BI__sync_sub_and_fetch:
2357 case Builtin::BI__sync_sub_and_fetch_1:
2358 case Builtin::BI__sync_sub_and_fetch_2:
2359 case Builtin::BI__sync_sub_and_fetch_4:
2360 case Builtin::BI__sync_sub_and_fetch_8:
2361 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002362 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002363 break;
2364
2365 case Builtin::BI__sync_and_and_fetch:
2366 case Builtin::BI__sync_and_and_fetch_1:
2367 case Builtin::BI__sync_and_and_fetch_2:
2368 case Builtin::BI__sync_and_and_fetch_4:
2369 case Builtin::BI__sync_and_and_fetch_8:
2370 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002371 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002372 break;
2373
2374 case Builtin::BI__sync_or_and_fetch:
2375 case Builtin::BI__sync_or_and_fetch_1:
2376 case Builtin::BI__sync_or_and_fetch_2:
2377 case Builtin::BI__sync_or_and_fetch_4:
2378 case Builtin::BI__sync_or_and_fetch_8:
2379 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002380 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002381 break;
2382
2383 case Builtin::BI__sync_xor_and_fetch:
2384 case Builtin::BI__sync_xor_and_fetch_1:
2385 case Builtin::BI__sync_xor_and_fetch_2:
2386 case Builtin::BI__sync_xor_and_fetch_4:
2387 case Builtin::BI__sync_xor_and_fetch_8:
2388 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002389 BuiltinIndex = 10;
2390 break;
2391
2392 case Builtin::BI__sync_nand_and_fetch:
2393 case Builtin::BI__sync_nand_and_fetch_1:
2394 case Builtin::BI__sync_nand_and_fetch_2:
2395 case Builtin::BI__sync_nand_and_fetch_4:
2396 case Builtin::BI__sync_nand_and_fetch_8:
2397 case Builtin::BI__sync_nand_and_fetch_16:
2398 BuiltinIndex = 11;
2399 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002400 break;
Mike Stump11289f42009-09-09 15:08:12 +00002401
Chris Lattnerdc046542009-05-08 06:58:22 +00002402 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002403 case Builtin::BI__sync_val_compare_and_swap_1:
2404 case Builtin::BI__sync_val_compare_and_swap_2:
2405 case Builtin::BI__sync_val_compare_and_swap_4:
2406 case Builtin::BI__sync_val_compare_and_swap_8:
2407 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002408 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002409 NumFixed = 2;
2410 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002411
Chris Lattnerdc046542009-05-08 06:58:22 +00002412 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002413 case Builtin::BI__sync_bool_compare_and_swap_1:
2414 case Builtin::BI__sync_bool_compare_and_swap_2:
2415 case Builtin::BI__sync_bool_compare_and_swap_4:
2416 case Builtin::BI__sync_bool_compare_and_swap_8:
2417 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002418 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002419 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002420 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002421 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002422
2423 case Builtin::BI__sync_lock_test_and_set:
2424 case Builtin::BI__sync_lock_test_and_set_1:
2425 case Builtin::BI__sync_lock_test_and_set_2:
2426 case Builtin::BI__sync_lock_test_and_set_4:
2427 case Builtin::BI__sync_lock_test_and_set_8:
2428 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002429 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002430 break;
2431
Chris Lattnerdc046542009-05-08 06:58:22 +00002432 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002433 case Builtin::BI__sync_lock_release_1:
2434 case Builtin::BI__sync_lock_release_2:
2435 case Builtin::BI__sync_lock_release_4:
2436 case Builtin::BI__sync_lock_release_8:
2437 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002438 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002439 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002440 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002441 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002442
2443 case Builtin::BI__sync_swap:
2444 case Builtin::BI__sync_swap_1:
2445 case Builtin::BI__sync_swap_2:
2446 case Builtin::BI__sync_swap_4:
2447 case Builtin::BI__sync_swap_8:
2448 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002449 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002450 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002451 }
Mike Stump11289f42009-09-09 15:08:12 +00002452
Chris Lattnerdc046542009-05-08 06:58:22 +00002453 // Now that we know how many fixed arguments we expect, first check that we
2454 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002455 if (TheCall->getNumArgs() < 1+NumFixed) {
2456 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2457 << 0 << 1+NumFixed << TheCall->getNumArgs()
2458 << TheCall->getCallee()->getSourceRange();
2459 return ExprError();
2460 }
Mike Stump11289f42009-09-09 15:08:12 +00002461
Hal Finkeld2208b52014-10-02 20:53:50 +00002462 if (WarnAboutSemanticsChange) {
2463 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2464 << TheCall->getCallee()->getSourceRange();
2465 }
2466
Chris Lattner5b9241b2009-05-08 15:36:58 +00002467 // Get the decl for the concrete builtin from this, we can tell what the
2468 // concrete integer type we should convert to is.
2469 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002470 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002471 FunctionDecl *NewBuiltinDecl;
2472 if (NewBuiltinID == BuiltinID)
2473 NewBuiltinDecl = FDecl;
2474 else {
2475 // Perform builtin lookup to avoid redeclaring it.
2476 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2477 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2478 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2479 assert(Res.getFoundDecl());
2480 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002481 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002482 return ExprError();
2483 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002484
John McCallcf142162010-08-07 06:22:56 +00002485 // The first argument --- the pointer --- has a fixed type; we
2486 // deduce the types of the rest of the arguments accordingly. Walk
2487 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002488 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002489 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002490
Chris Lattnerdc046542009-05-08 06:58:22 +00002491 // GCC does an implicit conversion to the pointer or integer ValType. This
2492 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002493 // Initialize the argument.
2494 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2495 ValType, /*consume*/ false);
2496 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002497 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002498 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002499
Chris Lattnerdc046542009-05-08 06:58:22 +00002500 // Okay, we have something that *can* be converted to the right type. Check
2501 // to see if there is a potentially weird extension going on here. This can
2502 // happen when you do an atomic operation on something like an char* and
2503 // pass in 42. The 42 gets converted to char. This is even more strange
2504 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002505 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002506 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002507 }
Mike Stump11289f42009-09-09 15:08:12 +00002508
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002509 ASTContext& Context = this->getASTContext();
2510
2511 // Create a new DeclRefExpr to refer to the new decl.
2512 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2513 Context,
2514 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002515 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002516 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002517 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002518 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002519 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002520 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002521
Chris Lattnerdc046542009-05-08 06:58:22 +00002522 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002523 // FIXME: This loses syntactic information.
2524 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2525 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2526 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002527 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002528
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002529 // Change the result type of the call to match the original value type. This
2530 // is arbitrary, but the codegen for these builtins ins design to handle it
2531 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002532 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002533
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002534 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002535}
2536
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002537/// SemaBuiltinNontemporalOverloaded - We have a call to
2538/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2539/// overloaded function based on the pointer type of its last argument.
2540///
2541/// This function goes through and does final semantic checking for these
2542/// builtins.
2543ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2544 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2545 DeclRefExpr *DRE =
2546 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2547 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2548 unsigned BuiltinID = FDecl->getBuiltinID();
2549 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2550 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2551 "Unexpected nontemporal load/store builtin!");
2552 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2553 unsigned numArgs = isStore ? 2 : 1;
2554
2555 // Ensure that we have the proper number of arguments.
2556 if (checkArgCount(*this, TheCall, numArgs))
2557 return ExprError();
2558
2559 // Inspect the last argument of the nontemporal builtin. This should always
2560 // be a pointer type, from which we imply the type of the memory access.
2561 // Because it is a pointer type, we don't have to worry about any implicit
2562 // casts here.
2563 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2564 ExprResult PointerArgResult =
2565 DefaultFunctionArrayLvalueConversion(PointerArg);
2566
2567 if (PointerArgResult.isInvalid())
2568 return ExprError();
2569 PointerArg = PointerArgResult.get();
2570 TheCall->setArg(numArgs - 1, PointerArg);
2571
2572 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2573 if (!pointerType) {
2574 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2575 << PointerArg->getType() << PointerArg->getSourceRange();
2576 return ExprError();
2577 }
2578
2579 QualType ValType = pointerType->getPointeeType();
2580
2581 // Strip any qualifiers off ValType.
2582 ValType = ValType.getUnqualifiedType();
2583 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2584 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2585 !ValType->isVectorType()) {
2586 Diag(DRE->getLocStart(),
2587 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2588 << PointerArg->getType() << PointerArg->getSourceRange();
2589 return ExprError();
2590 }
2591
2592 if (!isStore) {
2593 TheCall->setType(ValType);
2594 return TheCallResult;
2595 }
2596
2597 ExprResult ValArg = TheCall->getArg(0);
2598 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2599 Context, ValType, /*consume*/ false);
2600 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2601 if (ValArg.isInvalid())
2602 return ExprError();
2603
2604 TheCall->setArg(0, ValArg.get());
2605 TheCall->setType(Context.VoidTy);
2606 return TheCallResult;
2607}
2608
Chris Lattner6436fb62009-02-18 06:01:06 +00002609/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002610/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002611/// Note: It might also make sense to do the UTF-16 conversion here (would
2612/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002613bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002614 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002615 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2616
Douglas Gregorfb65e592011-07-27 05:40:30 +00002617 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002618 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2619 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002620 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002621 }
Mike Stump11289f42009-09-09 15:08:12 +00002622
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002623 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002624 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002625 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002626 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002627 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002628 UTF16 *ToPtr = &ToBuf[0];
2629
2630 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2631 &ToPtr, ToPtr + NumBytes,
2632 strictConversion);
2633 // Check for conversion failure.
2634 if (Result != conversionOK)
2635 Diag(Arg->getLocStart(),
2636 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2637 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002638 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002639}
2640
Charles Davisc7d5c942015-09-17 20:55:33 +00002641/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2642/// for validity. Emit an error and return true on failure; return false
2643/// on success.
2644bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002645 Expr *Fn = TheCall->getCallee();
2646 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002647 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002648 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002649 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2650 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002651 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002652 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002653 return true;
2654 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002655
2656 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002657 return Diag(TheCall->getLocEnd(),
2658 diag::err_typecheck_call_too_few_args_at_least)
2659 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002660 }
2661
John McCall29ad95b2011-08-27 01:09:30 +00002662 // Type-check the first argument normally.
2663 if (checkBuiltinArgument(*this, TheCall, 0))
2664 return true;
2665
Chris Lattnere202e6a2007-12-20 00:05:45 +00002666 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002667 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002668 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002669 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002670 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002671 else if (FunctionDecl *FD = getCurFunctionDecl())
2672 isVariadic = FD->isVariadic();
2673 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002674 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002675
Chris Lattnere202e6a2007-12-20 00:05:45 +00002676 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002677 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2678 return true;
2679 }
Mike Stump11289f42009-09-09 15:08:12 +00002680
Chris Lattner43be2e62007-12-19 23:59:04 +00002681 // Verify that the second argument to the builtin is the last argument of the
2682 // current function or method.
2683 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002684 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002685
Nico Weber9eea7642013-05-24 23:31:57 +00002686 // These are valid if SecondArgIsLastNamedArgument is false after the next
2687 // block.
2688 QualType Type;
2689 SourceLocation ParamLoc;
2690
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002691 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2692 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002693 // FIXME: This isn't correct for methods (results in bogus warning).
2694 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002695 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002696 if (CurBlock)
2697 LastArg = *(CurBlock->TheDecl->param_end()-1);
2698 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002699 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002700 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002701 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002702 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002703
2704 Type = PV->getType();
2705 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002706 }
2707 }
Mike Stump11289f42009-09-09 15:08:12 +00002708
Chris Lattner43be2e62007-12-19 23:59:04 +00002709 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002710 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002711 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002712 else if (Type->isReferenceType()) {
2713 Diag(Arg->getLocStart(),
2714 diag::warn_va_start_of_reference_type_is_undefined);
2715 Diag(ParamLoc, diag::note_parameter_type) << Type;
2716 }
2717
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002718 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002719 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002720}
Chris Lattner43be2e62007-12-19 23:59:04 +00002721
Charles Davisc7d5c942015-09-17 20:55:33 +00002722/// Check the arguments to '__builtin_va_start' for validity, and that
2723/// it was called from a function of the native ABI.
2724/// Emit an error and return true on failure; return false on success.
2725bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2726 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2727 // On x64 Windows, don't allow this in System V ABI functions.
2728 // (Yes, that means there's no corresponding way to support variadic
2729 // System V ABI functions on Windows.)
2730 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2731 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2732 clang::CallingConv CC = CC_C;
2733 if (const FunctionDecl *FD = getCurFunctionDecl())
2734 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2735 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2736 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2737 return Diag(TheCall->getCallee()->getLocStart(),
2738 diag::err_va_start_used_in_wrong_abi_function)
2739 << (OS != llvm::Triple::Win32);
2740 }
2741 return SemaBuiltinVAStartImpl(TheCall);
2742}
2743
2744/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2745/// it was called from a Win64 ABI function.
2746/// Emit an error and return true on failure; return false on success.
2747bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2748 // This only makes sense for x86-64.
2749 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2750 Expr *Callee = TheCall->getCallee();
2751 if (TT.getArch() != llvm::Triple::x86_64)
2752 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2753 // Don't allow this in System V ABI functions.
2754 clang::CallingConv CC = CC_C;
2755 if (const FunctionDecl *FD = getCurFunctionDecl())
2756 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2757 if (CC == CC_X86_64SysV ||
2758 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2759 return Diag(Callee->getLocStart(),
2760 diag::err_ms_va_start_used_in_sysv_function);
2761 return SemaBuiltinVAStartImpl(TheCall);
2762}
2763
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002764bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2765 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2766 // const char *named_addr);
2767
2768 Expr *Func = Call->getCallee();
2769
2770 if (Call->getNumArgs() < 3)
2771 return Diag(Call->getLocEnd(),
2772 diag::err_typecheck_call_too_few_args_at_least)
2773 << 0 /*function call*/ << 3 << Call->getNumArgs();
2774
2775 // Determine whether the current function is variadic or not.
2776 bool IsVariadic;
2777 if (BlockScopeInfo *CurBlock = getCurBlock())
2778 IsVariadic = CurBlock->TheDecl->isVariadic();
2779 else if (FunctionDecl *FD = getCurFunctionDecl())
2780 IsVariadic = FD->isVariadic();
2781 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2782 IsVariadic = MD->isVariadic();
2783 else
2784 llvm_unreachable("unexpected statement type");
2785
2786 if (!IsVariadic) {
2787 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2788 return true;
2789 }
2790
2791 // Type-check the first argument normally.
2792 if (checkBuiltinArgument(*this, Call, 0))
2793 return true;
2794
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002795 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002796 unsigned ArgNo;
2797 QualType Type;
2798 } ArgumentTypes[] = {
2799 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2800 { 2, Context.getSizeType() },
2801 };
2802
2803 for (const auto &AT : ArgumentTypes) {
2804 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2805 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2806 continue;
2807 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2808 << Arg->getType() << AT.Type << 1 /* different class */
2809 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2810 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2811 }
2812
2813 return false;
2814}
2815
Chris Lattner2da14fb2007-12-20 00:26:33 +00002816/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2817/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002818bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2819 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002820 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002821 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002822 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002823 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002824 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002825 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002826 << SourceRange(TheCall->getArg(2)->getLocStart(),
2827 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002828
John Wiegley01296292011-04-08 18:41:53 +00002829 ExprResult OrigArg0 = TheCall->getArg(0);
2830 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002831
Chris Lattner2da14fb2007-12-20 00:26:33 +00002832 // Do standard promotions between the two arguments, returning their common
2833 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002834 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002835 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2836 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002837
2838 // Make sure any conversions are pushed back into the call; this is
2839 // type safe since unordered compare builtins are declared as "_Bool
2840 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002841 TheCall->setArg(0, OrigArg0.get());
2842 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002843
John Wiegley01296292011-04-08 18:41:53 +00002844 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002845 return false;
2846
Chris Lattner2da14fb2007-12-20 00:26:33 +00002847 // If the common type isn't a real floating type, then the arguments were
2848 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002849 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002850 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002851 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002852 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2853 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002854
Chris Lattner2da14fb2007-12-20 00:26:33 +00002855 return false;
2856}
2857
Benjamin Kramer634fc102010-02-15 22:42:31 +00002858/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2859/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002860/// to check everything. We expect the last argument to be a floating point
2861/// value.
2862bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2863 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002864 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002865 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002866 if (TheCall->getNumArgs() > NumArgs)
2867 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002868 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002869 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002870 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002871 (*(TheCall->arg_end()-1))->getLocEnd());
2872
Benjamin Kramer64aae502010-02-16 10:07:31 +00002873 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002874
Eli Friedman7e4faac2009-08-31 20:06:00 +00002875 if (OrigArg->isTypeDependent())
2876 return false;
2877
Chris Lattner68784ef2010-05-06 05:50:07 +00002878 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002879 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002880 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002881 diag::err_typecheck_call_invalid_unary_fp)
2882 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002883
Chris Lattner68784ef2010-05-06 05:50:07 +00002884 // If this is an implicit conversion from float -> double, remove it.
2885 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2886 Expr *CastArg = Cast->getSubExpr();
2887 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2888 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2889 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002890 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002891 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002892 }
2893 }
2894
Eli Friedman7e4faac2009-08-31 20:06:00 +00002895 return false;
2896}
2897
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002898/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2899// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002900ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002901 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002902 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002903 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002904 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2905 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002906
Nate Begemana0110022010-06-08 00:16:34 +00002907 // Determine which of the following types of shufflevector we're checking:
2908 // 1) unary, vector mask: (lhs, mask)
2909 // 2) binary, vector mask: (lhs, rhs, mask)
2910 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2911 QualType resType = TheCall->getArg(0)->getType();
2912 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002913
Douglas Gregorc25f7662009-05-19 22:10:17 +00002914 if (!TheCall->getArg(0)->isTypeDependent() &&
2915 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002916 QualType LHSType = TheCall->getArg(0)->getType();
2917 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002918
Craig Topperbaca3892013-07-29 06:47:04 +00002919 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2920 return ExprError(Diag(TheCall->getLocStart(),
2921 diag::err_shufflevector_non_vector)
2922 << SourceRange(TheCall->getArg(0)->getLocStart(),
2923 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002924
Nate Begemana0110022010-06-08 00:16:34 +00002925 numElements = LHSType->getAs<VectorType>()->getNumElements();
2926 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002927
Nate Begemana0110022010-06-08 00:16:34 +00002928 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2929 // with mask. If so, verify that RHS is an integer vector type with the
2930 // same number of elts as lhs.
2931 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002932 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002933 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002934 return ExprError(Diag(TheCall->getLocStart(),
2935 diag::err_shufflevector_incompatible_vector)
2936 << SourceRange(TheCall->getArg(1)->getLocStart(),
2937 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002938 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002939 return ExprError(Diag(TheCall->getLocStart(),
2940 diag::err_shufflevector_incompatible_vector)
2941 << SourceRange(TheCall->getArg(0)->getLocStart(),
2942 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002943 } else if (numElements != numResElements) {
2944 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002945 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002946 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002947 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002948 }
2949
2950 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002951 if (TheCall->getArg(i)->isTypeDependent() ||
2952 TheCall->getArg(i)->isValueDependent())
2953 continue;
2954
Nate Begemana0110022010-06-08 00:16:34 +00002955 llvm::APSInt Result(32);
2956 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2957 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002958 diag::err_shufflevector_nonconstant_argument)
2959 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002960
Craig Topper50ad5b72013-08-03 17:40:38 +00002961 // Allow -1 which will be translated to undef in the IR.
2962 if (Result.isSigned() && Result.isAllOnesValue())
2963 continue;
2964
Chris Lattner7ab824e2008-08-10 02:05:13 +00002965 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002966 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002967 diag::err_shufflevector_argument_too_large)
2968 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002969 }
2970
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002971 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002972
Chris Lattner7ab824e2008-08-10 02:05:13 +00002973 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002974 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002975 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002976 }
2977
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002978 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2979 TheCall->getCallee()->getLocStart(),
2980 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002981}
Chris Lattner43be2e62007-12-19 23:59:04 +00002982
Hal Finkelc4d7c822013-09-18 03:29:45 +00002983/// SemaConvertVectorExpr - Handle __builtin_convertvector
2984ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2985 SourceLocation BuiltinLoc,
2986 SourceLocation RParenLoc) {
2987 ExprValueKind VK = VK_RValue;
2988 ExprObjectKind OK = OK_Ordinary;
2989 QualType DstTy = TInfo->getType();
2990 QualType SrcTy = E->getType();
2991
2992 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2993 return ExprError(Diag(BuiltinLoc,
2994 diag::err_convertvector_non_vector)
2995 << E->getSourceRange());
2996 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2997 return ExprError(Diag(BuiltinLoc,
2998 diag::err_convertvector_non_vector_type));
2999
3000 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3001 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3002 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3003 if (SrcElts != DstElts)
3004 return ExprError(Diag(BuiltinLoc,
3005 diag::err_convertvector_incompatible_vector)
3006 << E->getSourceRange());
3007 }
3008
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003009 return new (Context)
3010 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003011}
3012
Daniel Dunbarb7257262008-07-21 22:59:13 +00003013/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3014// This is declared to take (const void*, ...) and can take two
3015// optional constant int args.
3016bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003017 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003018
Chris Lattner3b054132008-11-19 05:08:23 +00003019 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003020 return Diag(TheCall->getLocEnd(),
3021 diag::err_typecheck_call_too_many_args_at_most)
3022 << 0 /*function call*/ << 3 << NumArgs
3023 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003024
3025 // Argument 0 is checked for us and the remaining arguments must be
3026 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003027 for (unsigned i = 1; i != NumArgs; ++i)
3028 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003029 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003030
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003031 return false;
3032}
3033
Hal Finkelf0417332014-07-17 14:25:55 +00003034/// SemaBuiltinAssume - Handle __assume (MS Extension).
3035// __assume does not evaluate its arguments, and should warn if its argument
3036// has side effects.
3037bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3038 Expr *Arg = TheCall->getArg(0);
3039 if (Arg->isInstantiationDependent()) return false;
3040
3041 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003042 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003043 << Arg->getSourceRange()
3044 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3045
3046 return false;
3047}
3048
3049/// Handle __builtin_assume_aligned. This is declared
3050/// as (const void*, size_t, ...) and can take one optional constant int arg.
3051bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3052 unsigned NumArgs = TheCall->getNumArgs();
3053
3054 if (NumArgs > 3)
3055 return Diag(TheCall->getLocEnd(),
3056 diag::err_typecheck_call_too_many_args_at_most)
3057 << 0 /*function call*/ << 3 << NumArgs
3058 << TheCall->getSourceRange();
3059
3060 // The alignment must be a constant integer.
3061 Expr *Arg = TheCall->getArg(1);
3062
3063 // We can't check the value of a dependent argument.
3064 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3065 llvm::APSInt Result;
3066 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3067 return true;
3068
3069 if (!Result.isPowerOf2())
3070 return Diag(TheCall->getLocStart(),
3071 diag::err_alignment_not_power_of_two)
3072 << Arg->getSourceRange();
3073 }
3074
3075 if (NumArgs > 2) {
3076 ExprResult Arg(TheCall->getArg(2));
3077 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3078 Context.getSizeType(), false);
3079 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3080 if (Arg.isInvalid()) return true;
3081 TheCall->setArg(2, Arg.get());
3082 }
Hal Finkelf0417332014-07-17 14:25:55 +00003083
3084 return false;
3085}
3086
Eric Christopher8d0c6212010-04-17 02:26:23 +00003087/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3088/// TheCall is a constant expression.
3089bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3090 llvm::APSInt &Result) {
3091 Expr *Arg = TheCall->getArg(ArgNum);
3092 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3093 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3094
3095 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3096
3097 if (!Arg->isIntegerConstantExpr(Result, Context))
3098 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003099 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003100
Chris Lattnerd545ad12009-09-23 06:06:36 +00003101 return false;
3102}
3103
Richard Sandiford28940af2014-04-16 08:47:51 +00003104/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3105/// TheCall is a constant expression in the range [Low, High].
3106bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3107 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003108 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003109
3110 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003111 Expr *Arg = TheCall->getArg(ArgNum);
3112 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003113 return false;
3114
Eric Christopher8d0c6212010-04-17 02:26:23 +00003115 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003116 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003117 return true;
3118
Richard Sandiford28940af2014-04-16 08:47:51 +00003119 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003120 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003121 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003122
3123 return false;
3124}
3125
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003126/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3127/// TheCall is an ARM/AArch64 special register string literal.
3128bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3129 int ArgNum, unsigned ExpectedFieldNum,
3130 bool AllowName) {
3131 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3132 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3133 BuiltinID == ARM::BI__builtin_arm_rsr ||
3134 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3135 BuiltinID == ARM::BI__builtin_arm_wsr ||
3136 BuiltinID == ARM::BI__builtin_arm_wsrp;
3137 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3138 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3139 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3140 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3141 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3142 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3143 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3144
3145 // We can't check the value of a dependent argument.
3146 Expr *Arg = TheCall->getArg(ArgNum);
3147 if (Arg->isTypeDependent() || Arg->isValueDependent())
3148 return false;
3149
3150 // Check if the argument is a string literal.
3151 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3152 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3153 << Arg->getSourceRange();
3154
3155 // Check the type of special register given.
3156 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3157 SmallVector<StringRef, 6> Fields;
3158 Reg.split(Fields, ":");
3159
3160 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3161 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3162 << Arg->getSourceRange();
3163
3164 // If the string is the name of a register then we cannot check that it is
3165 // valid here but if the string is of one the forms described in ACLE then we
3166 // can check that the supplied fields are integers and within the valid
3167 // ranges.
3168 if (Fields.size() > 1) {
3169 bool FiveFields = Fields.size() == 5;
3170
3171 bool ValidString = true;
3172 if (IsARMBuiltin) {
3173 ValidString &= Fields[0].startswith_lower("cp") ||
3174 Fields[0].startswith_lower("p");
3175 if (ValidString)
3176 Fields[0] =
3177 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3178
3179 ValidString &= Fields[2].startswith_lower("c");
3180 if (ValidString)
3181 Fields[2] = Fields[2].drop_front(1);
3182
3183 if (FiveFields) {
3184 ValidString &= Fields[3].startswith_lower("c");
3185 if (ValidString)
3186 Fields[3] = Fields[3].drop_front(1);
3187 }
3188 }
3189
3190 SmallVector<int, 5> Ranges;
3191 if (FiveFields)
3192 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3193 else
3194 Ranges.append({15, 7, 15});
3195
3196 for (unsigned i=0; i<Fields.size(); ++i) {
3197 int IntField;
3198 ValidString &= !Fields[i].getAsInteger(10, IntField);
3199 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3200 }
3201
3202 if (!ValidString)
3203 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3204 << Arg->getSourceRange();
3205
3206 } else if (IsAArch64Builtin && Fields.size() == 1) {
3207 // If the register name is one of those that appear in the condition below
3208 // and the special register builtin being used is one of the write builtins,
3209 // then we require that the argument provided for writing to the register
3210 // is an integer constant expression. This is because it will be lowered to
3211 // an MSR (immediate) instruction, so we need to know the immediate at
3212 // compile time.
3213 if (TheCall->getNumArgs() != 2)
3214 return false;
3215
3216 std::string RegLower = Reg.lower();
3217 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3218 RegLower != "pan" && RegLower != "uao")
3219 return false;
3220
3221 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3222 }
3223
3224 return false;
3225}
3226
Eli Friedmanc97d0142009-05-03 06:04:26 +00003227/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003228/// This checks that the target supports __builtin_longjmp and
3229/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003230bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003231 if (!Context.getTargetInfo().hasSjLjLowering())
3232 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3233 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3234
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003235 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003236 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003237
Eric Christopher8d0c6212010-04-17 02:26:23 +00003238 // TODO: This is less than ideal. Overload this to take a value.
3239 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3240 return true;
3241
3242 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003243 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3244 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3245
3246 return false;
3247}
3248
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003249/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3250/// This checks that the target supports __builtin_setjmp.
3251bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3252 if (!Context.getTargetInfo().hasSjLjLowering())
3253 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3254 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3255 return false;
3256}
3257
Richard Smithd7293d72013-08-05 18:49:43 +00003258namespace {
3259enum StringLiteralCheckType {
3260 SLCT_NotALiteral,
3261 SLCT_UncheckedLiteral,
3262 SLCT_CheckedLiteral
3263};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003264} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003265
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003266static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3267 const Expr *OrigFormatExpr,
3268 ArrayRef<const Expr *> Args,
3269 bool HasVAListArg, unsigned format_idx,
3270 unsigned firstDataArg,
3271 Sema::FormatStringType Type,
3272 bool inFunctionCall,
3273 Sema::VariadicCallType CallType,
3274 llvm::SmallBitVector &CheckedVarArgs);
3275
Richard Smith55ce3522012-06-25 20:30:08 +00003276// Determine if an expression is a string literal or constant string.
3277// If this function returns false on the arguments to a function expecting a
3278// format string, we will usually need to emit a warning.
3279// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003280static StringLiteralCheckType
3281checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3282 bool HasVAListArg, unsigned format_idx,
3283 unsigned firstDataArg, Sema::FormatStringType Type,
3284 Sema::VariadicCallType CallType, bool InFunctionCall,
3285 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00003286 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003287 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003288 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003289
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003290 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003291
Richard Smithd7293d72013-08-05 18:49:43 +00003292 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003293 // Technically -Wformat-nonliteral does not warn about this case.
3294 // The behavior of printf and friends in this case is implementation
3295 // dependent. Ideally if the format string cannot be null then
3296 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003297 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003298
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003299 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003300 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003301 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003302 // The expression is a literal if both sub-expressions were, and it was
3303 // completely checked only if both sub-expressions were checked.
3304 const AbstractConditionalOperator *C =
3305 cast<AbstractConditionalOperator>(E);
3306 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00003307 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003308 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003309 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003310 if (Left == SLCT_NotALiteral)
3311 return SLCT_NotALiteral;
3312 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003313 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003314 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003315 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003316 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003317 }
3318
3319 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003320 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3321 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003322 }
3323
John McCallc07a0c72011-02-17 10:25:35 +00003324 case Stmt::OpaqueValueExprClass:
3325 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3326 E = src;
3327 goto tryAgain;
3328 }
Richard Smith55ce3522012-06-25 20:30:08 +00003329 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003330
Ted Kremeneka8890832011-02-24 23:03:04 +00003331 case Stmt::PredefinedExprClass:
3332 // While __func__, etc., are technically not string literals, they
3333 // cannot contain format specifiers and thus are not a security
3334 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003335 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003336
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003337 case Stmt::DeclRefExprClass: {
3338 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003339
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003340 // As an exception, do not flag errors for variables binding to
3341 // const string literals.
3342 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3343 bool isConstant = false;
3344 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003345
Richard Smithd7293d72013-08-05 18:49:43 +00003346 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3347 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003348 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003349 isConstant = T.isConstant(S.Context) &&
3350 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003351 } else if (T->isObjCObjectPointerType()) {
3352 // In ObjC, there is usually no "const ObjectPointer" type,
3353 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003354 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003355 }
Mike Stump11289f42009-09-09 15:08:12 +00003356
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003357 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003358 if (const Expr *Init = VD->getAnyInitializer()) {
3359 // Look through initializers like const char c[] = { "foo" }
3360 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3361 if (InitList->isStringLiteralInit())
3362 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3363 }
Richard Smithd7293d72013-08-05 18:49:43 +00003364 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003365 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003366 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003367 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003368 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003369 }
Mike Stump11289f42009-09-09 15:08:12 +00003370
Anders Carlssonb012ca92009-06-28 19:55:58 +00003371 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3372 // special check to see if the format string is a function parameter
3373 // of the function calling the printf function. If the function
3374 // has an attribute indicating it is a printf-like function, then we
3375 // should suppress warnings concerning non-literals being used in a call
3376 // to a vprintf function. For example:
3377 //
3378 // void
3379 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3380 // va_list ap;
3381 // va_start(ap, fmt);
3382 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3383 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003384 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003385 if (HasVAListArg) {
3386 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3387 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3388 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003389 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003390 // adjust for implicit parameter
3391 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3392 if (MD->isInstance())
3393 ++PVIndex;
3394 // We also check if the formats are compatible.
3395 // We can't pass a 'scanf' string to a 'printf' function.
3396 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003397 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003398 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003399 }
3400 }
3401 }
3402 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003403 }
Mike Stump11289f42009-09-09 15:08:12 +00003404
Richard Smith55ce3522012-06-25 20:30:08 +00003405 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003406 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003407
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003408 case Stmt::CallExprClass:
3409 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003410 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003411 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3412 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3413 unsigned ArgIndex = FA->getFormatIdx();
3414 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3415 if (MD->isInstance())
3416 --ArgIndex;
3417 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003418
Richard Smithd7293d72013-08-05 18:49:43 +00003419 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003420 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003421 Type, CallType, InFunctionCall,
3422 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003423 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3424 unsigned BuiltinID = FD->getBuiltinID();
3425 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3426 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3427 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003428 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003429 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003430 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003431 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003432 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003433 }
3434 }
Mike Stump11289f42009-09-09 15:08:12 +00003435
Richard Smith55ce3522012-06-25 20:30:08 +00003436 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003437 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003438 case Stmt::ObjCStringLiteralClass:
3439 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003440 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003441
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003442 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003443 StrE = ObjCFExpr->getString();
3444 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003445 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003446
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003447 if (StrE) {
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003448 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
3449 firstDataArg, Type, InFunctionCall, CallType,
3450 CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003451 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003452 }
Mike Stump11289f42009-09-09 15:08:12 +00003453
Richard Smith55ce3522012-06-25 20:30:08 +00003454 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003455 }
Mike Stump11289f42009-09-09 15:08:12 +00003456
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003457 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003458 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003459 }
3460}
3461
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003462Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003463 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003464 .Case("scanf", FST_Scanf)
3465 .Cases("printf", "printf0", FST_Printf)
3466 .Cases("NSString", "CFString", FST_NSString)
3467 .Case("strftime", FST_Strftime)
3468 .Case("strfmon", FST_Strfmon)
3469 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003470 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003471 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003472 .Default(FST_Unknown);
3473}
3474
Jordan Rose3e0ec582012-07-19 18:10:23 +00003475/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003476/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003477/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003478bool Sema::CheckFormatArguments(const FormatAttr *Format,
3479 ArrayRef<const Expr *> Args,
3480 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003481 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003482 SourceLocation Loc, SourceRange Range,
3483 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003484 FormatStringInfo FSI;
3485 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003486 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003487 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003488 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003489 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003490}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003491
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003492bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003493 bool HasVAListArg, unsigned format_idx,
3494 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003495 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003496 SourceLocation Loc, SourceRange Range,
3497 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003498 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003499 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003500 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003501 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003502 }
Mike Stump11289f42009-09-09 15:08:12 +00003503
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003504 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003505
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003506 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003507 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003508 // Dynamically generated format strings are difficult to
3509 // automatically vet at compile time. Requiring that format strings
3510 // are string literals: (1) permits the checking of format strings by
3511 // the compiler and thereby (2) can practically remove the source of
3512 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003513
Mike Stump11289f42009-09-09 15:08:12 +00003514 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003515 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003516 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003517 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003518 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003519 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3520 format_idx, firstDataArg, Type, CallType,
3521 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003522 if (CT != SLCT_NotALiteral)
3523 // Literal format string found, check done!
3524 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003525
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003526 // Strftime is particular as it always uses a single 'time' argument,
3527 // so it is safe to pass a non-literal string.
3528 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003529 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003530
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003531 // Do not emit diag when the string param is a macro expansion and the
3532 // format is either NSString or CFString. This is a hack to prevent
3533 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3534 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003535 if (Type == FST_NSString &&
3536 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003537 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003538
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003539 // If there are no arguments specified, warn with -Wformat-security, otherwise
3540 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003541 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003542 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003543 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003544 << OrigFormatExpr->getSourceRange();
3545 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003546 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003547 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003548 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003549 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003550}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003551
Ted Kremenekab278de2010-01-28 23:39:18 +00003552namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003553class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3554protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003555 Sema &S;
3556 const StringLiteral *FExpr;
3557 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003558 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003559 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003560 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003561 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003562 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003563 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003564 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003565 bool usesPositionalArgs;
3566 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003567 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003568 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003569 llvm::SmallBitVector &CheckedVarArgs;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003570
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003571public:
Ted Kremenek02087932010-07-16 02:11:22 +00003572 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003573 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003574 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003575 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003576 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003577 Sema::VariadicCallType callType,
3578 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00003579 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003580 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3581 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003582 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003583 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003584 inFunctionCall(inFunctionCall), CallType(callType),
3585 CheckedVarArgs(CheckedVarArgs) {
3586 CoveredArgs.resize(numDataArgs);
3587 CoveredArgs.reset();
3588 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003589
Ted Kremenek019d2242010-01-29 01:50:07 +00003590 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003591
Ted Kremenek02087932010-07-16 02:11:22 +00003592 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003593 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003594
Jordan Rose92303592012-09-08 04:00:03 +00003595 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003596 const analyze_format_string::FormatSpecifier &FS,
3597 const analyze_format_string::ConversionSpecifier &CS,
3598 const char *startSpecifier, unsigned specifierLen,
3599 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003600
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003601 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003602 const analyze_format_string::FormatSpecifier &FS,
3603 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003604
3605 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003606 const analyze_format_string::ConversionSpecifier &CS,
3607 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003608
Craig Toppere14c0f82014-03-12 04:55:44 +00003609 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003610
Craig Toppere14c0f82014-03-12 04:55:44 +00003611 void HandleInvalidPosition(const char *startSpecifier,
3612 unsigned specifierLen,
3613 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003614
Craig Toppere14c0f82014-03-12 04:55:44 +00003615 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003616
Craig Toppere14c0f82014-03-12 04:55:44 +00003617 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003618
Richard Trieu03cf7b72011-10-28 00:41:25 +00003619 template <typename Range>
3620 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3621 const Expr *ArgumentExpr,
3622 PartialDiagnostic PDiag,
3623 SourceLocation StringLoc,
3624 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003625 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003626
Ted Kremenek02087932010-07-16 02:11:22 +00003627protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003628 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3629 const char *startSpec,
3630 unsigned specifierLen,
3631 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003632
3633 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3634 const char *startSpec,
3635 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003636
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003637 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003638 CharSourceRange getSpecifierRange(const char *startSpecifier,
3639 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003640 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003641
Ted Kremenek5739de72010-01-29 01:06:55 +00003642 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003643
3644 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3645 const analyze_format_string::ConversionSpecifier &CS,
3646 const char *startSpecifier, unsigned specifierLen,
3647 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003648
3649 template <typename Range>
3650 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3651 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003652 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003653};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003654} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00003655
Ted Kremenek02087932010-07-16 02:11:22 +00003656SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003657 return OrigFormatExpr->getSourceRange();
3658}
3659
Ted Kremenek02087932010-07-16 02:11:22 +00003660CharSourceRange CheckFormatHandler::
3661getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003662 SourceLocation Start = getLocationOfByte(startSpecifier);
3663 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3664
3665 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003666 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003667
3668 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003669}
3670
Ted Kremenek02087932010-07-16 02:11:22 +00003671SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003672 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003673}
3674
Ted Kremenek02087932010-07-16 02:11:22 +00003675void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3676 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003677 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3678 getLocationOfByte(startSpecifier),
3679 /*IsStringLocation*/true,
3680 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003681}
3682
Jordan Rose92303592012-09-08 04:00:03 +00003683void CheckFormatHandler::HandleInvalidLengthModifier(
3684 const analyze_format_string::FormatSpecifier &FS,
3685 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003686 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003687 using namespace analyze_format_string;
3688
3689 const LengthModifier &LM = FS.getLengthModifier();
3690 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3691
3692 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003693 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003694 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003695 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003696 getLocationOfByte(LM.getStart()),
3697 /*IsStringLocation*/true,
3698 getSpecifierRange(startSpecifier, specifierLen));
3699
3700 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3701 << FixedLM->toString()
3702 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3703
3704 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003705 FixItHint Hint;
3706 if (DiagID == diag::warn_format_nonsensical_length)
3707 Hint = FixItHint::CreateRemoval(LMRange);
3708
3709 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003710 getLocationOfByte(LM.getStart()),
3711 /*IsStringLocation*/true,
3712 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003713 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003714 }
3715}
3716
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003717void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003718 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003719 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003720 using namespace analyze_format_string;
3721
3722 const LengthModifier &LM = FS.getLengthModifier();
3723 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3724
3725 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003726 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003727 if (FixedLM) {
3728 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3729 << LM.toString() << 0,
3730 getLocationOfByte(LM.getStart()),
3731 /*IsStringLocation*/true,
3732 getSpecifierRange(startSpecifier, specifierLen));
3733
3734 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3735 << FixedLM->toString()
3736 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3737
3738 } else {
3739 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3740 << LM.toString() << 0,
3741 getLocationOfByte(LM.getStart()),
3742 /*IsStringLocation*/true,
3743 getSpecifierRange(startSpecifier, specifierLen));
3744 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003745}
3746
3747void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3748 const analyze_format_string::ConversionSpecifier &CS,
3749 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003750 using namespace analyze_format_string;
3751
3752 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003753 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003754 if (FixedCS) {
3755 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3756 << CS.toString() << /*conversion specifier*/1,
3757 getLocationOfByte(CS.getStart()),
3758 /*IsStringLocation*/true,
3759 getSpecifierRange(startSpecifier, specifierLen));
3760
3761 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3762 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3763 << FixedCS->toString()
3764 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3765 } else {
3766 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3767 << CS.toString() << /*conversion specifier*/1,
3768 getLocationOfByte(CS.getStart()),
3769 /*IsStringLocation*/true,
3770 getSpecifierRange(startSpecifier, specifierLen));
3771 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003772}
3773
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003774void CheckFormatHandler::HandlePosition(const char *startPos,
3775 unsigned posLen) {
3776 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3777 getLocationOfByte(startPos),
3778 /*IsStringLocation*/true,
3779 getSpecifierRange(startPos, posLen));
3780}
3781
Ted Kremenekd1668192010-02-27 01:41:03 +00003782void
Ted Kremenek02087932010-07-16 02:11:22 +00003783CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3784 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003785 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3786 << (unsigned) p,
3787 getLocationOfByte(startPos), /*IsStringLocation*/true,
3788 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003789}
3790
Ted Kremenek02087932010-07-16 02:11:22 +00003791void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003792 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003793 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3794 getLocationOfByte(startPos),
3795 /*IsStringLocation*/true,
3796 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003797}
3798
Ted Kremenek02087932010-07-16 02:11:22 +00003799void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003800 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003801 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003802 EmitFormatDiagnostic(
3803 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3804 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3805 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003806 }
Ted Kremenek02087932010-07-16 02:11:22 +00003807}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003808
Jordan Rose58bbe422012-07-19 18:10:08 +00003809// Note that this may return NULL if there was an error parsing or building
3810// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003811const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003812 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003813}
3814
3815void CheckFormatHandler::DoneProcessing() {
3816 // Does the number of data arguments exceed the number of
3817 // format conversions in the format string?
3818 if (!HasVAListArg) {
3819 // Find any arguments that weren't covered.
3820 CoveredArgs.flip();
3821 signed notCoveredArg = CoveredArgs.find_first();
3822 if (notCoveredArg >= 0) {
3823 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003824 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3825 SourceLocation Loc = E->getLocStart();
3826 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3827 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3828 Loc, /*IsStringLocation*/false,
3829 getFormatStringRange());
3830 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003831 }
Ted Kremenek02087932010-07-16 02:11:22 +00003832 }
3833 }
3834}
3835
Ted Kremenekce815422010-07-19 21:25:57 +00003836bool
3837CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3838 SourceLocation Loc,
3839 const char *startSpec,
3840 unsigned specifierLen,
3841 const char *csStart,
3842 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00003843 bool keepGoing = true;
3844 if (argIndex < NumDataArgs) {
3845 // Consider the argument coverered, even though the specifier doesn't
3846 // make sense.
3847 CoveredArgs.set(argIndex);
3848 }
3849 else {
3850 // If argIndex exceeds the number of data arguments we
3851 // don't issue a warning because that is just a cascade of warnings (and
3852 // they may have intended '%%' anyway). We don't want to continue processing
3853 // the format string after this point, however, as we will like just get
3854 // gibberish when trying to match arguments.
3855 keepGoing = false;
3856 }
3857
Richard Trieu03cf7b72011-10-28 00:41:25 +00003858 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3859 << StringRef(csStart, csLen),
3860 Loc, /*IsStringLocation*/true,
3861 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003862
3863 return keepGoing;
3864}
3865
Richard Trieu03cf7b72011-10-28 00:41:25 +00003866void
3867CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3868 const char *startSpec,
3869 unsigned specifierLen) {
3870 EmitFormatDiagnostic(
3871 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3872 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3873}
3874
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003875bool
3876CheckFormatHandler::CheckNumArgs(
3877 const analyze_format_string::FormatSpecifier &FS,
3878 const analyze_format_string::ConversionSpecifier &CS,
3879 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3880
3881 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003882 PartialDiagnostic PDiag = FS.usesPositionalArg()
3883 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3884 << (argIndex+1) << NumDataArgs)
3885 : S.PDiag(diag::warn_printf_insufficient_data_args);
3886 EmitFormatDiagnostic(
3887 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3888 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003889 return false;
3890 }
3891 return true;
3892}
3893
Richard Trieu03cf7b72011-10-28 00:41:25 +00003894template<typename Range>
3895void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3896 SourceLocation Loc,
3897 bool IsStringLocation,
3898 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003899 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003900 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003901 Loc, IsStringLocation, StringRange, FixIt);
3902}
3903
3904/// \brief If the format string is not within the funcion call, emit a note
3905/// so that the function call and string are in diagnostic messages.
3906///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003907/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003908/// call and only one diagnostic message will be produced. Otherwise, an
3909/// extra note will be emitted pointing to location of the format string.
3910///
3911/// \param ArgumentExpr the expression that is passed as the format string
3912/// argument in the function call. Used for getting locations when two
3913/// diagnostics are emitted.
3914///
3915/// \param PDiag the callee should already have provided any strings for the
3916/// diagnostic message. This function only adds locations and fixits
3917/// to diagnostics.
3918///
3919/// \param Loc primary location for diagnostic. If two diagnostics are
3920/// required, one will be at Loc and a new SourceLocation will be created for
3921/// the other one.
3922///
3923/// \param IsStringLocation if true, Loc points to the format string should be
3924/// used for the note. Otherwise, Loc points to the argument list and will
3925/// be used with PDiag.
3926///
3927/// \param StringRange some or all of the string to highlight. This is
3928/// templated so it can accept either a CharSourceRange or a SourceRange.
3929///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003930/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003931template<typename Range>
3932void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3933 const Expr *ArgumentExpr,
3934 PartialDiagnostic PDiag,
3935 SourceLocation Loc,
3936 bool IsStringLocation,
3937 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003938 ArrayRef<FixItHint> FixIt) {
3939 if (InFunctionCall) {
3940 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3941 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003942 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003943 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003944 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3945 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003946
3947 const Sema::SemaDiagnosticBuilder &Note =
3948 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3949 diag::note_format_string_defined);
3950
3951 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003952 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003953 }
3954}
3955
Ted Kremenek02087932010-07-16 02:11:22 +00003956//===--- CHECK: Printf format string checking ------------------------------===//
3957
3958namespace {
3959class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003960 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003961
Ted Kremenek02087932010-07-16 02:11:22 +00003962public:
3963 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3964 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003965 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003966 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003967 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003968 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003969 Sema::VariadicCallType CallType,
3970 llvm::SmallBitVector &CheckedVarArgs)
3971 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3972 numDataArgs, beg, hasVAListArg, Args,
3973 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3974 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003975 {}
3976
Ted Kremenek02087932010-07-16 02:11:22 +00003977 bool HandleInvalidPrintfConversionSpecifier(
3978 const analyze_printf::PrintfSpecifier &FS,
3979 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003980 unsigned specifierLen) override;
3981
Ted Kremenek02087932010-07-16 02:11:22 +00003982 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3983 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003984 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003985 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3986 const char *StartSpecifier,
3987 unsigned SpecifierLen,
3988 const Expr *E);
3989
Ted Kremenek02087932010-07-16 02:11:22 +00003990 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3991 const char *startSpecifier, unsigned specifierLen);
3992 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3993 const analyze_printf::OptionalAmount &Amt,
3994 unsigned type,
3995 const char *startSpecifier, unsigned specifierLen);
3996 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3997 const analyze_printf::OptionalFlag &flag,
3998 const char *startSpecifier, unsigned specifierLen);
3999 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4000 const analyze_printf::OptionalFlag &ignoredFlag,
4001 const analyze_printf::OptionalFlag &flag,
4002 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004003 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004004 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004005
4006 void HandleEmptyObjCModifierFlag(const char *startFlag,
4007 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004008
Ted Kremenek2b417712015-07-02 05:39:16 +00004009 void HandleInvalidObjCModifierFlag(const char *startFlag,
4010 unsigned flagLen) override;
4011
4012 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4013 const char *flagsEnd,
4014 const char *conversionPosition)
4015 override;
4016};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004017} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004018
4019bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4020 const analyze_printf::PrintfSpecifier &FS,
4021 const char *startSpecifier,
4022 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004023 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004024 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004025
Ted Kremenekce815422010-07-19 21:25:57 +00004026 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4027 getLocationOfByte(CS.getStart()),
4028 startSpecifier, specifierLen,
4029 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004030}
4031
Ted Kremenek02087932010-07-16 02:11:22 +00004032bool CheckPrintfHandler::HandleAmount(
4033 const analyze_format_string::OptionalAmount &Amt,
4034 unsigned k, const char *startSpecifier,
4035 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004036 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004037 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004038 unsigned argIndex = Amt.getArgIndex();
4039 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004040 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4041 << k,
4042 getLocationOfByte(Amt.getStart()),
4043 /*IsStringLocation*/true,
4044 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004045 // Don't do any more checking. We will just emit
4046 // spurious errors.
4047 return false;
4048 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004049
Ted Kremenek5739de72010-01-29 01:06:55 +00004050 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004051 // Although not in conformance with C99, we also allow the argument to be
4052 // an 'unsigned int' as that is a reasonably safe case. GCC also
4053 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004054 CoveredArgs.set(argIndex);
4055 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004056 if (!Arg)
4057 return false;
4058
Ted Kremenek5739de72010-01-29 01:06:55 +00004059 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004060
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004061 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4062 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004063
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004064 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004065 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004066 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004067 << T << Arg->getSourceRange(),
4068 getLocationOfByte(Amt.getStart()),
4069 /*IsStringLocation*/true,
4070 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004071 // Don't do any more checking. We will just emit
4072 // spurious errors.
4073 return false;
4074 }
4075 }
4076 }
4077 return true;
4078}
Ted Kremenek5739de72010-01-29 01:06:55 +00004079
Tom Careb49ec692010-06-17 19:00:27 +00004080void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004081 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004082 const analyze_printf::OptionalAmount &Amt,
4083 unsigned type,
4084 const char *startSpecifier,
4085 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004086 const analyze_printf::PrintfConversionSpecifier &CS =
4087 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004088
Richard Trieu03cf7b72011-10-28 00:41:25 +00004089 FixItHint fixit =
4090 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4091 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4092 Amt.getConstantLength()))
4093 : FixItHint();
4094
4095 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4096 << type << CS.toString(),
4097 getLocationOfByte(Amt.getStart()),
4098 /*IsStringLocation*/true,
4099 getSpecifierRange(startSpecifier, specifierLen),
4100 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004101}
4102
Ted Kremenek02087932010-07-16 02:11:22 +00004103void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004104 const analyze_printf::OptionalFlag &flag,
4105 const char *startSpecifier,
4106 unsigned specifierLen) {
4107 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004108 const analyze_printf::PrintfConversionSpecifier &CS =
4109 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004110 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4111 << flag.toString() << CS.toString(),
4112 getLocationOfByte(flag.getPosition()),
4113 /*IsStringLocation*/true,
4114 getSpecifierRange(startSpecifier, specifierLen),
4115 FixItHint::CreateRemoval(
4116 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004117}
4118
4119void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004120 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004121 const analyze_printf::OptionalFlag &ignoredFlag,
4122 const analyze_printf::OptionalFlag &flag,
4123 const char *startSpecifier,
4124 unsigned specifierLen) {
4125 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004126 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4127 << ignoredFlag.toString() << flag.toString(),
4128 getLocationOfByte(ignoredFlag.getPosition()),
4129 /*IsStringLocation*/true,
4130 getSpecifierRange(startSpecifier, specifierLen),
4131 FixItHint::CreateRemoval(
4132 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004133}
4134
Ted Kremenek2b417712015-07-02 05:39:16 +00004135// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4136// bool IsStringLocation, Range StringRange,
4137// ArrayRef<FixItHint> Fixit = None);
4138
4139void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4140 unsigned flagLen) {
4141 // Warn about an empty flag.
4142 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4143 getLocationOfByte(startFlag),
4144 /*IsStringLocation*/true,
4145 getSpecifierRange(startFlag, flagLen));
4146}
4147
4148void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4149 unsigned flagLen) {
4150 // Warn about an invalid flag.
4151 auto Range = getSpecifierRange(startFlag, flagLen);
4152 StringRef flag(startFlag, flagLen);
4153 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4154 getLocationOfByte(startFlag),
4155 /*IsStringLocation*/true,
4156 Range, FixItHint::CreateRemoval(Range));
4157}
4158
4159void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4160 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4161 // Warn about using '[...]' without a '@' conversion.
4162 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4163 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4164 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4165 getLocationOfByte(conversionPosition),
4166 /*IsStringLocation*/true,
4167 Range, FixItHint::CreateRemoval(Range));
4168}
4169
Richard Smith55ce3522012-06-25 20:30:08 +00004170// Determines if the specified is a C++ class or struct containing
4171// a member with the specified name and kind (e.g. a CXXMethodDecl named
4172// "c_str()").
4173template<typename MemberKind>
4174static llvm::SmallPtrSet<MemberKind*, 1>
4175CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4176 const RecordType *RT = Ty->getAs<RecordType>();
4177 llvm::SmallPtrSet<MemberKind*, 1> Results;
4178
4179 if (!RT)
4180 return Results;
4181 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004182 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004183 return Results;
4184
Alp Tokerb6cc5922014-05-03 03:45:55 +00004185 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004186 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004187 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004188
4189 // We just need to include all members of the right kind turned up by the
4190 // filter, at this point.
4191 if (S.LookupQualifiedName(R, RT->getDecl()))
4192 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4193 NamedDecl *decl = (*I)->getUnderlyingDecl();
4194 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4195 Results.insert(FK);
4196 }
4197 return Results;
4198}
4199
Richard Smith2868a732014-02-28 01:36:39 +00004200/// Check if we could call '.c_str()' on an object.
4201///
4202/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4203/// allow the call, or if it would be ambiguous).
4204bool Sema::hasCStrMethod(const Expr *E) {
4205 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4206 MethodSet Results =
4207 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4208 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4209 MI != ME; ++MI)
4210 if ((*MI)->getMinRequiredArguments() == 0)
4211 return true;
4212 return false;
4213}
4214
Richard Smith55ce3522012-06-25 20:30:08 +00004215// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004216// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004217// Returns true when a c_str() conversion method is found.
4218bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004219 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004220 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4221
4222 MethodSet Results =
4223 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4224
4225 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4226 MI != ME; ++MI) {
4227 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004228 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004229 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004230 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004231 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004232 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4233 << "c_str()"
4234 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4235 return true;
4236 }
4237 }
4238
4239 return false;
4240}
4241
Ted Kremenekab278de2010-01-28 23:39:18 +00004242bool
Ted Kremenek02087932010-07-16 02:11:22 +00004243CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004244 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004245 const char *startSpecifier,
4246 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004247 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004248 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004249 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004250
Ted Kremenek6cd69422010-07-19 22:01:06 +00004251 if (FS.consumesDataArgument()) {
4252 if (atFirstArg) {
4253 atFirstArg = false;
4254 usesPositionalArgs = FS.usesPositionalArg();
4255 }
4256 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004257 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4258 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004259 return false;
4260 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004261 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004262
Ted Kremenekd1668192010-02-27 01:41:03 +00004263 // First check if the field width, precision, and conversion specifier
4264 // have matching data arguments.
4265 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4266 startSpecifier, specifierLen)) {
4267 return false;
4268 }
4269
4270 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4271 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004272 return false;
4273 }
4274
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004275 if (!CS.consumesDataArgument()) {
4276 // FIXME: Technically specifying a precision or field width here
4277 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004278 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004279 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004280
Ted Kremenek4a49d982010-02-26 19:18:41 +00004281 // Consume the argument.
4282 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004283 if (argIndex < NumDataArgs) {
4284 // The check to see if the argIndex is valid will come later.
4285 // We set the bit here because we may exit early from this
4286 // function if we encounter some other error.
4287 CoveredArgs.set(argIndex);
4288 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004289
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004290 // FreeBSD kernel extensions.
4291 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4292 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4293 // We need at least two arguments.
4294 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4295 return false;
4296
4297 // Claim the second argument.
4298 CoveredArgs.set(argIndex + 1);
4299
4300 // Type check the first argument (int for %b, pointer for %D)
4301 const Expr *Ex = getDataArg(argIndex);
4302 const analyze_printf::ArgType &AT =
4303 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4304 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4305 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4306 EmitFormatDiagnostic(
4307 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4308 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4309 << false << Ex->getSourceRange(),
4310 Ex->getLocStart(), /*IsStringLocation*/false,
4311 getSpecifierRange(startSpecifier, specifierLen));
4312
4313 // Type check the second argument (char * for both %b and %D)
4314 Ex = getDataArg(argIndex + 1);
4315 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4316 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4317 EmitFormatDiagnostic(
4318 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4319 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4320 << false << Ex->getSourceRange(),
4321 Ex->getLocStart(), /*IsStringLocation*/false,
4322 getSpecifierRange(startSpecifier, specifierLen));
4323
4324 return true;
4325 }
4326
Ted Kremenek4a49d982010-02-26 19:18:41 +00004327 // Check for using an Objective-C specific conversion specifier
4328 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004329 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004330 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4331 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004332 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004333
Tom Careb49ec692010-06-17 19:00:27 +00004334 // Check for invalid use of field width
4335 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004336 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004337 startSpecifier, specifierLen);
4338 }
4339
4340 // Check for invalid use of precision
4341 if (!FS.hasValidPrecision()) {
4342 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4343 startSpecifier, specifierLen);
4344 }
4345
4346 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004347 if (!FS.hasValidThousandsGroupingPrefix())
4348 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004349 if (!FS.hasValidLeadingZeros())
4350 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4351 if (!FS.hasValidPlusPrefix())
4352 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004353 if (!FS.hasValidSpacePrefix())
4354 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004355 if (!FS.hasValidAlternativeForm())
4356 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4357 if (!FS.hasValidLeftJustified())
4358 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4359
4360 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004361 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4362 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4363 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004364 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4365 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4366 startSpecifier, specifierLen);
4367
4368 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004369 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004370 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4371 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004372 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004373 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004374 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004375 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4376 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004377
Jordan Rose92303592012-09-08 04:00:03 +00004378 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4379 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4380
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004381 // The remaining checks depend on the data arguments.
4382 if (HasVAListArg)
4383 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004384
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004385 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004386 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004387
Jordan Rose58bbe422012-07-19 18:10:08 +00004388 const Expr *Arg = getDataArg(argIndex);
4389 if (!Arg)
4390 return true;
4391
4392 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004393}
4394
Jordan Roseaee34382012-09-05 22:56:26 +00004395static bool requiresParensToAddCast(const Expr *E) {
4396 // FIXME: We should have a general way to reason about operator
4397 // precedence and whether parens are actually needed here.
4398 // Take care of a few common cases where they aren't.
4399 const Expr *Inside = E->IgnoreImpCasts();
4400 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4401 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4402
4403 switch (Inside->getStmtClass()) {
4404 case Stmt::ArraySubscriptExprClass:
4405 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004406 case Stmt::CharacterLiteralClass:
4407 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004408 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004409 case Stmt::FloatingLiteralClass:
4410 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004411 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004412 case Stmt::ObjCArrayLiteralClass:
4413 case Stmt::ObjCBoolLiteralExprClass:
4414 case Stmt::ObjCBoxedExprClass:
4415 case Stmt::ObjCDictionaryLiteralClass:
4416 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004417 case Stmt::ObjCIvarRefExprClass:
4418 case Stmt::ObjCMessageExprClass:
4419 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004420 case Stmt::ObjCStringLiteralClass:
4421 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004422 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004423 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004424 case Stmt::UnaryOperatorClass:
4425 return false;
4426 default:
4427 return true;
4428 }
4429}
4430
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004431static std::pair<QualType, StringRef>
4432shouldNotPrintDirectly(const ASTContext &Context,
4433 QualType IntendedTy,
4434 const Expr *E) {
4435 // Use a 'while' to peel off layers of typedefs.
4436 QualType TyTy = IntendedTy;
4437 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4438 StringRef Name = UserTy->getDecl()->getName();
4439 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4440 .Case("NSInteger", Context.LongTy)
4441 .Case("NSUInteger", Context.UnsignedLongTy)
4442 .Case("SInt32", Context.IntTy)
4443 .Case("UInt32", Context.UnsignedIntTy)
4444 .Default(QualType());
4445
4446 if (!CastTy.isNull())
4447 return std::make_pair(CastTy, Name);
4448
4449 TyTy = UserTy->desugar();
4450 }
4451
4452 // Strip parens if necessary.
4453 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4454 return shouldNotPrintDirectly(Context,
4455 PE->getSubExpr()->getType(),
4456 PE->getSubExpr());
4457
4458 // If this is a conditional expression, then its result type is constructed
4459 // via usual arithmetic conversions and thus there might be no necessary
4460 // typedef sugar there. Recurse to operands to check for NSInteger &
4461 // Co. usage condition.
4462 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4463 QualType TrueTy, FalseTy;
4464 StringRef TrueName, FalseName;
4465
4466 std::tie(TrueTy, TrueName) =
4467 shouldNotPrintDirectly(Context,
4468 CO->getTrueExpr()->getType(),
4469 CO->getTrueExpr());
4470 std::tie(FalseTy, FalseName) =
4471 shouldNotPrintDirectly(Context,
4472 CO->getFalseExpr()->getType(),
4473 CO->getFalseExpr());
4474
4475 if (TrueTy == FalseTy)
4476 return std::make_pair(TrueTy, TrueName);
4477 else if (TrueTy.isNull())
4478 return std::make_pair(FalseTy, FalseName);
4479 else if (FalseTy.isNull())
4480 return std::make_pair(TrueTy, TrueName);
4481 }
4482
4483 return std::make_pair(QualType(), StringRef());
4484}
4485
Richard Smith55ce3522012-06-25 20:30:08 +00004486bool
4487CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4488 const char *StartSpecifier,
4489 unsigned SpecifierLen,
4490 const Expr *E) {
4491 using namespace analyze_format_string;
4492 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004493 // Now type check the data expression that matches the
4494 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004495 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4496 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004497 if (!AT.isValid())
4498 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004499
Jordan Rose598ec092012-12-05 18:44:40 +00004500 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004501 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4502 ExprTy = TET->getUnderlyingExpr()->getType();
4503 }
4504
Seth Cantrellb4802962015-03-04 03:12:10 +00004505 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4506
4507 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004508 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004509 }
Jordan Rose98709982012-06-04 22:48:57 +00004510
Jordan Rose22b74712012-09-05 22:56:19 +00004511 // Look through argument promotions for our error message's reported type.
4512 // This includes the integral and floating promotions, but excludes array
4513 // and function pointer decay; seeing that an argument intended to be a
4514 // string has type 'char [6]' is probably more confusing than 'char *'.
4515 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4516 if (ICE->getCastKind() == CK_IntegralCast ||
4517 ICE->getCastKind() == CK_FloatingCast) {
4518 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004519 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004520
4521 // Check if we didn't match because of an implicit cast from a 'char'
4522 // or 'short' to an 'int'. This is done because printf is a varargs
4523 // function.
4524 if (ICE->getType() == S.Context.IntTy ||
4525 ICE->getType() == S.Context.UnsignedIntTy) {
4526 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004527 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004528 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004529 }
Jordan Rose98709982012-06-04 22:48:57 +00004530 }
Jordan Rose598ec092012-12-05 18:44:40 +00004531 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4532 // Special case for 'a', which has type 'int' in C.
4533 // Note, however, that we do /not/ want to treat multibyte constants like
4534 // 'MooV' as characters! This form is deprecated but still exists.
4535 if (ExprTy == S.Context.IntTy)
4536 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4537 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004538 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004539
Jordan Rosebc53ed12014-05-31 04:12:14 +00004540 // Look through enums to their underlying type.
4541 bool IsEnum = false;
4542 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4543 ExprTy = EnumTy->getDecl()->getIntegerType();
4544 IsEnum = true;
4545 }
4546
Jordan Rose0e5badd2012-12-05 18:44:49 +00004547 // %C in an Objective-C context prints a unichar, not a wchar_t.
4548 // If the argument is an integer of some kind, believe the %C and suggest
4549 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004550 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004551 if (ObjCContext &&
4552 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4553 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4554 !ExprTy->isCharType()) {
4555 // 'unichar' is defined as a typedef of unsigned short, but we should
4556 // prefer using the typedef if it is visible.
4557 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004558
4559 // While we are here, check if the value is an IntegerLiteral that happens
4560 // to be within the valid range.
4561 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4562 const llvm::APInt &V = IL->getValue();
4563 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4564 return true;
4565 }
4566
Jordan Rose0e5badd2012-12-05 18:44:49 +00004567 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4568 Sema::LookupOrdinaryName);
4569 if (S.LookupName(Result, S.getCurScope())) {
4570 NamedDecl *ND = Result.getFoundDecl();
4571 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4572 if (TD->getUnderlyingType() == IntendedTy)
4573 IntendedTy = S.Context.getTypedefType(TD);
4574 }
4575 }
4576 }
4577
4578 // Special-case some of Darwin's platform-independence types by suggesting
4579 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004580 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004581 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004582 QualType CastTy;
4583 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4584 if (!CastTy.isNull()) {
4585 IntendedTy = CastTy;
4586 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004587 }
4588 }
4589
Jordan Rose22b74712012-09-05 22:56:19 +00004590 // We may be able to offer a FixItHint if it is a supported type.
4591 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004592 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004593 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004594
Jordan Rose22b74712012-09-05 22:56:19 +00004595 if (success) {
4596 // Get the fix string from the fixed format specifier
4597 SmallString<16> buf;
4598 llvm::raw_svector_ostream os(buf);
4599 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004600
Jordan Roseaee34382012-09-05 22:56:26 +00004601 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4602
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004603 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004604 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4605 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4606 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4607 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004608 // In this case, the specifier is wrong and should be changed to match
4609 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004610 EmitFormatDiagnostic(S.PDiag(diag)
4611 << AT.getRepresentativeTypeName(S.Context)
4612 << IntendedTy << IsEnum << E->getSourceRange(),
4613 E->getLocStart(),
4614 /*IsStringLocation*/ false, SpecRange,
4615 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004616 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004617 // The canonical type for formatting this value is different from the
4618 // actual type of the expression. (This occurs, for example, with Darwin's
4619 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4620 // should be printed as 'long' for 64-bit compatibility.)
4621 // Rather than emitting a normal format/argument mismatch, we want to
4622 // add a cast to the recommended type (and correct the format string
4623 // if necessary).
4624 SmallString<16> CastBuf;
4625 llvm::raw_svector_ostream CastFix(CastBuf);
4626 CastFix << "(";
4627 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4628 CastFix << ")";
4629
4630 SmallVector<FixItHint,4> Hints;
4631 if (!AT.matchesType(S.Context, IntendedTy))
4632 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4633
4634 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4635 // If there's already a cast present, just replace it.
4636 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4637 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4638
4639 } else if (!requiresParensToAddCast(E)) {
4640 // If the expression has high enough precedence,
4641 // just write the C-style cast.
4642 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4643 CastFix.str()));
4644 } else {
4645 // Otherwise, add parens around the expression as well as the cast.
4646 CastFix << "(";
4647 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4648 CastFix.str()));
4649
Alp Tokerb6cc5922014-05-03 03:45:55 +00004650 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004651 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4652 }
4653
Jordan Rose0e5badd2012-12-05 18:44:49 +00004654 if (ShouldNotPrintDirectly) {
4655 // The expression has a type that should not be printed directly.
4656 // We extract the name from the typedef because we don't want to show
4657 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004658 StringRef Name;
4659 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4660 Name = TypedefTy->getDecl()->getName();
4661 else
4662 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004663 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004664 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004665 << E->getSourceRange(),
4666 E->getLocStart(), /*IsStringLocation=*/false,
4667 SpecRange, Hints);
4668 } else {
4669 // In this case, the expression could be printed using a different
4670 // specifier, but we've decided that the specifier is probably correct
4671 // and we should cast instead. Just use the normal warning message.
4672 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004673 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4674 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004675 << E->getSourceRange(),
4676 E->getLocStart(), /*IsStringLocation*/false,
4677 SpecRange, Hints);
4678 }
Jordan Roseaee34382012-09-05 22:56:26 +00004679 }
Jordan Rose22b74712012-09-05 22:56:19 +00004680 } else {
4681 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4682 SpecifierLen);
4683 // Since the warning for passing non-POD types to variadic functions
4684 // was deferred until now, we emit a warning for non-POD
4685 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004686 switch (S.isValidVarArgType(ExprTy)) {
4687 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004688 case Sema::VAK_ValidInCXX11: {
4689 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4690 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4691 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4692 }
Richard Smithd7293d72013-08-05 18:49:43 +00004693
Seth Cantrellb4802962015-03-04 03:12:10 +00004694 EmitFormatDiagnostic(
4695 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4696 << IsEnum << CSR << E->getSourceRange(),
4697 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4698 break;
4699 }
Richard Smithd7293d72013-08-05 18:49:43 +00004700 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004701 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004702 EmitFormatDiagnostic(
4703 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004704 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004705 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004706 << CallType
4707 << AT.getRepresentativeTypeName(S.Context)
4708 << CSR
4709 << E->getSourceRange(),
4710 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004711 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004712 break;
4713
4714 case Sema::VAK_Invalid:
4715 if (ExprTy->isObjCObjectType())
4716 EmitFormatDiagnostic(
4717 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4718 << S.getLangOpts().CPlusPlus11
4719 << ExprTy
4720 << CallType
4721 << AT.getRepresentativeTypeName(S.Context)
4722 << CSR
4723 << E->getSourceRange(),
4724 E->getLocStart(), /*IsStringLocation*/false, CSR);
4725 else
4726 // FIXME: If this is an initializer list, suggest removing the braces
4727 // or inserting a cast to the target type.
4728 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4729 << isa<InitListExpr>(E) << ExprTy << CallType
4730 << AT.getRepresentativeTypeName(S.Context)
4731 << E->getSourceRange();
4732 break;
4733 }
4734
4735 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4736 "format string specifier index out of range");
4737 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004738 }
4739
Ted Kremenekab278de2010-01-28 23:39:18 +00004740 return true;
4741}
4742
Ted Kremenek02087932010-07-16 02:11:22 +00004743//===--- CHECK: Scanf format string checking ------------------------------===//
4744
4745namespace {
4746class CheckScanfHandler : public CheckFormatHandler {
4747public:
4748 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4749 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004750 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004751 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004752 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004753 Sema::VariadicCallType CallType,
4754 llvm::SmallBitVector &CheckedVarArgs)
4755 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4756 numDataArgs, beg, hasVAListArg,
4757 Args, formatIdx, inFunctionCall, CallType,
4758 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004759 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004760
4761 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4762 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004763 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004764
4765 bool HandleInvalidScanfConversionSpecifier(
4766 const analyze_scanf::ScanfSpecifier &FS,
4767 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004768 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004769
Craig Toppere14c0f82014-03-12 04:55:44 +00004770 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004771};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004772} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004773
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004774void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4775 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004776 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4777 getLocationOfByte(end), /*IsStringLocation*/true,
4778 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004779}
4780
Ted Kremenekce815422010-07-19 21:25:57 +00004781bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4782 const analyze_scanf::ScanfSpecifier &FS,
4783 const char *startSpecifier,
4784 unsigned specifierLen) {
4785
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004786 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004787 FS.getConversionSpecifier();
4788
4789 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4790 getLocationOfByte(CS.getStart()),
4791 startSpecifier, specifierLen,
4792 CS.getStart(), CS.getLength());
4793}
4794
Ted Kremenek02087932010-07-16 02:11:22 +00004795bool CheckScanfHandler::HandleScanfSpecifier(
4796 const analyze_scanf::ScanfSpecifier &FS,
4797 const char *startSpecifier,
4798 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00004799 using namespace analyze_scanf;
4800 using namespace analyze_format_string;
4801
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004802 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004803
Ted Kremenek6cd69422010-07-19 22:01:06 +00004804 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4805 // be used to decide if we are using positional arguments consistently.
4806 if (FS.consumesDataArgument()) {
4807 if (atFirstArg) {
4808 atFirstArg = false;
4809 usesPositionalArgs = FS.usesPositionalArg();
4810 }
4811 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004812 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4813 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004814 return false;
4815 }
Ted Kremenek02087932010-07-16 02:11:22 +00004816 }
4817
4818 // Check if the field with is non-zero.
4819 const OptionalAmount &Amt = FS.getFieldWidth();
4820 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4821 if (Amt.getConstantAmount() == 0) {
4822 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4823 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004824 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4825 getLocationOfByte(Amt.getStart()),
4826 /*IsStringLocation*/true, R,
4827 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004828 }
4829 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004830
Ted Kremenek02087932010-07-16 02:11:22 +00004831 if (!FS.consumesDataArgument()) {
4832 // FIXME: Technically specifying a precision or field width here
4833 // makes no sense. Worth issuing a warning at some point.
4834 return true;
4835 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004836
Ted Kremenek02087932010-07-16 02:11:22 +00004837 // Consume the argument.
4838 unsigned argIndex = FS.getArgIndex();
4839 if (argIndex < NumDataArgs) {
4840 // The check to see if the argIndex is valid will come later.
4841 // We set the bit here because we may exit early from this
4842 // function if we encounter some other error.
4843 CoveredArgs.set(argIndex);
4844 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004845
Ted Kremenek4407ea42010-07-20 20:04:47 +00004846 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004847 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004848 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4849 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004850 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004851 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004852 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004853 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4854 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004855
Jordan Rose92303592012-09-08 04:00:03 +00004856 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4857 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4858
Ted Kremenek02087932010-07-16 02:11:22 +00004859 // The remaining checks depend on the data arguments.
4860 if (HasVAListArg)
4861 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004862
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004863 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004864 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004865
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004866 // Check that the argument type matches the format specifier.
4867 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004868 if (!Ex)
4869 return true;
4870
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004871 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004872
4873 if (!AT.isValid()) {
4874 return true;
4875 }
4876
Seth Cantrellb4802962015-03-04 03:12:10 +00004877 analyze_format_string::ArgType::MatchKind match =
4878 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004879 if (match == analyze_format_string::ArgType::Match) {
4880 return true;
4881 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004882
Seth Cantrell79340072015-03-04 05:58:08 +00004883 ScanfSpecifier fixedFS = FS;
4884 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4885 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004886
Seth Cantrell79340072015-03-04 05:58:08 +00004887 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4888 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4889 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4890 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004891
Seth Cantrell79340072015-03-04 05:58:08 +00004892 if (success) {
4893 // Get the fix string from the fixed format specifier.
4894 SmallString<128> buf;
4895 llvm::raw_svector_ostream os(buf);
4896 fixedFS.toString(os);
4897
4898 EmitFormatDiagnostic(
4899 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4900 << Ex->getType() << false << Ex->getSourceRange(),
4901 Ex->getLocStart(),
4902 /*IsStringLocation*/ false,
4903 getSpecifierRange(startSpecifier, specifierLen),
4904 FixItHint::CreateReplacement(
4905 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4906 } else {
4907 EmitFormatDiagnostic(S.PDiag(diag)
4908 << AT.getRepresentativeTypeName(S.Context)
4909 << Ex->getType() << false << Ex->getSourceRange(),
4910 Ex->getLocStart(),
4911 /*IsStringLocation*/ false,
4912 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004913 }
4914
Ted Kremenek02087932010-07-16 02:11:22 +00004915 return true;
4916}
4917
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004918static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
4919 const Expr *OrigFormatExpr,
4920 ArrayRef<const Expr *> Args,
4921 bool HasVAListArg, unsigned format_idx,
4922 unsigned firstDataArg,
4923 Sema::FormatStringType Type,
4924 bool inFunctionCall,
4925 Sema::VariadicCallType CallType,
4926 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenekab278de2010-01-28 23:39:18 +00004927 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004928 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004929 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004930 S, inFunctionCall, Args[format_idx],
4931 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00004932 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004933 return;
4934 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004935
Ted Kremenekab278de2010-01-28 23:39:18 +00004936 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004937 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004938 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004939 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004940 const ConstantArrayType *T =
4941 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004942 assert(T && "String literal not of constant array type!");
4943 size_t TypeSize = T->getSize().getZExtValue();
4944 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004945 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004946
4947 // Emit a warning if the string literal is truncated and does not contain an
4948 // embedded null character.
4949 if (TypeSize <= StrRef.size() &&
4950 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4951 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004952 S, inFunctionCall, Args[format_idx],
4953 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004954 FExpr->getLocStart(),
4955 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4956 return;
4957 }
4958
Ted Kremenekab278de2010-01-28 23:39:18 +00004959 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004960 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004961 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004962 S, inFunctionCall, Args[format_idx],
4963 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00004964 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004965 return;
4966 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004967
4968 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
4969 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
4970 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
4971 numDataArgs, (Type == Sema::FST_NSString ||
4972 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004973 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004974 inFunctionCall, CallType, CheckedVarArgs);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004975
Hans Wennborg23926bd2011-12-15 10:25:47 +00004976 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004977 S.getLangOpts(),
4978 S.Context.getTargetInfo(),
4979 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004980 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004981 } else if (Type == Sema::FST_Scanf) {
4982 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004983 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004984 inFunctionCall, CallType, CheckedVarArgs);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004985
Hans Wennborg23926bd2011-12-15 10:25:47 +00004986 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004987 S.getLangOpts(),
4988 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004989 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004990 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004991}
4992
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004993bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4994 // Str - The format string. NOTE: this is NOT null-terminated!
4995 StringRef StrRef = FExpr->getString();
4996 const char *Str = StrRef.data();
4997 // Account for cases where the string literal is truncated in a declaration.
4998 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4999 assert(T && "String literal not of constant array type!");
5000 size_t TypeSize = T->getSize().getZExtValue();
5001 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5002 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5003 getLangOpts(),
5004 Context.getTargetInfo());
5005}
5006
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005007//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5008
5009// Returns the related absolute value function that is larger, of 0 if one
5010// does not exist.
5011static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5012 switch (AbsFunction) {
5013 default:
5014 return 0;
5015
5016 case Builtin::BI__builtin_abs:
5017 return Builtin::BI__builtin_labs;
5018 case Builtin::BI__builtin_labs:
5019 return Builtin::BI__builtin_llabs;
5020 case Builtin::BI__builtin_llabs:
5021 return 0;
5022
5023 case Builtin::BI__builtin_fabsf:
5024 return Builtin::BI__builtin_fabs;
5025 case Builtin::BI__builtin_fabs:
5026 return Builtin::BI__builtin_fabsl;
5027 case Builtin::BI__builtin_fabsl:
5028 return 0;
5029
5030 case Builtin::BI__builtin_cabsf:
5031 return Builtin::BI__builtin_cabs;
5032 case Builtin::BI__builtin_cabs:
5033 return Builtin::BI__builtin_cabsl;
5034 case Builtin::BI__builtin_cabsl:
5035 return 0;
5036
5037 case Builtin::BIabs:
5038 return Builtin::BIlabs;
5039 case Builtin::BIlabs:
5040 return Builtin::BIllabs;
5041 case Builtin::BIllabs:
5042 return 0;
5043
5044 case Builtin::BIfabsf:
5045 return Builtin::BIfabs;
5046 case Builtin::BIfabs:
5047 return Builtin::BIfabsl;
5048 case Builtin::BIfabsl:
5049 return 0;
5050
5051 case Builtin::BIcabsf:
5052 return Builtin::BIcabs;
5053 case Builtin::BIcabs:
5054 return Builtin::BIcabsl;
5055 case Builtin::BIcabsl:
5056 return 0;
5057 }
5058}
5059
5060// Returns the argument type of the absolute value function.
5061static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5062 unsigned AbsType) {
5063 if (AbsType == 0)
5064 return QualType();
5065
5066 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5067 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5068 if (Error != ASTContext::GE_None)
5069 return QualType();
5070
5071 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5072 if (!FT)
5073 return QualType();
5074
5075 if (FT->getNumParams() != 1)
5076 return QualType();
5077
5078 return FT->getParamType(0);
5079}
5080
5081// Returns the best absolute value function, or zero, based on type and
5082// current absolute value function.
5083static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5084 unsigned AbsFunctionKind) {
5085 unsigned BestKind = 0;
5086 uint64_t ArgSize = Context.getTypeSize(ArgType);
5087 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5088 Kind = getLargerAbsoluteValueFunction(Kind)) {
5089 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5090 if (Context.getTypeSize(ParamType) >= ArgSize) {
5091 if (BestKind == 0)
5092 BestKind = Kind;
5093 else if (Context.hasSameType(ParamType, ArgType)) {
5094 BestKind = Kind;
5095 break;
5096 }
5097 }
5098 }
5099 return BestKind;
5100}
5101
5102enum AbsoluteValueKind {
5103 AVK_Integer,
5104 AVK_Floating,
5105 AVK_Complex
5106};
5107
5108static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5109 if (T->isIntegralOrEnumerationType())
5110 return AVK_Integer;
5111 if (T->isRealFloatingType())
5112 return AVK_Floating;
5113 if (T->isAnyComplexType())
5114 return AVK_Complex;
5115
5116 llvm_unreachable("Type not integer, floating, or complex");
5117}
5118
5119// Changes the absolute value function to a different type. Preserves whether
5120// the function is a builtin.
5121static unsigned changeAbsFunction(unsigned AbsKind,
5122 AbsoluteValueKind ValueKind) {
5123 switch (ValueKind) {
5124 case AVK_Integer:
5125 switch (AbsKind) {
5126 default:
5127 return 0;
5128 case Builtin::BI__builtin_fabsf:
5129 case Builtin::BI__builtin_fabs:
5130 case Builtin::BI__builtin_fabsl:
5131 case Builtin::BI__builtin_cabsf:
5132 case Builtin::BI__builtin_cabs:
5133 case Builtin::BI__builtin_cabsl:
5134 return Builtin::BI__builtin_abs;
5135 case Builtin::BIfabsf:
5136 case Builtin::BIfabs:
5137 case Builtin::BIfabsl:
5138 case Builtin::BIcabsf:
5139 case Builtin::BIcabs:
5140 case Builtin::BIcabsl:
5141 return Builtin::BIabs;
5142 }
5143 case AVK_Floating:
5144 switch (AbsKind) {
5145 default:
5146 return 0;
5147 case Builtin::BI__builtin_abs:
5148 case Builtin::BI__builtin_labs:
5149 case Builtin::BI__builtin_llabs:
5150 case Builtin::BI__builtin_cabsf:
5151 case Builtin::BI__builtin_cabs:
5152 case Builtin::BI__builtin_cabsl:
5153 return Builtin::BI__builtin_fabsf;
5154 case Builtin::BIabs:
5155 case Builtin::BIlabs:
5156 case Builtin::BIllabs:
5157 case Builtin::BIcabsf:
5158 case Builtin::BIcabs:
5159 case Builtin::BIcabsl:
5160 return Builtin::BIfabsf;
5161 }
5162 case AVK_Complex:
5163 switch (AbsKind) {
5164 default:
5165 return 0;
5166 case Builtin::BI__builtin_abs:
5167 case Builtin::BI__builtin_labs:
5168 case Builtin::BI__builtin_llabs:
5169 case Builtin::BI__builtin_fabsf:
5170 case Builtin::BI__builtin_fabs:
5171 case Builtin::BI__builtin_fabsl:
5172 return Builtin::BI__builtin_cabsf;
5173 case Builtin::BIabs:
5174 case Builtin::BIlabs:
5175 case Builtin::BIllabs:
5176 case Builtin::BIfabsf:
5177 case Builtin::BIfabs:
5178 case Builtin::BIfabsl:
5179 return Builtin::BIcabsf;
5180 }
5181 }
5182 llvm_unreachable("Unable to convert function");
5183}
5184
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005185static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005186 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5187 if (!FnInfo)
5188 return 0;
5189
5190 switch (FDecl->getBuiltinID()) {
5191 default:
5192 return 0;
5193 case Builtin::BI__builtin_abs:
5194 case Builtin::BI__builtin_fabs:
5195 case Builtin::BI__builtin_fabsf:
5196 case Builtin::BI__builtin_fabsl:
5197 case Builtin::BI__builtin_labs:
5198 case Builtin::BI__builtin_llabs:
5199 case Builtin::BI__builtin_cabs:
5200 case Builtin::BI__builtin_cabsf:
5201 case Builtin::BI__builtin_cabsl:
5202 case Builtin::BIabs:
5203 case Builtin::BIlabs:
5204 case Builtin::BIllabs:
5205 case Builtin::BIfabs:
5206 case Builtin::BIfabsf:
5207 case Builtin::BIfabsl:
5208 case Builtin::BIcabs:
5209 case Builtin::BIcabsf:
5210 case Builtin::BIcabsl:
5211 return FDecl->getBuiltinID();
5212 }
5213 llvm_unreachable("Unknown Builtin type");
5214}
5215
5216// If the replacement is valid, emit a note with replacement function.
5217// Additionally, suggest including the proper header if not already included.
5218static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005219 unsigned AbsKind, QualType ArgType) {
5220 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005221 const char *HeaderName = nullptr;
5222 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005223 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5224 FunctionName = "std::abs";
5225 if (ArgType->isIntegralOrEnumerationType()) {
5226 HeaderName = "cstdlib";
5227 } else if (ArgType->isRealFloatingType()) {
5228 HeaderName = "cmath";
5229 } else {
5230 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005231 }
Richard Trieubeffb832014-04-15 23:47:53 +00005232
5233 // Lookup all std::abs
5234 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005235 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005236 R.suppressDiagnostics();
5237 S.LookupQualifiedName(R, Std);
5238
5239 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005240 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005241 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5242 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5243 } else {
5244 FDecl = dyn_cast<FunctionDecl>(I);
5245 }
5246 if (!FDecl)
5247 continue;
5248
5249 // Found std::abs(), check that they are the right ones.
5250 if (FDecl->getNumParams() != 1)
5251 continue;
5252
5253 // Check that the parameter type can handle the argument.
5254 QualType ParamType = FDecl->getParamDecl(0)->getType();
5255 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5256 S.Context.getTypeSize(ArgType) <=
5257 S.Context.getTypeSize(ParamType)) {
5258 // Found a function, don't need the header hint.
5259 EmitHeaderHint = false;
5260 break;
5261 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005262 }
Richard Trieubeffb832014-04-15 23:47:53 +00005263 }
5264 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005265 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005266 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5267
5268 if (HeaderName) {
5269 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5270 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5271 R.suppressDiagnostics();
5272 S.LookupName(R, S.getCurScope());
5273
5274 if (R.isSingleResult()) {
5275 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5276 if (FD && FD->getBuiltinID() == AbsKind) {
5277 EmitHeaderHint = false;
5278 } else {
5279 return;
5280 }
5281 } else if (!R.empty()) {
5282 return;
5283 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005284 }
5285 }
5286
5287 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005288 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005289
Richard Trieubeffb832014-04-15 23:47:53 +00005290 if (!HeaderName)
5291 return;
5292
5293 if (!EmitHeaderHint)
5294 return;
5295
Alp Toker5d96e0a2014-07-11 20:53:51 +00005296 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5297 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005298}
5299
5300static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5301 if (!FDecl)
5302 return false;
5303
5304 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5305 return false;
5306
5307 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5308
5309 while (ND && ND->isInlineNamespace()) {
5310 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005311 }
Richard Trieubeffb832014-04-15 23:47:53 +00005312
5313 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5314 return false;
5315
5316 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5317 return false;
5318
5319 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005320}
5321
5322// Warn when using the wrong abs() function.
5323void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5324 const FunctionDecl *FDecl,
5325 IdentifierInfo *FnInfo) {
5326 if (Call->getNumArgs() != 1)
5327 return;
5328
5329 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005330 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5331 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005332 return;
5333
5334 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5335 QualType ParamType = Call->getArg(0)->getType();
5336
Alp Toker5d96e0a2014-07-11 20:53:51 +00005337 // Unsigned types cannot be negative. Suggest removing the absolute value
5338 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005339 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005340 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005341 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005342 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5343 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005344 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005345 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5346 return;
5347 }
5348
David Majnemer7f77eb92015-11-15 03:04:34 +00005349 // Taking the absolute value of a pointer is very suspicious, they probably
5350 // wanted to index into an array, dereference a pointer, call a function, etc.
5351 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5352 unsigned DiagType = 0;
5353 if (ArgType->isFunctionType())
5354 DiagType = 1;
5355 else if (ArgType->isArrayType())
5356 DiagType = 2;
5357
5358 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5359 return;
5360 }
5361
Richard Trieubeffb832014-04-15 23:47:53 +00005362 // std::abs has overloads which prevent most of the absolute value problems
5363 // from occurring.
5364 if (IsStdAbs)
5365 return;
5366
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005367 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5368 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5369
5370 // The argument and parameter are the same kind. Check if they are the right
5371 // size.
5372 if (ArgValueKind == ParamValueKind) {
5373 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5374 return;
5375
5376 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5377 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5378 << FDecl << ArgType << ParamType;
5379
5380 if (NewAbsKind == 0)
5381 return;
5382
5383 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005384 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005385 return;
5386 }
5387
5388 // ArgValueKind != ParamValueKind
5389 // The wrong type of absolute value function was used. Attempt to find the
5390 // proper one.
5391 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5392 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5393 if (NewAbsKind == 0)
5394 return;
5395
5396 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5397 << FDecl << ParamValueKind << ArgValueKind;
5398
5399 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005400 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005401}
5402
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005403//===--- CHECK: Standard memory functions ---------------------------------===//
5404
Nico Weber0e6daef2013-12-26 23:38:39 +00005405/// \brief Takes the expression passed to the size_t parameter of functions
5406/// such as memcmp, strncat, etc and warns if it's a comparison.
5407///
5408/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5409static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5410 IdentifierInfo *FnName,
5411 SourceLocation FnLoc,
5412 SourceLocation RParenLoc) {
5413 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5414 if (!Size)
5415 return false;
5416
5417 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5418 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5419 return false;
5420
Nico Weber0e6daef2013-12-26 23:38:39 +00005421 SourceRange SizeRange = Size->getSourceRange();
5422 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5423 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005424 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005425 << FnName << FixItHint::CreateInsertion(
5426 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005427 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005428 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005429 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005430 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5431 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005432
5433 return true;
5434}
5435
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005436/// \brief Determine whether the given type is or contains a dynamic class type
5437/// (e.g., whether it has a vtable).
5438static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5439 bool &IsContained) {
5440 // Look through array types while ignoring qualifiers.
5441 const Type *Ty = T->getBaseElementTypeUnsafe();
5442 IsContained = false;
5443
5444 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5445 RD = RD ? RD->getDefinition() : nullptr;
5446 if (!RD)
5447 return nullptr;
5448
5449 if (RD->isDynamicClass())
5450 return RD;
5451
5452 // Check all the fields. If any bases were dynamic, the class is dynamic.
5453 // It's impossible for a class to transitively contain itself by value, so
5454 // infinite recursion is impossible.
5455 for (auto *FD : RD->fields()) {
5456 bool SubContained;
5457 if (const CXXRecordDecl *ContainedRD =
5458 getContainedDynamicClass(FD->getType(), SubContained)) {
5459 IsContained = true;
5460 return ContainedRD;
5461 }
5462 }
5463
5464 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005465}
5466
Chandler Carruth889ed862011-06-21 23:04:20 +00005467/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005468/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005469static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005470 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005471 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5472 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5473 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005474
Craig Topperc3ec1492014-05-26 06:22:03 +00005475 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005476}
5477
Chandler Carruth889ed862011-06-21 23:04:20 +00005478/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005479static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005480 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5481 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5482 if (SizeOf->getKind() == clang::UETT_SizeOf)
5483 return SizeOf->getTypeOfArgument();
5484
5485 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005486}
5487
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005488/// \brief Check for dangerous or invalid arguments to memset().
5489///
Chandler Carruthac687262011-06-03 06:23:57 +00005490/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005491/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5492/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005493///
5494/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005495void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005496 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005497 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005498 assert(BId != 0);
5499
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005500 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005501 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005502 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005503 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005504 return;
5505
Anna Zaks22122702012-01-17 00:37:07 +00005506 unsigned LastArg = (BId == Builtin::BImemset ||
5507 BId == Builtin::BIstrndup ? 1 : 2);
5508 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005509 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005510
Nico Weber0e6daef2013-12-26 23:38:39 +00005511 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5512 Call->getLocStart(), Call->getRParenLoc()))
5513 return;
5514
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005515 // We have special checking when the length is a sizeof expression.
5516 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5517 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5518 llvm::FoldingSetNodeID SizeOfArgID;
5519
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005520 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5521 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005522 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005523
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005524 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005525 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005526 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005527 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005528
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005529 // Never warn about void type pointers. This can be used to suppress
5530 // false positives.
5531 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005532 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005533
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005534 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5535 // actually comparing the expressions for equality. Because computing the
5536 // expression IDs can be expensive, we only do this if the diagnostic is
5537 // enabled.
5538 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005539 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5540 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005541 // We only compute IDs for expressions if the warning is enabled, and
5542 // cache the sizeof arg's ID.
5543 if (SizeOfArgID == llvm::FoldingSetNodeID())
5544 SizeOfArg->Profile(SizeOfArgID, Context, true);
5545 llvm::FoldingSetNodeID DestID;
5546 Dest->Profile(DestID, Context, true);
5547 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005548 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5549 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005550 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005551 StringRef ReadableName = FnName->getName();
5552
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005553 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005554 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005555 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005556 if (!PointeeTy->isIncompleteType() &&
5557 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005558 ActionIdx = 2; // If the pointee's size is sizeof(char),
5559 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005560
5561 // If the function is defined as a builtin macro, do not show macro
5562 // expansion.
5563 SourceLocation SL = SizeOfArg->getExprLoc();
5564 SourceRange DSR = Dest->getSourceRange();
5565 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005566 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005567
5568 if (SM.isMacroArgExpansion(SL)) {
5569 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5570 SL = SM.getSpellingLoc(SL);
5571 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5572 SM.getSpellingLoc(DSR.getEnd()));
5573 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5574 SM.getSpellingLoc(SSR.getEnd()));
5575 }
5576
Anna Zaksd08d9152012-05-30 23:14:52 +00005577 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005578 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005579 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005580 << PointeeTy
5581 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005582 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005583 << SSR);
5584 DiagRuntimeBehavior(SL, SizeOfArg,
5585 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5586 << ActionIdx
5587 << SSR);
5588
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005589 break;
5590 }
5591 }
5592
5593 // Also check for cases where the sizeof argument is the exact same
5594 // type as the memory argument, and where it points to a user-defined
5595 // record type.
5596 if (SizeOfArgTy != QualType()) {
5597 if (PointeeTy->isRecordType() &&
5598 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5599 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5600 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5601 << FnName << SizeOfArgTy << ArgIdx
5602 << PointeeTy << Dest->getSourceRange()
5603 << LenExpr->getSourceRange());
5604 break;
5605 }
Nico Weberc5e73862011-06-14 16:14:58 +00005606 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005607 } else if (DestTy->isArrayType()) {
5608 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005609 }
Nico Weberc5e73862011-06-14 16:14:58 +00005610
Nico Weberc44b35e2015-03-21 17:37:46 +00005611 if (PointeeTy == QualType())
5612 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005613
Nico Weberc44b35e2015-03-21 17:37:46 +00005614 // Always complain about dynamic classes.
5615 bool IsContained;
5616 if (const CXXRecordDecl *ContainedRD =
5617 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005618
Nico Weberc44b35e2015-03-21 17:37:46 +00005619 unsigned OperationType = 0;
5620 // "overwritten" if we're warning about the destination for any call
5621 // but memcmp; otherwise a verb appropriate to the call.
5622 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5623 if (BId == Builtin::BImemcpy)
5624 OperationType = 1;
5625 else if(BId == Builtin::BImemmove)
5626 OperationType = 2;
5627 else if (BId == Builtin::BImemcmp)
5628 OperationType = 3;
5629 }
5630
John McCall31168b02011-06-15 23:02:42 +00005631 DiagRuntimeBehavior(
5632 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005633 PDiag(diag::warn_dyn_class_memaccess)
5634 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5635 << FnName << IsContained << ContainedRD << OperationType
5636 << Call->getCallee()->getSourceRange());
5637 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5638 BId != Builtin::BImemset)
5639 DiagRuntimeBehavior(
5640 Dest->getExprLoc(), Dest,
5641 PDiag(diag::warn_arc_object_memaccess)
5642 << ArgIdx << FnName << PointeeTy
5643 << Call->getCallee()->getSourceRange());
5644 else
5645 continue;
5646
5647 DiagRuntimeBehavior(
5648 Dest->getExprLoc(), Dest,
5649 PDiag(diag::note_bad_memaccess_silence)
5650 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5651 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005652 }
5653}
5654
Ted Kremenek6865f772011-08-18 20:55:45 +00005655// A little helper routine: ignore addition and subtraction of integer literals.
5656// This intentionally does not ignore all integer constant expressions because
5657// we don't want to remove sizeof().
5658static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5659 Ex = Ex->IgnoreParenCasts();
5660
5661 for (;;) {
5662 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5663 if (!BO || !BO->isAdditiveOp())
5664 break;
5665
5666 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5667 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5668
5669 if (isa<IntegerLiteral>(RHS))
5670 Ex = LHS;
5671 else if (isa<IntegerLiteral>(LHS))
5672 Ex = RHS;
5673 else
5674 break;
5675 }
5676
5677 return Ex;
5678}
5679
Anna Zaks13b08572012-08-08 21:42:23 +00005680static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5681 ASTContext &Context) {
5682 // Only handle constant-sized or VLAs, but not flexible members.
5683 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5684 // Only issue the FIXIT for arrays of size > 1.
5685 if (CAT->getSize().getSExtValue() <= 1)
5686 return false;
5687 } else if (!Ty->isVariableArrayType()) {
5688 return false;
5689 }
5690 return true;
5691}
5692
Ted Kremenek6865f772011-08-18 20:55:45 +00005693// Warn if the user has made the 'size' argument to strlcpy or strlcat
5694// be the size of the source, instead of the destination.
5695void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5696 IdentifierInfo *FnName) {
5697
5698 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005699 unsigned NumArgs = Call->getNumArgs();
5700 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005701 return;
5702
5703 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5704 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005705 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005706
5707 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5708 Call->getLocStart(), Call->getRParenLoc()))
5709 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005710
5711 // Look for 'strlcpy(dst, x, sizeof(x))'
5712 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5713 CompareWithSrc = Ex;
5714 else {
5715 // Look for 'strlcpy(dst, x, strlen(x))'
5716 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005717 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5718 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005719 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5720 }
5721 }
5722
5723 if (!CompareWithSrc)
5724 return;
5725
5726 // Determine if the argument to sizeof/strlen is equal to the source
5727 // argument. In principle there's all kinds of things you could do
5728 // here, for instance creating an == expression and evaluating it with
5729 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5730 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5731 if (!SrcArgDRE)
5732 return;
5733
5734 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5735 if (!CompareWithSrcDRE ||
5736 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5737 return;
5738
5739 const Expr *OriginalSizeArg = Call->getArg(2);
5740 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5741 << OriginalSizeArg->getSourceRange() << FnName;
5742
5743 // Output a FIXIT hint if the destination is an array (rather than a
5744 // pointer to an array). This could be enhanced to handle some
5745 // pointers if we know the actual size, like if DstArg is 'array+2'
5746 // we could say 'sizeof(array)-2'.
5747 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005748 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005749 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005750
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005751 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005752 llvm::raw_svector_ostream OS(sizeString);
5753 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005754 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005755 OS << ")";
5756
5757 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5758 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5759 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005760}
5761
Anna Zaks314cd092012-02-01 19:08:57 +00005762/// Check if two expressions refer to the same declaration.
5763static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5764 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5765 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5766 return D1->getDecl() == D2->getDecl();
5767 return false;
5768}
5769
5770static const Expr *getStrlenExprArg(const Expr *E) {
5771 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5772 const FunctionDecl *FD = CE->getDirectCallee();
5773 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005774 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005775 return CE->getArg(0)->IgnoreParenCasts();
5776 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005777 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005778}
5779
5780// Warn on anti-patterns as the 'size' argument to strncat.
5781// The correct size argument should look like following:
5782// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5783void Sema::CheckStrncatArguments(const CallExpr *CE,
5784 IdentifierInfo *FnName) {
5785 // Don't crash if the user has the wrong number of arguments.
5786 if (CE->getNumArgs() < 3)
5787 return;
5788 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5789 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5790 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5791
Nico Weber0e6daef2013-12-26 23:38:39 +00005792 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5793 CE->getRParenLoc()))
5794 return;
5795
Anna Zaks314cd092012-02-01 19:08:57 +00005796 // Identify common expressions, which are wrongly used as the size argument
5797 // to strncat and may lead to buffer overflows.
5798 unsigned PatternType = 0;
5799 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5800 // - sizeof(dst)
5801 if (referToTheSameDecl(SizeOfArg, DstArg))
5802 PatternType = 1;
5803 // - sizeof(src)
5804 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5805 PatternType = 2;
5806 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5807 if (BE->getOpcode() == BO_Sub) {
5808 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5809 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5810 // - sizeof(dst) - strlen(dst)
5811 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5812 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5813 PatternType = 1;
5814 // - sizeof(src) - (anything)
5815 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5816 PatternType = 2;
5817 }
5818 }
5819
5820 if (PatternType == 0)
5821 return;
5822
Anna Zaks5069aa32012-02-03 01:27:37 +00005823 // Generate the diagnostic.
5824 SourceLocation SL = LenArg->getLocStart();
5825 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005826 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005827
5828 // If the function is defined as a builtin macro, do not show macro expansion.
5829 if (SM.isMacroArgExpansion(SL)) {
5830 SL = SM.getSpellingLoc(SL);
5831 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5832 SM.getSpellingLoc(SR.getEnd()));
5833 }
5834
Anna Zaks13b08572012-08-08 21:42:23 +00005835 // Check if the destination is an array (rather than a pointer to an array).
5836 QualType DstTy = DstArg->getType();
5837 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5838 Context);
5839 if (!isKnownSizeArray) {
5840 if (PatternType == 1)
5841 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5842 else
5843 Diag(SL, diag::warn_strncat_src_size) << SR;
5844 return;
5845 }
5846
Anna Zaks314cd092012-02-01 19:08:57 +00005847 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005848 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005849 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005850 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005851
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005852 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005853 llvm::raw_svector_ostream OS(sizeString);
5854 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005855 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005856 OS << ") - ";
5857 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005858 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005859 OS << ") - 1";
5860
Anna Zaks5069aa32012-02-03 01:27:37 +00005861 Diag(SL, diag::note_strncat_wrong_size)
5862 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005863}
5864
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005865//===--- CHECK: Return Address of Stack Variable --------------------------===//
5866
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005867static const Expr *EvalVal(const Expr *E,
5868 SmallVectorImpl<const DeclRefExpr *> &refVars,
5869 const Decl *ParentDecl);
5870static const Expr *EvalAddr(const Expr *E,
5871 SmallVectorImpl<const DeclRefExpr *> &refVars,
5872 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005873
5874/// CheckReturnStackAddr - Check if a return statement returns the address
5875/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005876static void
5877CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5878 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005879
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005880 const Expr *stackE = nullptr;
5881 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005882
5883 // Perform checking for returned stack addresses, local blocks,
5884 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005885 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005886 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005887 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005888 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005889 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005890 }
5891
Craig Topperc3ec1492014-05-26 06:22:03 +00005892 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005893 return; // Nothing suspicious was found.
5894
5895 SourceLocation diagLoc;
5896 SourceRange diagRange;
5897 if (refVars.empty()) {
5898 diagLoc = stackE->getLocStart();
5899 diagRange = stackE->getSourceRange();
5900 } else {
5901 // We followed through a reference variable. 'stackE' contains the
5902 // problematic expression but we will warn at the return statement pointing
5903 // at the reference variable. We will later display the "trail" of
5904 // reference variables using notes.
5905 diagLoc = refVars[0]->getLocStart();
5906 diagRange = refVars[0]->getSourceRange();
5907 }
5908
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005909 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
5910 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00005911 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005912 << DR->getDecl()->getDeclName() << diagRange;
5913 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005914 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005915 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005916 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005917 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00005918 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
5919 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005920 }
5921
5922 // Display the "trail" of reference variables that we followed until we
5923 // found the problematic expression using notes.
5924 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005925 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005926 // If this var binds to another reference var, show the range of the next
5927 // var, otherwise the var binds to the problematic expression, in which case
5928 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005929 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
5930 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005931 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5932 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005933 }
5934}
5935
5936/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5937/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005938/// to a location on the stack, a local block, an address of a label, or a
5939/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005940/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005941/// encounter a subexpression that (1) clearly does not lead to one of the
5942/// above problematic expressions (2) is something we cannot determine leads to
5943/// a problematic expression based on such local checking.
5944///
5945/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5946/// the expression that they point to. Such variables are added to the
5947/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005948///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005949/// EvalAddr processes expressions that are pointers that are used as
5950/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005951/// At the base case of the recursion is a check for the above problematic
5952/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005953///
5954/// This implementation handles:
5955///
5956/// * pointer-to-pointer casts
5957/// * implicit conversions from array references to pointers
5958/// * taking the address of fields
5959/// * arbitrary interplay between "&" and "*" operators
5960/// * pointer arithmetic from an address of a stack variable
5961/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005962static const Expr *EvalAddr(const Expr *E,
5963 SmallVectorImpl<const DeclRefExpr *> &refVars,
5964 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005965 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005966 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005967
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005968 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005969 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005970 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005971 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005972 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005973
Peter Collingbourne91147592011-04-15 00:35:48 +00005974 E = E->IgnoreParens();
5975
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005976 // Our "symbolic interpreter" is just a dispatch off the currently
5977 // viewed AST node. We then recursively traverse the AST by calling
5978 // EvalAddr and EvalVal appropriately.
5979 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005980 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005981 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005982
Richard Smith40f08eb2014-01-30 22:05:38 +00005983 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005984 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005985 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005986
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005987 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005988 // If this is a reference variable, follow through to the expression that
5989 // it points to.
5990 if (V->hasLocalStorage() &&
5991 V->getType()->isReferenceType() && V->hasInit()) {
5992 // Add the reference variable to the "trail".
5993 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005994 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005995 }
5996
Craig Topperc3ec1492014-05-26 06:22:03 +00005997 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005998 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005999
Chris Lattner934edb22007-12-28 05:31:15 +00006000 case Stmt::UnaryOperatorClass: {
6001 // The only unary operator that make sense to handle here
6002 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006003 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006004
John McCalle3027922010-08-25 11:45:40 +00006005 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006006 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006007 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006008 }
Mike Stump11289f42009-09-09 15:08:12 +00006009
Chris Lattner934edb22007-12-28 05:31:15 +00006010 case Stmt::BinaryOperatorClass: {
6011 // Handle pointer arithmetic. All other binary operators are not valid
6012 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006013 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006014 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006015
John McCalle3027922010-08-25 11:45:40 +00006016 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006017 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006018
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006019 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006020
6021 // Determine which argument is the real pointer base. It could be
6022 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006023 if (!Base->getType()->isPointerType())
6024 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006025
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006026 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006027 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006028 }
Steve Naroff2752a172008-09-10 19:17:48 +00006029
Chris Lattner934edb22007-12-28 05:31:15 +00006030 // For conditional operators we need to see if either the LHS or RHS are
6031 // valid DeclRefExpr*s. If one of them is valid, we return it.
6032 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006033 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006034
Chris Lattner934edb22007-12-28 05:31:15 +00006035 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006036 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006037 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006038 // In C++, we can have a throw-expression, which has 'void' type.
6039 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006040 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006041 return LHS;
6042 }
Chris Lattner934edb22007-12-28 05:31:15 +00006043
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006044 // In C++, we can have a throw-expression, which has 'void' type.
6045 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006046 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006047
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006048 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006049 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006050
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006051 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006052 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006053 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006054 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006055
6056 case Stmt::AddrLabelExprClass:
6057 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006058
John McCall28fc7092011-11-10 05:35:25 +00006059 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006060 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6061 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006062
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006063 // For casts, we need to handle conversions from arrays to
6064 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006065 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006066 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006067 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006068 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006069 case Stmt::CXXStaticCastExprClass:
6070 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006071 case Stmt::CXXConstCastExprClass:
6072 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006073 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006074 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006075 case CK_LValueToRValue:
6076 case CK_NoOp:
6077 case CK_BaseToDerived:
6078 case CK_DerivedToBase:
6079 case CK_UncheckedDerivedToBase:
6080 case CK_Dynamic:
6081 case CK_CPointerToObjCPointerCast:
6082 case CK_BlockPointerToObjCPointerCast:
6083 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006084 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006085
6086 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006087 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006088
Richard Trieudadefde2014-07-02 04:39:38 +00006089 case CK_BitCast:
6090 if (SubExpr->getType()->isAnyPointerType() ||
6091 SubExpr->getType()->isBlockPointerType() ||
6092 SubExpr->getType()->isObjCQualifiedIdType())
6093 return EvalAddr(SubExpr, refVars, ParentDecl);
6094 else
6095 return nullptr;
6096
Eli Friedman8195ad72012-02-23 23:04:32 +00006097 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006098 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006099 }
Chris Lattner934edb22007-12-28 05:31:15 +00006100 }
Mike Stump11289f42009-09-09 15:08:12 +00006101
Douglas Gregorfe314812011-06-21 17:03:29 +00006102 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006103 if (const Expr *Result =
6104 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6105 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006106 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006107 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006108
Chris Lattner934edb22007-12-28 05:31:15 +00006109 // Everything else: we simply don't reason about them.
6110 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006111 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006112 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006113}
Mike Stump11289f42009-09-09 15:08:12 +00006114
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006115/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6116/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006117static const Expr *EvalVal(const Expr *E,
6118 SmallVectorImpl<const DeclRefExpr *> &refVars,
6119 const Decl *ParentDecl) {
6120 do {
6121 // We should only be called for evaluating non-pointer expressions, or
6122 // expressions with a pointer type that are not used as references but
6123 // instead
6124 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006125
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006126 // Our "symbolic interpreter" is just a dispatch off the currently
6127 // viewed AST node. We then recursively traverse the AST by calling
6128 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006129
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006130 E = E->IgnoreParens();
6131 switch (E->getStmtClass()) {
6132 case Stmt::ImplicitCastExprClass: {
6133 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6134 if (IE->getValueKind() == VK_LValue) {
6135 E = IE->getSubExpr();
6136 continue;
6137 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006138 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006139 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006140
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006141 case Stmt::ExprWithCleanupsClass:
6142 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6143 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006144
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006145 case Stmt::DeclRefExprClass: {
6146 // When we hit a DeclRefExpr we are looking at code that refers to a
6147 // variable's name. If it's not a reference variable we check if it has
6148 // local storage within the function, and if so, return the expression.
6149 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6150
6151 // If we leave the immediate function, the lifetime isn't about to end.
6152 if (DR->refersToEnclosingVariableOrCapture())
6153 return nullptr;
6154
6155 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6156 // Check if it refers to itself, e.g. "int& i = i;".
6157 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006158 return DR;
6159
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006160 if (V->hasLocalStorage()) {
6161 if (!V->getType()->isReferenceType())
6162 return DR;
6163
6164 // Reference variable, follow through to the expression that
6165 // it points to.
6166 if (V->hasInit()) {
6167 // Add the reference variable to the "trail".
6168 refVars.push_back(DR);
6169 return EvalVal(V->getInit(), refVars, V);
6170 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006171 }
6172 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006173
6174 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006175 }
Mike Stump11289f42009-09-09 15:08:12 +00006176
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006177 case Stmt::UnaryOperatorClass: {
6178 // The only unary operator that make sense to handle here
6179 // is Deref. All others don't resolve to a "name." This includes
6180 // handling all sorts of rvalues passed to a unary operator.
6181 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006182
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006183 if (U->getOpcode() == UO_Deref)
6184 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006185
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006186 return nullptr;
6187 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006188
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006189 case Stmt::ArraySubscriptExprClass: {
6190 // Array subscripts are potential references to data on the stack. We
6191 // retrieve the DeclRefExpr* for the array variable if it indeed
6192 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006193 const auto *ASE = cast<ArraySubscriptExpr>(E);
6194 if (ASE->isTypeDependent())
6195 return nullptr;
6196 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006197 }
Mike Stump11289f42009-09-09 15:08:12 +00006198
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006199 case Stmt::OMPArraySectionExprClass: {
6200 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6201 ParentDecl);
6202 }
Mike Stump11289f42009-09-09 15:08:12 +00006203
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006204 case Stmt::ConditionalOperatorClass: {
6205 // For conditional operators we need to see if either the LHS or RHS are
6206 // non-NULL Expr's. If one is non-NULL, we return it.
6207 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006208
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006209 // Handle the GNU extension for missing LHS.
6210 if (const Expr *LHSExpr = C->getLHS()) {
6211 // In C++, we can have a throw-expression, which has 'void' type.
6212 if (!LHSExpr->getType()->isVoidType())
6213 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6214 return LHS;
6215 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006216
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006217 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006218 if (C->getRHS()->getType()->isVoidType())
6219 return nullptr;
6220
6221 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006222 }
6223
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006224 // Accesses to members are potential references to data on the stack.
6225 case Stmt::MemberExprClass: {
6226 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006227
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006228 // Check for indirect access. We only want direct field accesses.
6229 if (M->isArrow())
6230 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006231
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006232 // Check whether the member type is itself a reference, in which case
6233 // we're not going to refer to the member, but to what the member refers
6234 // to.
6235 if (M->getMemberDecl()->getType()->isReferenceType())
6236 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006237
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006238 return EvalVal(M->getBase(), refVars, ParentDecl);
6239 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006240
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006241 case Stmt::MaterializeTemporaryExprClass:
6242 if (const Expr *Result =
6243 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6244 refVars, ParentDecl))
6245 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006246 return E;
6247
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006248 default:
6249 // Check that we don't return or take the address of a reference to a
6250 // temporary. This is only useful in C++.
6251 if (!E->isTypeDependent() && E->isRValue())
6252 return E;
6253
6254 // Everything else: we simply don't reason about them.
6255 return nullptr;
6256 }
6257 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006258}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006259
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006260void
6261Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6262 SourceLocation ReturnLoc,
6263 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006264 const AttrVec *Attrs,
6265 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006266 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6267
6268 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006269 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6270 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006271 CheckNonNullExpr(*this, RetValExp))
6272 Diag(ReturnLoc, diag::warn_null_ret)
6273 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006274
6275 // C++11 [basic.stc.dynamic.allocation]p4:
6276 // If an allocation function declared with a non-throwing
6277 // exception-specification fails to allocate storage, it shall return
6278 // a null pointer. Any other allocation function that fails to allocate
6279 // storage shall indicate failure only by throwing an exception [...]
6280 if (FD) {
6281 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6282 if (Op == OO_New || Op == OO_Array_New) {
6283 const FunctionProtoType *Proto
6284 = FD->getType()->castAs<FunctionProtoType>();
6285 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6286 CheckNonNullExpr(*this, RetValExp))
6287 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6288 << FD << getLangOpts().CPlusPlus11;
6289 }
6290 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006291}
6292
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006293//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6294
6295/// Check for comparisons of floating point operands using != and ==.
6296/// Issue a warning if these are no self-comparisons, as they are not likely
6297/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006298void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006299 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6300 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006301
6302 // Special case: check for x == x (which is OK).
6303 // Do not emit warnings for such cases.
6304 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6305 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6306 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006307 return;
Mike Stump11289f42009-09-09 15:08:12 +00006308
Ted Kremenekeda40e22007-11-29 00:59:04 +00006309 // Special case: check for comparisons against literals that can be exactly
6310 // represented by APFloat. In such cases, do not emit a warning. This
6311 // is a heuristic: often comparison against such literals are used to
6312 // detect if a value in a variable has not changed. This clearly can
6313 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006314 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6315 if (FLL->isExact())
6316 return;
6317 } else
6318 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6319 if (FLR->isExact())
6320 return;
Mike Stump11289f42009-09-09 15:08:12 +00006321
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006322 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006323 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006324 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006325 return;
Mike Stump11289f42009-09-09 15:08:12 +00006326
David Blaikie1f4ff152012-07-16 20:47:22 +00006327 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006328 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006329 return;
Mike Stump11289f42009-09-09 15:08:12 +00006330
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006331 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006332 Diag(Loc, diag::warn_floatingpoint_eq)
6333 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006334}
John McCallca01b222010-01-04 23:21:16 +00006335
John McCall70aa5392010-01-06 05:24:50 +00006336//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6337//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006338
John McCall70aa5392010-01-06 05:24:50 +00006339namespace {
John McCallca01b222010-01-04 23:21:16 +00006340
John McCall70aa5392010-01-06 05:24:50 +00006341/// Structure recording the 'active' range of an integer-valued
6342/// expression.
6343struct IntRange {
6344 /// The number of bits active in the int.
6345 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006346
John McCall70aa5392010-01-06 05:24:50 +00006347 /// True if the int is known not to have negative values.
6348 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006349
John McCall70aa5392010-01-06 05:24:50 +00006350 IntRange(unsigned Width, bool NonNegative)
6351 : Width(Width), NonNegative(NonNegative)
6352 {}
John McCallca01b222010-01-04 23:21:16 +00006353
John McCall817d4af2010-11-10 23:38:19 +00006354 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006355 static IntRange forBoolType() {
6356 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006357 }
6358
John McCall817d4af2010-11-10 23:38:19 +00006359 /// Returns the range of an opaque value of the given integral type.
6360 static IntRange forValueOfType(ASTContext &C, QualType T) {
6361 return forValueOfCanonicalType(C,
6362 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006363 }
6364
John McCall817d4af2010-11-10 23:38:19 +00006365 /// Returns the range of an opaque value of a canonical integral type.
6366 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006367 assert(T->isCanonicalUnqualified());
6368
6369 if (const VectorType *VT = dyn_cast<VectorType>(T))
6370 T = VT->getElementType().getTypePtr();
6371 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6372 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006373 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6374 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006375
David Majnemer6a426652013-06-07 22:07:20 +00006376 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006377 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006378 EnumDecl *Enum = ET->getDecl();
6379 if (!Enum->isCompleteDefinition())
6380 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006381
David Majnemer6a426652013-06-07 22:07:20 +00006382 unsigned NumPositive = Enum->getNumPositiveBits();
6383 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006384
David Majnemer6a426652013-06-07 22:07:20 +00006385 if (NumNegative == 0)
6386 return IntRange(NumPositive, true/*NonNegative*/);
6387 else
6388 return IntRange(std::max(NumPositive + 1, NumNegative),
6389 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006390 }
John McCall70aa5392010-01-06 05:24:50 +00006391
6392 const BuiltinType *BT = cast<BuiltinType>(T);
6393 assert(BT->isInteger());
6394
6395 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6396 }
6397
John McCall817d4af2010-11-10 23:38:19 +00006398 /// Returns the "target" range of a canonical integral type, i.e.
6399 /// the range of values expressible in the type.
6400 ///
6401 /// This matches forValueOfCanonicalType except that enums have the
6402 /// full range of their type, not the range of their enumerators.
6403 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6404 assert(T->isCanonicalUnqualified());
6405
6406 if (const VectorType *VT = dyn_cast<VectorType>(T))
6407 T = VT->getElementType().getTypePtr();
6408 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6409 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006410 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6411 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006412 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006413 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006414
6415 const BuiltinType *BT = cast<BuiltinType>(T);
6416 assert(BT->isInteger());
6417
6418 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6419 }
6420
6421 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006422 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006423 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006424 L.NonNegative && R.NonNegative);
6425 }
6426
John McCall817d4af2010-11-10 23:38:19 +00006427 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006428 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006429 return IntRange(std::min(L.Width, R.Width),
6430 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006431 }
6432};
6433
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006434IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006435 if (value.isSigned() && value.isNegative())
6436 return IntRange(value.getMinSignedBits(), false);
6437
6438 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006439 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006440
6441 // isNonNegative() just checks the sign bit without considering
6442 // signedness.
6443 return IntRange(value.getActiveBits(), true);
6444}
6445
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006446IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6447 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006448 if (result.isInt())
6449 return GetValueRange(C, result.getInt(), MaxWidth);
6450
6451 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006452 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6453 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6454 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6455 R = IntRange::join(R, El);
6456 }
John McCall70aa5392010-01-06 05:24:50 +00006457 return R;
6458 }
6459
6460 if (result.isComplexInt()) {
6461 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6462 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6463 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006464 }
6465
6466 // This can happen with lossless casts to intptr_t of "based" lvalues.
6467 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006468 // FIXME: The only reason we need to pass the type in here is to get
6469 // the sign right on this one case. It would be nice if APValue
6470 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006471 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006472 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006473}
John McCall70aa5392010-01-06 05:24:50 +00006474
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006475QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006476 QualType Ty = E->getType();
6477 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6478 Ty = AtomicRHS->getValueType();
6479 return Ty;
6480}
6481
John McCall70aa5392010-01-06 05:24:50 +00006482/// Pseudo-evaluate the given integer expression, estimating the
6483/// range of values it might take.
6484///
6485/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006486IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006487 E = E->IgnoreParens();
6488
6489 // Try a full evaluation first.
6490 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006491 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006492 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006493
6494 // I think we only want to look through implicit casts here; if the
6495 // user has an explicit widening cast, we should treat the value as
6496 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006497 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006498 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006499 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6500
Eli Friedmane6d33952013-07-08 20:20:06 +00006501 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006502
George Burgess IVdf1ed002016-01-13 01:52:39 +00006503 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6504 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00006505
John McCall70aa5392010-01-06 05:24:50 +00006506 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006507 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006508 return OutputTypeRange;
6509
6510 IntRange SubRange
6511 = GetExprRange(C, CE->getSubExpr(),
6512 std::min(MaxWidth, OutputTypeRange.Width));
6513
6514 // Bail out if the subexpr's range is as wide as the cast type.
6515 if (SubRange.Width >= OutputTypeRange.Width)
6516 return OutputTypeRange;
6517
6518 // Otherwise, we take the smaller width, and we're non-negative if
6519 // either the output type or the subexpr is.
6520 return IntRange(SubRange.Width,
6521 SubRange.NonNegative || OutputTypeRange.NonNegative);
6522 }
6523
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006524 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006525 // If we can fold the condition, just take that operand.
6526 bool CondResult;
6527 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6528 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6529 : CO->getFalseExpr(),
6530 MaxWidth);
6531
6532 // Otherwise, conservatively merge.
6533 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6534 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6535 return IntRange::join(L, R);
6536 }
6537
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006538 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006539 switch (BO->getOpcode()) {
6540
6541 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006542 case BO_LAnd:
6543 case BO_LOr:
6544 case BO_LT:
6545 case BO_GT:
6546 case BO_LE:
6547 case BO_GE:
6548 case BO_EQ:
6549 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006550 return IntRange::forBoolType();
6551
John McCallc3688382011-07-13 06:35:24 +00006552 // The type of the assignments is the type of the LHS, so the RHS
6553 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006554 case BO_MulAssign:
6555 case BO_DivAssign:
6556 case BO_RemAssign:
6557 case BO_AddAssign:
6558 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006559 case BO_XorAssign:
6560 case BO_OrAssign:
6561 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006562 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006563
John McCallc3688382011-07-13 06:35:24 +00006564 // Simple assignments just pass through the RHS, which will have
6565 // been coerced to the LHS type.
6566 case BO_Assign:
6567 // TODO: bitfields?
6568 return GetExprRange(C, BO->getRHS(), MaxWidth);
6569
John McCall70aa5392010-01-06 05:24:50 +00006570 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006571 case BO_PtrMemD:
6572 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006573 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006574
John McCall2ce81ad2010-01-06 22:07:33 +00006575 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006576 case BO_And:
6577 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006578 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6579 GetExprRange(C, BO->getRHS(), MaxWidth));
6580
John McCall70aa5392010-01-06 05:24:50 +00006581 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006582 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006583 // ...except that we want to treat '1 << (blah)' as logically
6584 // positive. It's an important idiom.
6585 if (IntegerLiteral *I
6586 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6587 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006588 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006589 return IntRange(R.Width, /*NonNegative*/ true);
6590 }
6591 }
6592 // fallthrough
6593
John McCalle3027922010-08-25 11:45:40 +00006594 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006595 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006596
John McCall2ce81ad2010-01-06 22:07:33 +00006597 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006598 case BO_Shr:
6599 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006600 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6601
6602 // If the shift amount is a positive constant, drop the width by
6603 // that much.
6604 llvm::APSInt shift;
6605 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6606 shift.isNonNegative()) {
6607 unsigned zext = shift.getZExtValue();
6608 if (zext >= L.Width)
6609 L.Width = (L.NonNegative ? 0 : 1);
6610 else
6611 L.Width -= zext;
6612 }
6613
6614 return L;
6615 }
6616
6617 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006618 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006619 return GetExprRange(C, BO->getRHS(), MaxWidth);
6620
John McCall2ce81ad2010-01-06 22:07:33 +00006621 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006622 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006623 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006624 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006625 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006626
John McCall51431812011-07-14 22:39:48 +00006627 // The width of a division result is mostly determined by the size
6628 // of the LHS.
6629 case BO_Div: {
6630 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006631 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006632 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6633
6634 // If the divisor is constant, use that.
6635 llvm::APSInt divisor;
6636 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6637 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6638 if (log2 >= L.Width)
6639 L.Width = (L.NonNegative ? 0 : 1);
6640 else
6641 L.Width = std::min(L.Width - log2, MaxWidth);
6642 return L;
6643 }
6644
6645 // Otherwise, just use the LHS's width.
6646 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6647 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6648 }
6649
6650 // The result of a remainder can't be larger than the result of
6651 // either side.
6652 case BO_Rem: {
6653 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006654 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006655 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6656 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6657
6658 IntRange meet = IntRange::meet(L, R);
6659 meet.Width = std::min(meet.Width, MaxWidth);
6660 return meet;
6661 }
6662
6663 // The default behavior is okay for these.
6664 case BO_Mul:
6665 case BO_Add:
6666 case BO_Xor:
6667 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006668 break;
6669 }
6670
John McCall51431812011-07-14 22:39:48 +00006671 // The default case is to treat the operation as if it were closed
6672 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006673 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6674 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6675 return IntRange::join(L, R);
6676 }
6677
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006678 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006679 switch (UO->getOpcode()) {
6680 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006681 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006682 return IntRange::forBoolType();
6683
6684 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006685 case UO_Deref:
6686 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006687 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006688
6689 default:
6690 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6691 }
6692 }
6693
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006694 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006695 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6696
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006697 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006698 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006699 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006700
Eli Friedmane6d33952013-07-08 20:20:06 +00006701 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006702}
John McCall263a48b2010-01-04 23:31:57 +00006703
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006704IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006705 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006706}
6707
John McCall263a48b2010-01-04 23:31:57 +00006708/// Checks whether the given value, which currently has the given
6709/// source semantics, has the same value when coerced through the
6710/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006711bool IsSameFloatAfterCast(const llvm::APFloat &value,
6712 const llvm::fltSemantics &Src,
6713 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006714 llvm::APFloat truncated = value;
6715
6716 bool ignored;
6717 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6718 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6719
6720 return truncated.bitwiseIsEqual(value);
6721}
6722
6723/// Checks whether the given value, which currently has the given
6724/// source semantics, has the same value when coerced through the
6725/// target semantics.
6726///
6727/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006728bool IsSameFloatAfterCast(const APValue &value,
6729 const llvm::fltSemantics &Src,
6730 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006731 if (value.isFloat())
6732 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6733
6734 if (value.isVector()) {
6735 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6736 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6737 return false;
6738 return true;
6739 }
6740
6741 assert(value.isComplexFloat());
6742 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6743 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6744}
6745
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006746void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006747
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006748bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00006749 // Suppress cases where we are comparing against an enum constant.
6750 if (const DeclRefExpr *DR =
6751 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6752 if (isa<EnumConstantDecl>(DR->getDecl()))
6753 return false;
6754
6755 // Suppress cases where the '0' value is expanded from a macro.
6756 if (E->getLocStart().isMacroID())
6757 return false;
6758
John McCallcc7e5bf2010-05-06 08:58:33 +00006759 llvm::APSInt Value;
6760 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6761}
6762
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006763bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00006764 // Strip off implicit integral promotions.
6765 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006766 if (ICE->getCastKind() != CK_IntegralCast &&
6767 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006768 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006769 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006770 }
6771
6772 return E->getType()->isEnumeralType();
6773}
6774
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006775void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006776 // Disable warning in template instantiations.
6777 if (!S.ActiveTemplateInstantiations.empty())
6778 return;
6779
John McCalle3027922010-08-25 11:45:40 +00006780 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006781 if (E->isValueDependent())
6782 return;
6783
John McCalle3027922010-08-25 11:45:40 +00006784 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006785 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006786 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006787 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006788 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006789 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006790 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006791 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006792 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006793 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006794 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006795 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006796 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006797 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006798 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006799 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6800 }
6801}
6802
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006803void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
6804 Expr *Constant, Expr *Other,
6805 llvm::APSInt Value,
6806 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006807 // Disable warning in template instantiations.
6808 if (!S.ActiveTemplateInstantiations.empty())
6809 return;
6810
Richard Trieu0f097742014-04-04 04:13:47 +00006811 // TODO: Investigate using GetExprRange() to get tighter bounds
6812 // on the bit ranges.
6813 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006814 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006815 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006816 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6817 unsigned OtherWidth = OtherRange.Width;
6818
6819 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6820
Richard Trieu560910c2012-11-14 22:50:24 +00006821 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006822 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006823 return;
6824
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006825 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006826 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006827
Richard Trieu0f097742014-04-04 04:13:47 +00006828 // Used for diagnostic printout.
6829 enum {
6830 LiteralConstant = 0,
6831 CXXBoolLiteralTrue,
6832 CXXBoolLiteralFalse
6833 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006834
Richard Trieu0f097742014-04-04 04:13:47 +00006835 if (!OtherIsBooleanType) {
6836 QualType ConstantT = Constant->getType();
6837 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006838
Richard Trieu0f097742014-04-04 04:13:47 +00006839 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6840 return;
6841 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6842 "comparison with non-integer type");
6843
6844 bool ConstantSigned = ConstantT->isSignedIntegerType();
6845 bool CommonSigned = CommonT->isSignedIntegerType();
6846
6847 bool EqualityOnly = false;
6848
6849 if (CommonSigned) {
6850 // The common type is signed, therefore no signed to unsigned conversion.
6851 if (!OtherRange.NonNegative) {
6852 // Check that the constant is representable in type OtherT.
6853 if (ConstantSigned) {
6854 if (OtherWidth >= Value.getMinSignedBits())
6855 return;
6856 } else { // !ConstantSigned
6857 if (OtherWidth >= Value.getActiveBits() + 1)
6858 return;
6859 }
6860 } else { // !OtherSigned
6861 // Check that the constant is representable in type OtherT.
6862 // Negative values are out of range.
6863 if (ConstantSigned) {
6864 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6865 return;
6866 } else { // !ConstantSigned
6867 if (OtherWidth >= Value.getActiveBits())
6868 return;
6869 }
Richard Trieu560910c2012-11-14 22:50:24 +00006870 }
Richard Trieu0f097742014-04-04 04:13:47 +00006871 } else { // !CommonSigned
6872 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006873 if (OtherWidth >= Value.getActiveBits())
6874 return;
Craig Toppercf360162014-06-18 05:13:11 +00006875 } else { // OtherSigned
6876 assert(!ConstantSigned &&
6877 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006878 // Check to see if the constant is representable in OtherT.
6879 if (OtherWidth > Value.getActiveBits())
6880 return;
6881 // Check to see if the constant is equivalent to a negative value
6882 // cast to CommonT.
6883 if (S.Context.getIntWidth(ConstantT) ==
6884 S.Context.getIntWidth(CommonT) &&
6885 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6886 return;
6887 // The constant value rests between values that OtherT can represent
6888 // after conversion. Relational comparison still works, but equality
6889 // comparisons will be tautological.
6890 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006891 }
6892 }
Richard Trieu0f097742014-04-04 04:13:47 +00006893
6894 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6895
6896 if (op == BO_EQ || op == BO_NE) {
6897 IsTrue = op == BO_NE;
6898 } else if (EqualityOnly) {
6899 return;
6900 } else if (RhsConstant) {
6901 if (op == BO_GT || op == BO_GE)
6902 IsTrue = !PositiveConstant;
6903 else // op == BO_LT || op == BO_LE
6904 IsTrue = PositiveConstant;
6905 } else {
6906 if (op == BO_LT || op == BO_LE)
6907 IsTrue = !PositiveConstant;
6908 else // op == BO_GT || op == BO_GE
6909 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006910 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006911 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006912 // Other isKnownToHaveBooleanValue
6913 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6914 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6915 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6916
6917 static const struct LinkedConditions {
6918 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6919 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6920 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6921 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6922 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6923 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6924
6925 } TruthTable = {
6926 // Constant on LHS. | Constant on RHS. |
6927 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6928 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6929 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6930 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6931 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6932 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6933 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6934 };
6935
6936 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6937
6938 enum ConstantValue ConstVal = Zero;
6939 if (Value.isUnsigned() || Value.isNonNegative()) {
6940 if (Value == 0) {
6941 LiteralOrBoolConstant =
6942 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6943 ConstVal = Zero;
6944 } else if (Value == 1) {
6945 LiteralOrBoolConstant =
6946 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6947 ConstVal = One;
6948 } else {
6949 LiteralOrBoolConstant = LiteralConstant;
6950 ConstVal = GT_One;
6951 }
6952 } else {
6953 ConstVal = LT_Zero;
6954 }
6955
6956 CompareBoolWithConstantResult CmpRes;
6957
6958 switch (op) {
6959 case BO_LT:
6960 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6961 break;
6962 case BO_GT:
6963 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6964 break;
6965 case BO_LE:
6966 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6967 break;
6968 case BO_GE:
6969 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6970 break;
6971 case BO_EQ:
6972 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6973 break;
6974 case BO_NE:
6975 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6976 break;
6977 default:
6978 CmpRes = Unkwn;
6979 break;
6980 }
6981
6982 if (CmpRes == AFals) {
6983 IsTrue = false;
6984 } else if (CmpRes == ATrue) {
6985 IsTrue = true;
6986 } else {
6987 return;
6988 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006989 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006990
6991 // If this is a comparison to an enum constant, include that
6992 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006993 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006994 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6995 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6996
6997 SmallString<64> PrettySourceValue;
6998 llvm::raw_svector_ostream OS(PrettySourceValue);
6999 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007000 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007001 else
7002 OS << Value;
7003
Richard Trieu0f097742014-04-04 04:13:47 +00007004 S.DiagRuntimeBehavior(
7005 E->getOperatorLoc(), E,
7006 S.PDiag(diag::warn_out_of_range_compare)
7007 << OS.str() << LiteralOrBoolConstant
7008 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7009 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007010}
7011
John McCallcc7e5bf2010-05-06 08:58:33 +00007012/// Analyze the operands of the given comparison. Implements the
7013/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007014void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007015 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7016 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007017}
John McCall263a48b2010-01-04 23:31:57 +00007018
John McCallca01b222010-01-04 23:21:16 +00007019/// \brief Implements -Wsign-compare.
7020///
Richard Trieu82402a02011-09-15 21:56:47 +00007021/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007022void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007023 // The type the comparison is being performed in.
7024 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007025
7026 // Only analyze comparison operators where both sides have been converted to
7027 // the same type.
7028 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7029 return AnalyzeImpConvsInComparison(S, E);
7030
7031 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007032 if (E->isValueDependent())
7033 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007034
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007035 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7036 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007037
7038 bool IsComparisonConstant = false;
7039
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007040 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007041 // of 'true' or 'false'.
7042 if (T->isIntegralType(S.Context)) {
7043 llvm::APSInt RHSValue;
7044 bool IsRHSIntegralLiteral =
7045 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7046 llvm::APSInt LHSValue;
7047 bool IsLHSIntegralLiteral =
7048 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7049 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7050 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7051 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7052 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7053 else
7054 IsComparisonConstant =
7055 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007056 } else if (!T->hasUnsignedIntegerRepresentation())
7057 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007058
John McCallcc7e5bf2010-05-06 08:58:33 +00007059 // We don't do anything special if this isn't an unsigned integral
7060 // comparison: we're only interested in integral comparisons, and
7061 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007062 //
7063 // We also don't care about value-dependent expressions or expressions
7064 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007065 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007066 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007067
John McCallcc7e5bf2010-05-06 08:58:33 +00007068 // Check to see if one of the (unmodified) operands is of different
7069 // signedness.
7070 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007071 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7072 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007073 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007074 signedOperand = LHS;
7075 unsignedOperand = RHS;
7076 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7077 signedOperand = RHS;
7078 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007079 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007080 CheckTrivialUnsignedComparison(S, E);
7081 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007082 }
7083
John McCallcc7e5bf2010-05-06 08:58:33 +00007084 // Otherwise, calculate the effective range of the signed operand.
7085 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007086
John McCallcc7e5bf2010-05-06 08:58:33 +00007087 // Go ahead and analyze implicit conversions in the operands. Note
7088 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007089 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7090 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007091
John McCallcc7e5bf2010-05-06 08:58:33 +00007092 // If the signed range is non-negative, -Wsign-compare won't fire,
7093 // but we should still check for comparisons which are always true
7094 // or false.
7095 if (signedRange.NonNegative)
7096 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007097
7098 // For (in)equality comparisons, if the unsigned operand is a
7099 // constant which cannot collide with a overflowed signed operand,
7100 // then reinterpreting the signed operand as unsigned will not
7101 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007102 if (E->isEqualityOp()) {
7103 unsigned comparisonWidth = S.Context.getIntWidth(T);
7104 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007105
John McCallcc7e5bf2010-05-06 08:58:33 +00007106 // We should never be unable to prove that the unsigned operand is
7107 // non-negative.
7108 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7109
7110 if (unsignedRange.Width < comparisonWidth)
7111 return;
7112 }
7113
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007114 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7115 S.PDiag(diag::warn_mixed_sign_comparison)
7116 << LHS->getType() << RHS->getType()
7117 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007118}
7119
John McCall1f425642010-11-11 03:21:53 +00007120/// Analyzes an attempt to assign the given value to a bitfield.
7121///
7122/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007123bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7124 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007125 assert(Bitfield->isBitField());
7126 if (Bitfield->isInvalidDecl())
7127 return false;
7128
John McCalldeebbcf2010-11-11 05:33:51 +00007129 // White-list bool bitfields.
7130 if (Bitfield->getType()->isBooleanType())
7131 return false;
7132
Douglas Gregor789adec2011-02-04 13:09:01 +00007133 // Ignore value- or type-dependent expressions.
7134 if (Bitfield->getBitWidth()->isValueDependent() ||
7135 Bitfield->getBitWidth()->isTypeDependent() ||
7136 Init->isValueDependent() ||
7137 Init->isTypeDependent())
7138 return false;
7139
John McCall1f425642010-11-11 03:21:53 +00007140 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7141
Richard Smith5fab0c92011-12-28 19:48:30 +00007142 llvm::APSInt Value;
7143 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007144 return false;
7145
John McCall1f425642010-11-11 03:21:53 +00007146 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007147 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007148
7149 if (OriginalWidth <= FieldWidth)
7150 return false;
7151
Eli Friedmanc267a322012-01-26 23:11:39 +00007152 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007153 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007154 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007155
Eli Friedmanc267a322012-01-26 23:11:39 +00007156 // Check whether the stored value is equal to the original value.
7157 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007158 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007159 return false;
7160
Eli Friedmanc267a322012-01-26 23:11:39 +00007161 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007162 // therefore don't strictly fit into a signed bitfield of width 1.
7163 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007164 return false;
7165
John McCall1f425642010-11-11 03:21:53 +00007166 std::string PrettyValue = Value.toString(10);
7167 std::string PrettyTrunc = TruncatedValue.toString(10);
7168
7169 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7170 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7171 << Init->getSourceRange();
7172
7173 return true;
7174}
7175
John McCalld2a53122010-11-09 23:24:47 +00007176/// Analyze the given simple or compound assignment for warning-worthy
7177/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007178void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007179 // Just recurse on the LHS.
7180 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7181
7182 // We want to recurse on the RHS as normal unless we're assigning to
7183 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007184 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007185 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007186 E->getOperatorLoc())) {
7187 // Recurse, ignoring any implicit conversions on the RHS.
7188 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7189 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007190 }
7191 }
7192
7193 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7194}
7195
John McCall263a48b2010-01-04 23:31:57 +00007196/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007197void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7198 SourceLocation CContext, unsigned diag,
7199 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007200 if (pruneControlFlow) {
7201 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7202 S.PDiag(diag)
7203 << SourceType << T << E->getSourceRange()
7204 << SourceRange(CContext));
7205 return;
7206 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007207 S.Diag(E->getExprLoc(), diag)
7208 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7209}
7210
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007211/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007212void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7213 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007214 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007215}
7216
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007217/// Diagnose an implicit cast from a literal expression. Does not warn when the
7218/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00007219void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
7220 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007221 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00007222 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007223 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007224 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7225 T->hasUnsignedIntegerRepresentation());
7226 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00007227 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007228 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00007229 return;
7230
Eli Friedman07185912013-08-29 23:44:43 +00007231 // FIXME: Force the precision of the source value down so we don't print
7232 // digits which are usually useless (we don't really care here if we
7233 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7234 // would automatically print the shortest representation, but it's a bit
7235 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007236 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007237 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7238 precision = (precision * 59 + 195) / 196;
7239 Value.toString(PrettySourceValue, precision);
7240
David Blaikie9b88cc02012-05-15 17:18:27 +00007241 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00007242 if (T->isSpecificBuiltinType(BuiltinType::Bool))
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007243 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007244 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007245 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007246
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007247 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00007248 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
7249 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00007250}
7251
John McCall18a2c2c2010-11-09 22:22:12 +00007252std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7253 if (!Range.Width) return "0";
7254
7255 llvm::APSInt ValueInRange = Value;
7256 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007257 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007258 return ValueInRange.toString(10);
7259}
7260
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007261bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007262 if (!isa<ImplicitCastExpr>(Ex))
7263 return false;
7264
7265 Expr *InnerE = Ex->IgnoreParenImpCasts();
7266 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7267 const Type *Source =
7268 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7269 if (Target->isDependentType())
7270 return false;
7271
7272 const BuiltinType *FloatCandidateBT =
7273 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7274 const Type *BoolCandidateType = ToBool ? Target : Source;
7275
7276 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7277 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7278}
7279
7280void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7281 SourceLocation CC) {
7282 unsigned NumArgs = TheCall->getNumArgs();
7283 for (unsigned i = 0; i < NumArgs; ++i) {
7284 Expr *CurrA = TheCall->getArg(i);
7285 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7286 continue;
7287
7288 bool IsSwapped = ((i > 0) &&
7289 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7290 IsSwapped |= ((i < (NumArgs - 1)) &&
7291 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7292 if (IsSwapped) {
7293 // Warn on this floating-point to bool conversion.
7294 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7295 CurrA->getType(), CC,
7296 diag::warn_impcast_floating_point_to_bool);
7297 }
7298 }
7299}
7300
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007301void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007302 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7303 E->getExprLoc()))
7304 return;
7305
Richard Trieu09d6b802016-01-08 23:35:06 +00007306 // Don't warn on functions which have return type nullptr_t.
7307 if (isa<CallExpr>(E))
7308 return;
7309
Richard Trieu5b993502014-10-15 03:42:06 +00007310 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7311 const Expr::NullPointerConstantKind NullKind =
7312 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7313 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7314 return;
7315
7316 // Return if target type is a safe conversion.
7317 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7318 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7319 return;
7320
7321 SourceLocation Loc = E->getSourceRange().getBegin();
7322
Richard Trieu0a5e1662016-02-13 00:58:53 +00007323 // Venture through the macro stacks to get to the source of macro arguments.
7324 // The new location is a better location than the complete location that was
7325 // passed in.
7326 while (S.SourceMgr.isMacroArgExpansion(Loc))
7327 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
7328
7329 while (S.SourceMgr.isMacroArgExpansion(CC))
7330 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
7331
Richard Trieu5b993502014-10-15 03:42:06 +00007332 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00007333 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
7334 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7335 Loc, S.SourceMgr, S.getLangOpts());
7336 if (MacroName == "NULL")
7337 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00007338 }
7339
7340 // Only warn if the null and context location are in the same macro expansion.
7341 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7342 return;
7343
7344 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7345 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7346 << FixItHint::CreateReplacement(Loc,
7347 S.getFixItZeroLiteralForType(T, Loc));
7348}
7349
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007350void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7351 ObjCArrayLiteral *ArrayLiteral);
7352void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7353 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00007354
7355/// Check a single element within a collection literal against the
7356/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007357void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7358 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007359 // Skip a bitcast to 'id' or qualified 'id'.
7360 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7361 if (ICE->getCastKind() == CK_BitCast &&
7362 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7363 Element = ICE->getSubExpr();
7364 }
7365
7366 QualType ElementType = Element->getType();
7367 ExprResult ElementResult(Element);
7368 if (ElementType->getAs<ObjCObjectPointerType>() &&
7369 S.CheckSingleAssignmentConstraints(TargetElementType,
7370 ElementResult,
7371 false, false)
7372 != Sema::Compatible) {
7373 S.Diag(Element->getLocStart(),
7374 diag::warn_objc_collection_literal_element)
7375 << ElementType << ElementKind << TargetElementType
7376 << Element->getSourceRange();
7377 }
7378
7379 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7380 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7381 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7382 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7383}
7384
7385/// Check an Objective-C array literal being converted to the given
7386/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007387void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7388 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007389 if (!S.NSArrayDecl)
7390 return;
7391
7392 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7393 if (!TargetObjCPtr)
7394 return;
7395
7396 if (TargetObjCPtr->isUnspecialized() ||
7397 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7398 != S.NSArrayDecl->getCanonicalDecl())
7399 return;
7400
7401 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7402 if (TypeArgs.size() != 1)
7403 return;
7404
7405 QualType TargetElementType = TypeArgs[0];
7406 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7407 checkObjCCollectionLiteralElement(S, TargetElementType,
7408 ArrayLiteral->getElement(I),
7409 0);
7410 }
7411}
7412
7413/// Check an Objective-C dictionary literal being converted to the given
7414/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007415void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7416 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007417 if (!S.NSDictionaryDecl)
7418 return;
7419
7420 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7421 if (!TargetObjCPtr)
7422 return;
7423
7424 if (TargetObjCPtr->isUnspecialized() ||
7425 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7426 != S.NSDictionaryDecl->getCanonicalDecl())
7427 return;
7428
7429 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7430 if (TypeArgs.size() != 2)
7431 return;
7432
7433 QualType TargetKeyType = TypeArgs[0];
7434 QualType TargetObjectType = TypeArgs[1];
7435 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7436 auto Element = DictionaryLiteral->getKeyValueElement(I);
7437 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7438 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7439 }
7440}
7441
Richard Trieufc404c72016-02-05 23:02:38 +00007442// Helper function to filter out cases for constant width constant conversion.
7443// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007444bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7445 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00007446 // If initializing from a constant, and the constant starts with '0',
7447 // then it is a binary, octal, or hexadecimal. Allow these constants
7448 // to fill all the bits, even if there is a sign change.
7449 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7450 const char FirstLiteralCharacter =
7451 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7452 if (FirstLiteralCharacter == '0')
7453 return false;
7454 }
7455
7456 // If the CC location points to a '{', and the type is char, then assume
7457 // assume it is an array initialization.
7458 if (CC.isValid() && T->isCharType()) {
7459 const char FirstContextCharacter =
7460 S.getSourceManager().getCharacterData(CC)[0];
7461 if (FirstContextCharacter == '{')
7462 return false;
7463 }
7464
7465 return true;
7466}
7467
John McCallcc7e5bf2010-05-06 08:58:33 +00007468void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007469 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007470 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007471
John McCallcc7e5bf2010-05-06 08:58:33 +00007472 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7473 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7474 if (Source == Target) return;
7475 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007476
Chandler Carruthc22845a2011-07-26 05:40:03 +00007477 // If the conversion context location is invalid don't complain. We also
7478 // don't want to emit a warning if the issue occurs from the expansion of
7479 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7480 // delay this check as long as possible. Once we detect we are in that
7481 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007482 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007483 return;
7484
Richard Trieu021baa32011-09-23 20:10:00 +00007485 // Diagnose implicit casts to bool.
7486 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7487 if (isa<StringLiteral>(E))
7488 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007489 // and expressions, for instance, assert(0 && "error here"), are
7490 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007491 return DiagnoseImpCast(S, E, T, CC,
7492 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007493 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7494 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7495 // This covers the literal expressions that evaluate to Objective-C
7496 // objects.
7497 return DiagnoseImpCast(S, E, T, CC,
7498 diag::warn_impcast_objective_c_literal_to_bool);
7499 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007500 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7501 // Warn on pointer to bool conversion that is always true.
7502 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7503 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007504 }
Richard Trieu021baa32011-09-23 20:10:00 +00007505 }
John McCall263a48b2010-01-04 23:31:57 +00007506
Douglas Gregor5054cb02015-07-07 03:58:22 +00007507 // Check implicit casts from Objective-C collection literals to specialized
7508 // collection types, e.g., NSArray<NSString *> *.
7509 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7510 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7511 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7512 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7513
John McCall263a48b2010-01-04 23:31:57 +00007514 // Strip vector types.
7515 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007516 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007517 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007518 return;
John McCallacf0ee52010-10-08 02:01:28 +00007519 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007520 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007521
7522 // If the vector cast is cast between two vectors of the same size, it is
7523 // a bitcast, not a conversion.
7524 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7525 return;
John McCall263a48b2010-01-04 23:31:57 +00007526
7527 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7528 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7529 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007530 if (auto VecTy = dyn_cast<VectorType>(Target))
7531 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007532
7533 // Strip complex types.
7534 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007535 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007536 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007537 return;
7538
John McCallacf0ee52010-10-08 02:01:28 +00007539 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007540 }
John McCall263a48b2010-01-04 23:31:57 +00007541
7542 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7543 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7544 }
7545
7546 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7547 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7548
7549 // If the source is floating point...
7550 if (SourceBT && SourceBT->isFloatingPoint()) {
7551 // ...and the target is floating point...
7552 if (TargetBT && TargetBT->isFloatingPoint()) {
7553 // ...then warn if we're dropping FP rank.
7554
7555 // Builtin FP kinds are ordered by increasing FP rank.
7556 if (SourceBT->getKind() > TargetBT->getKind()) {
7557 // Don't warn about float constants that are precisely
7558 // representable in the target type.
7559 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007560 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007561 // Value might be a float, a float vector, or a float complex.
7562 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007563 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7564 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007565 return;
7566 }
7567
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007568 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007569 return;
7570
John McCallacf0ee52010-10-08 02:01:28 +00007571 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007572 }
7573 // ... or possibly if we're increasing rank, too
7574 else if (TargetBT->getKind() > SourceBT->getKind()) {
7575 if (S.SourceMgr.isInSystemMacro(CC))
7576 return;
7577
7578 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007579 }
7580 return;
7581 }
7582
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007583 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007584 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007585 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007586 return;
7587
Chandler Carruth22c7a792011-02-17 11:05:49 +00007588 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007589 // We also want to warn on, e.g., "int i = -1.234"
7590 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7591 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7592 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7593
Chandler Carruth016ef402011-04-10 08:36:24 +00007594 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7595 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007596 } else {
7597 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7598 }
7599 }
John McCall263a48b2010-01-04 23:31:57 +00007600
Richard Smith54894fd2015-12-30 01:06:52 +00007601 // Detect the case where a call result is converted from floating-point to
7602 // to bool, and the final argument to the call is converted from bool, to
7603 // discover this typo:
7604 //
7605 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
7606 //
7607 // FIXME: This is an incredibly special case; is there some more general
7608 // way to detect this class of misplaced-parentheses bug?
7609 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007610 // Check last argument of function call to see if it is an
7611 // implicit cast from a type matching the type the result
7612 // is being cast to.
7613 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00007614 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007615 Expr *LastA = CEx->getArg(NumArgs - 1);
7616 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00007617 if (isa<ImplicitCastExpr>(LastA) &&
7618 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007619 // Warn on this floating-point to bool conversion
7620 DiagnoseImpCast(S, E, T, CC,
7621 diag::warn_impcast_floating_point_to_bool);
7622 }
7623 }
7624 }
John McCall263a48b2010-01-04 23:31:57 +00007625 return;
7626 }
7627
Richard Trieu5b993502014-10-15 03:42:06 +00007628 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007629
David Blaikie9366d2b2012-06-19 21:19:06 +00007630 if (!Source->isIntegerType() || !Target->isIntegerType())
7631 return;
7632
David Blaikie7555b6a2012-05-15 16:56:36 +00007633 // TODO: remove this early return once the false positives for constant->bool
7634 // in templates, macros, etc, are reduced or removed.
7635 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7636 return;
7637
John McCallcc7e5bf2010-05-06 08:58:33 +00007638 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007639 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007640
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007641 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007642 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007643 // TODO: this should happen for bitfield stores, too.
7644 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00007645 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007646 if (S.SourceMgr.isInSystemMacro(CC))
7647 return;
7648
John McCall18a2c2c2010-11-09 22:22:12 +00007649 std::string PrettySourceValue = Value.toString(10);
7650 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007651
Ted Kremenek33ba9952011-10-22 02:37:33 +00007652 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7653 S.PDiag(diag::warn_impcast_integer_precision_constant)
7654 << PrettySourceValue << PrettyTargetValue
7655 << E->getType() << T << E->getSourceRange()
7656 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007657 return;
7658 }
7659
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007660 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7661 if (S.SourceMgr.isInSystemMacro(CC))
7662 return;
7663
David Blaikie9455da02012-04-12 22:40:54 +00007664 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007665 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7666 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007667 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007668 }
7669
Richard Trieudcb55572016-01-29 23:51:16 +00007670 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
7671 SourceRange.NonNegative && Source->isSignedIntegerType()) {
7672 // Warn when doing a signed to signed conversion, warn if the positive
7673 // source value is exactly the width of the target type, which will
7674 // cause a negative value to be stored.
7675
7676 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00007677 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
7678 !S.SourceMgr.isInSystemMacro(CC)) {
7679 if (isSameWidthConstantConversion(S, E, T, CC)) {
7680 std::string PrettySourceValue = Value.toString(10);
7681 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00007682
Richard Trieufc404c72016-02-05 23:02:38 +00007683 S.DiagRuntimeBehavior(
7684 E->getExprLoc(), E,
7685 S.PDiag(diag::warn_impcast_integer_precision_constant)
7686 << PrettySourceValue << PrettyTargetValue << E->getType() << T
7687 << E->getSourceRange() << clang::SourceRange(CC));
7688 return;
Richard Trieudcb55572016-01-29 23:51:16 +00007689 }
7690 }
Richard Trieufc404c72016-02-05 23:02:38 +00007691
Richard Trieudcb55572016-01-29 23:51:16 +00007692 // Fall through for non-constants to give a sign conversion warning.
7693 }
7694
John McCallcc7e5bf2010-05-06 08:58:33 +00007695 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7696 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7697 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007698 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007699 return;
7700
John McCallcc7e5bf2010-05-06 08:58:33 +00007701 unsigned DiagID = diag::warn_impcast_integer_sign;
7702
7703 // Traditionally, gcc has warned about this under -Wsign-compare.
7704 // We also want to warn about it in -Wconversion.
7705 // So if -Wconversion is off, use a completely identical diagnostic
7706 // in the sign-compare group.
7707 // The conditional-checking code will
7708 if (ICContext) {
7709 DiagID = diag::warn_impcast_integer_sign_conditional;
7710 *ICContext = true;
7711 }
7712
John McCallacf0ee52010-10-08 02:01:28 +00007713 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007714 }
7715
Douglas Gregora78f1932011-02-22 02:45:07 +00007716 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007717 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7718 // type, to give us better diagnostics.
7719 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007720 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007721 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7722 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7723 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7724 SourceType = S.Context.getTypeDeclType(Enum);
7725 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7726 }
7727 }
7728
Douglas Gregora78f1932011-02-22 02:45:07 +00007729 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7730 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007731 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7732 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007733 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007734 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007735 return;
7736
Douglas Gregor364f7db2011-03-12 00:14:31 +00007737 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007738 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007739 }
John McCall263a48b2010-01-04 23:31:57 +00007740}
7741
David Blaikie18e9ac72012-05-15 21:57:38 +00007742void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7743 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007744
7745void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007746 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007747 E = E->IgnoreParenImpCasts();
7748
7749 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007750 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007751
John McCallacf0ee52010-10-08 02:01:28 +00007752 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007753 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007754 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007755}
7756
David Blaikie18e9ac72012-05-15 21:57:38 +00007757void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7758 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007759 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007760
7761 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007762 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7763 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007764
7765 // If -Wconversion would have warned about either of the candidates
7766 // for a signedness conversion to the context type...
7767 if (!Suspicious) return;
7768
7769 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007770 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007771 return;
7772
John McCallcc7e5bf2010-05-06 08:58:33 +00007773 // ...then check whether it would have warned about either of the
7774 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007775 if (E->getType() == T) return;
7776
7777 Suspicious = false;
7778 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7779 E->getType(), CC, &Suspicious);
7780 if (!Suspicious)
7781 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007782 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007783}
7784
Richard Trieu65724892014-11-15 06:37:39 +00007785/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7786/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007787void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00007788 if (S.getLangOpts().Bool)
7789 return;
7790 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7791}
7792
John McCallcc7e5bf2010-05-06 08:58:33 +00007793/// AnalyzeImplicitConversions - Find and report any interesting
7794/// implicit conversions in the given expression. There are a couple
7795/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007796void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007797 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007798 Expr *E = OrigE->IgnoreParenImpCasts();
7799
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007800 if (E->isTypeDependent() || E->isValueDependent())
7801 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007802
John McCallcc7e5bf2010-05-06 08:58:33 +00007803 // For conditional operators, we analyze the arguments as if they
7804 // were being fed directly into the output.
7805 if (isa<ConditionalOperator>(E)) {
7806 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007807 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007808 return;
7809 }
7810
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007811 // Check implicit argument conversions for function calls.
7812 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7813 CheckImplicitArgumentConversions(S, Call, CC);
7814
John McCallcc7e5bf2010-05-06 08:58:33 +00007815 // Go ahead and check any implicit conversions we might have skipped.
7816 // The non-canonical typecheck is just an optimization;
7817 // CheckImplicitConversion will filter out dead implicit conversions.
7818 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007819 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007820
7821 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00007822
7823 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
7824 // The bound subexpressions in a PseudoObjectExpr are not reachable
7825 // as transitive children.
7826 // FIXME: Use a more uniform representation for this.
7827 for (auto *SE : POE->semantics())
7828 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
7829 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007830 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00007831
John McCallcc7e5bf2010-05-06 08:58:33 +00007832 // Skip past explicit casts.
7833 if (isa<ExplicitCastExpr>(E)) {
7834 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007835 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007836 }
7837
John McCalld2a53122010-11-09 23:24:47 +00007838 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7839 // Do a somewhat different check with comparison operators.
7840 if (BO->isComparisonOp())
7841 return AnalyzeComparison(S, BO);
7842
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007843 // And with simple assignments.
7844 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007845 return AnalyzeAssignment(S, BO);
7846 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007847
7848 // These break the otherwise-useful invariant below. Fortunately,
7849 // we don't really need to recurse into them, because any internal
7850 // expressions should have been analyzed already when they were
7851 // built into statements.
7852 if (isa<StmtExpr>(E)) return;
7853
7854 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007855 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007856
7857 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007858 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007859 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007860 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007861 for (Stmt *SubStmt : E->children()) {
7862 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007863 if (!ChildExpr)
7864 continue;
7865
Richard Trieu955231d2014-01-25 01:10:35 +00007866 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007867 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007868 // Ignore checking string literals that are in logical and operators.
7869 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007870 continue;
7871 AnalyzeImplicitConversions(S, ChildExpr, CC);
7872 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007873
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007874 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007875 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7876 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007877 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007878
7879 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7880 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007881 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007882 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007883
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007884 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7885 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007886 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007887}
7888
7889} // end anonymous namespace
7890
Richard Trieuc1888e02014-06-28 23:25:37 +00007891// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7892// Returns true when emitting a warning about taking the address of a reference.
7893static bool CheckForReference(Sema &SemaRef, const Expr *E,
7894 PartialDiagnostic PD) {
7895 E = E->IgnoreParenImpCasts();
7896
7897 const FunctionDecl *FD = nullptr;
7898
7899 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7900 if (!DRE->getDecl()->getType()->isReferenceType())
7901 return false;
7902 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7903 if (!M->getMemberDecl()->getType()->isReferenceType())
7904 return false;
7905 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007906 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007907 return false;
7908 FD = Call->getDirectCallee();
7909 } else {
7910 return false;
7911 }
7912
7913 SemaRef.Diag(E->getExprLoc(), PD);
7914
7915 // If possible, point to location of function.
7916 if (FD) {
7917 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7918 }
7919
7920 return true;
7921}
7922
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007923// Returns true if the SourceLocation is expanded from any macro body.
7924// Returns false if the SourceLocation is invalid, is from not in a macro
7925// expansion, or is from expanded from a top-level macro argument.
7926static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7927 if (Loc.isInvalid())
7928 return false;
7929
7930 while (Loc.isMacroID()) {
7931 if (SM.isMacroBodyExpansion(Loc))
7932 return true;
7933 Loc = SM.getImmediateMacroCallerLoc(Loc);
7934 }
7935
7936 return false;
7937}
7938
Richard Trieu3bb8b562014-02-26 02:36:06 +00007939/// \brief Diagnose pointers that are always non-null.
7940/// \param E the expression containing the pointer
7941/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7942/// compared to a null pointer
7943/// \param IsEqual True when the comparison is equal to a null pointer
7944/// \param Range Extra SourceRange to highlight in the diagnostic
7945void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7946 Expr::NullPointerConstantKind NullKind,
7947 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007948 if (!E)
7949 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007950
7951 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007952 if (E->getExprLoc().isMacroID()) {
7953 const SourceManager &SM = getSourceManager();
7954 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7955 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007956 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007957 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007958 E = E->IgnoreImpCasts();
7959
7960 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7961
Richard Trieuf7432752014-06-06 21:39:26 +00007962 if (isa<CXXThisExpr>(E)) {
7963 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7964 : diag::warn_this_bool_conversion;
7965 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7966 return;
7967 }
7968
Richard Trieu3bb8b562014-02-26 02:36:06 +00007969 bool IsAddressOf = false;
7970
7971 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7972 if (UO->getOpcode() != UO_AddrOf)
7973 return;
7974 IsAddressOf = true;
7975 E = UO->getSubExpr();
7976 }
7977
Richard Trieuc1888e02014-06-28 23:25:37 +00007978 if (IsAddressOf) {
7979 unsigned DiagID = IsCompare
7980 ? diag::warn_address_of_reference_null_compare
7981 : diag::warn_address_of_reference_bool_conversion;
7982 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7983 << IsEqual;
7984 if (CheckForReference(*this, E, PD)) {
7985 return;
7986 }
7987 }
7988
George Burgess IV850269a2015-12-08 22:02:00 +00007989 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
7990 std::string Str;
7991 llvm::raw_string_ostream S(Str);
7992 E->printPretty(S, nullptr, getPrintingPolicy());
7993 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
7994 : diag::warn_cast_nonnull_to_bool;
7995 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
7996 << E->getSourceRange() << Range << IsEqual;
7997 };
7998
7999 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8000 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8001 if (auto *Callee = Call->getDirectCallee()) {
8002 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
8003 ComplainAboutNonnullParamOrCall(false);
8004 return;
8005 }
8006 }
8007 }
8008
Richard Trieu3bb8b562014-02-26 02:36:06 +00008009 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008010 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008011 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8012 D = R->getDecl();
8013 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8014 D = M->getMemberDecl();
8015 }
8016
8017 // Weak Decls can be null.
8018 if (!D || D->isWeak())
8019 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008020
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008021 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008022 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8023 if (getCurFunction() &&
8024 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8025 if (PV->hasAttr<NonNullAttr>()) {
8026 ComplainAboutNonnullParamOrCall(true);
8027 return;
8028 }
8029
8030 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8031 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
8032 assert(ParamIter != FD->param_end());
8033 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8034
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008035 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8036 if (!NonNull->args_size()) {
George Burgess IV850269a2015-12-08 22:02:00 +00008037 ComplainAboutNonnullParamOrCall(true);
8038 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008039 }
George Burgess IV850269a2015-12-08 22:02:00 +00008040
8041 for (unsigned ArgNo : NonNull->args()) {
8042 if (ArgNo == ParamNo) {
8043 ComplainAboutNonnullParamOrCall(true);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008044 return;
8045 }
George Burgess IV850269a2015-12-08 22:02:00 +00008046 }
8047 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008048 }
8049 }
George Burgess IV850269a2015-12-08 22:02:00 +00008050 }
8051
Richard Trieu3bb8b562014-02-26 02:36:06 +00008052 QualType T = D->getType();
8053 const bool IsArray = T->isArrayType();
8054 const bool IsFunction = T->isFunctionType();
8055
Richard Trieuc1888e02014-06-28 23:25:37 +00008056 // Address of function is used to silence the function warning.
8057 if (IsAddressOf && IsFunction) {
8058 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008059 }
8060
8061 // Found nothing.
8062 if (!IsAddressOf && !IsFunction && !IsArray)
8063 return;
8064
8065 // Pretty print the expression for the diagnostic.
8066 std::string Str;
8067 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008068 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008069
8070 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8071 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008072 enum {
8073 AddressOf,
8074 FunctionPointer,
8075 ArrayPointer
8076 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008077 if (IsAddressOf)
8078 DiagType = AddressOf;
8079 else if (IsFunction)
8080 DiagType = FunctionPointer;
8081 else if (IsArray)
8082 DiagType = ArrayPointer;
8083 else
8084 llvm_unreachable("Could not determine diagnostic.");
8085 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8086 << Range << IsEqual;
8087
8088 if (!IsFunction)
8089 return;
8090
8091 // Suggest '&' to silence the function warning.
8092 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8093 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8094
8095 // Check to see if '()' fixit should be emitted.
8096 QualType ReturnType;
8097 UnresolvedSet<4> NonTemplateOverloads;
8098 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8099 if (ReturnType.isNull())
8100 return;
8101
8102 if (IsCompare) {
8103 // There are two cases here. If there is null constant, the only suggest
8104 // for a pointer return type. If the null is 0, then suggest if the return
8105 // type is a pointer or an integer type.
8106 if (!ReturnType->isPointerType()) {
8107 if (NullKind == Expr::NPCK_ZeroExpression ||
8108 NullKind == Expr::NPCK_ZeroLiteral) {
8109 if (!ReturnType->isIntegerType())
8110 return;
8111 } else {
8112 return;
8113 }
8114 }
8115 } else { // !IsCompare
8116 // For function to bool, only suggest if the function pointer has bool
8117 // return type.
8118 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8119 return;
8120 }
8121 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008122 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008123}
8124
John McCallcc7e5bf2010-05-06 08:58:33 +00008125/// Diagnoses "dangerous" implicit conversions within the given
8126/// expression (which is a full expression). Implements -Wconversion
8127/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008128///
8129/// \param CC the "context" location of the implicit conversion, i.e.
8130/// the most location of the syntactic entity requiring the implicit
8131/// conversion
8132void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008133 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008134 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008135 return;
8136
8137 // Don't diagnose for value- or type-dependent expressions.
8138 if (E->isTypeDependent() || E->isValueDependent())
8139 return;
8140
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008141 // Check for array bounds violations in cases where the check isn't triggered
8142 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8143 // ArraySubscriptExpr is on the RHS of a variable initialization.
8144 CheckArrayAccess(E);
8145
John McCallacf0ee52010-10-08 02:01:28 +00008146 // This is not the right CC for (e.g.) a variable initialization.
8147 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008148}
8149
Richard Trieu65724892014-11-15 06:37:39 +00008150/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8151/// Input argument E is a logical expression.
8152void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8153 ::CheckBoolLikeConversion(*this, E, CC);
8154}
8155
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008156/// Diagnose when expression is an integer constant expression and its evaluation
8157/// results in integer overflow
8158void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008159 // Use a work list to deal with nested struct initializers.
8160 SmallVector<Expr *, 2> Exprs(1, E);
8161
8162 do {
8163 Expr *E = Exprs.pop_back_val();
8164
8165 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8166 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8167 continue;
8168 }
8169
8170 if (auto InitList = dyn_cast<InitListExpr>(E))
8171 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8172 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008173}
8174
Richard Smithc406cb72013-01-17 01:17:56 +00008175namespace {
8176/// \brief Visitor for expressions which looks for unsequenced operations on the
8177/// same object.
8178class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008179 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8180
Richard Smithc406cb72013-01-17 01:17:56 +00008181 /// \brief A tree of sequenced regions within an expression. Two regions are
8182 /// unsequenced if one is an ancestor or a descendent of the other. When we
8183 /// finish processing an expression with sequencing, such as a comma
8184 /// expression, we fold its tree nodes into its parent, since they are
8185 /// unsequenced with respect to nodes we will visit later.
8186 class SequenceTree {
8187 struct Value {
8188 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8189 unsigned Parent : 31;
8190 bool Merged : 1;
8191 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008192 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008193
8194 public:
8195 /// \brief A region within an expression which may be sequenced with respect
8196 /// to some other region.
8197 class Seq {
8198 explicit Seq(unsigned N) : Index(N) {}
8199 unsigned Index;
8200 friend class SequenceTree;
8201 public:
8202 Seq() : Index(0) {}
8203 };
8204
8205 SequenceTree() { Values.push_back(Value(0)); }
8206 Seq root() const { return Seq(0); }
8207
8208 /// \brief Create a new sequence of operations, which is an unsequenced
8209 /// subset of \p Parent. This sequence of operations is sequenced with
8210 /// respect to other children of \p Parent.
8211 Seq allocate(Seq Parent) {
8212 Values.push_back(Value(Parent.Index));
8213 return Seq(Values.size() - 1);
8214 }
8215
8216 /// \brief Merge a sequence of operations into its parent.
8217 void merge(Seq S) {
8218 Values[S.Index].Merged = true;
8219 }
8220
8221 /// \brief Determine whether two operations are unsequenced. This operation
8222 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8223 /// should have been merged into its parent as appropriate.
8224 bool isUnsequenced(Seq Cur, Seq Old) {
8225 unsigned C = representative(Cur.Index);
8226 unsigned Target = representative(Old.Index);
8227 while (C >= Target) {
8228 if (C == Target)
8229 return true;
8230 C = Values[C].Parent;
8231 }
8232 return false;
8233 }
8234
8235 private:
8236 /// \brief Pick a representative for a sequence.
8237 unsigned representative(unsigned K) {
8238 if (Values[K].Merged)
8239 // Perform path compression as we go.
8240 return Values[K].Parent = representative(Values[K].Parent);
8241 return K;
8242 }
8243 };
8244
8245 /// An object for which we can track unsequenced uses.
8246 typedef NamedDecl *Object;
8247
8248 /// Different flavors of object usage which we track. We only track the
8249 /// least-sequenced usage of each kind.
8250 enum UsageKind {
8251 /// A read of an object. Multiple unsequenced reads are OK.
8252 UK_Use,
8253 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008254 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008255 UK_ModAsValue,
8256 /// A modification of an object which is not sequenced before the value
8257 /// computation of the expression, such as n++.
8258 UK_ModAsSideEffect,
8259
8260 UK_Count = UK_ModAsSideEffect + 1
8261 };
8262
8263 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008264 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008265 Expr *Use;
8266 SequenceTree::Seq Seq;
8267 };
8268
8269 struct UsageInfo {
8270 UsageInfo() : Diagnosed(false) {}
8271 Usage Uses[UK_Count];
8272 /// Have we issued a diagnostic for this variable already?
8273 bool Diagnosed;
8274 };
8275 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8276
8277 Sema &SemaRef;
8278 /// Sequenced regions within the expression.
8279 SequenceTree Tree;
8280 /// Declaration modifications and references which we have seen.
8281 UsageInfoMap UsageMap;
8282 /// The region we are currently within.
8283 SequenceTree::Seq Region;
8284 /// Filled in with declarations which were modified as a side-effect
8285 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008286 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008287 /// Expressions to check later. We defer checking these to reduce
8288 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008289 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008290
8291 /// RAII object wrapping the visitation of a sequenced subexpression of an
8292 /// expression. At the end of this process, the side-effects of the evaluation
8293 /// become sequenced with respect to the value computation of the result, so
8294 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8295 /// UK_ModAsValue.
8296 struct SequencedSubexpression {
8297 SequencedSubexpression(SequenceChecker &Self)
8298 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8299 Self.ModAsSideEffect = &ModAsSideEffect;
8300 }
8301 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00008302 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8303 MI != ME; ++MI) {
8304 UsageInfo &U = Self.UsageMap[MI->first];
8305 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8306 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8307 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00008308 }
8309 Self.ModAsSideEffect = OldModAsSideEffect;
8310 }
8311
8312 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008313 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8314 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008315 };
8316
Richard Smith40238f02013-06-20 22:21:56 +00008317 /// RAII object wrapping the visitation of a subexpression which we might
8318 /// choose to evaluate as a constant. If any subexpression is evaluated and
8319 /// found to be non-constant, this allows us to suppress the evaluation of
8320 /// the outer expression.
8321 class EvaluationTracker {
8322 public:
8323 EvaluationTracker(SequenceChecker &Self)
8324 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8325 Self.EvalTracker = this;
8326 }
8327 ~EvaluationTracker() {
8328 Self.EvalTracker = Prev;
8329 if (Prev)
8330 Prev->EvalOK &= EvalOK;
8331 }
8332
8333 bool evaluate(const Expr *E, bool &Result) {
8334 if (!EvalOK || E->isValueDependent())
8335 return false;
8336 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8337 return EvalOK;
8338 }
8339
8340 private:
8341 SequenceChecker &Self;
8342 EvaluationTracker *Prev;
8343 bool EvalOK;
8344 } *EvalTracker;
8345
Richard Smithc406cb72013-01-17 01:17:56 +00008346 /// \brief Find the object which is produced by the specified expression,
8347 /// if any.
8348 Object getObject(Expr *E, bool Mod) const {
8349 E = E->IgnoreParenCasts();
8350 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8351 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8352 return getObject(UO->getSubExpr(), Mod);
8353 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8354 if (BO->getOpcode() == BO_Comma)
8355 return getObject(BO->getRHS(), Mod);
8356 if (Mod && BO->isAssignmentOp())
8357 return getObject(BO->getLHS(), Mod);
8358 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8359 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8360 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8361 return ME->getMemberDecl();
8362 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8363 // FIXME: If this is a reference, map through to its value.
8364 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008365 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008366 }
8367
8368 /// \brief Note that an object was modified or used by an expression.
8369 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8370 Usage &U = UI.Uses[UK];
8371 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8372 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8373 ModAsSideEffect->push_back(std::make_pair(O, U));
8374 U.Use = Ref;
8375 U.Seq = Region;
8376 }
8377 }
8378 /// \brief Check whether a modification or use conflicts with a prior usage.
8379 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8380 bool IsModMod) {
8381 if (UI.Diagnosed)
8382 return;
8383
8384 const Usage &U = UI.Uses[OtherKind];
8385 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8386 return;
8387
8388 Expr *Mod = U.Use;
8389 Expr *ModOrUse = Ref;
8390 if (OtherKind == UK_Use)
8391 std::swap(Mod, ModOrUse);
8392
8393 SemaRef.Diag(Mod->getExprLoc(),
8394 IsModMod ? diag::warn_unsequenced_mod_mod
8395 : diag::warn_unsequenced_mod_use)
8396 << O << SourceRange(ModOrUse->getExprLoc());
8397 UI.Diagnosed = true;
8398 }
8399
8400 void notePreUse(Object O, Expr *Use) {
8401 UsageInfo &U = UsageMap[O];
8402 // Uses conflict with other modifications.
8403 checkUsage(O, U, Use, UK_ModAsValue, false);
8404 }
8405 void notePostUse(Object O, Expr *Use) {
8406 UsageInfo &U = UsageMap[O];
8407 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8408 addUsage(U, O, Use, UK_Use);
8409 }
8410
8411 void notePreMod(Object O, Expr *Mod) {
8412 UsageInfo &U = UsageMap[O];
8413 // Modifications conflict with other modifications and with uses.
8414 checkUsage(O, U, Mod, UK_ModAsValue, true);
8415 checkUsage(O, U, Mod, UK_Use, false);
8416 }
8417 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8418 UsageInfo &U = UsageMap[O];
8419 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8420 addUsage(U, O, Use, UK);
8421 }
8422
8423public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008424 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008425 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8426 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008427 Visit(E);
8428 }
8429
8430 void VisitStmt(Stmt *S) {
8431 // Skip all statements which aren't expressions for now.
8432 }
8433
8434 void VisitExpr(Expr *E) {
8435 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008436 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008437 }
8438
8439 void VisitCastExpr(CastExpr *E) {
8440 Object O = Object();
8441 if (E->getCastKind() == CK_LValueToRValue)
8442 O = getObject(E->getSubExpr(), false);
8443
8444 if (O)
8445 notePreUse(O, E);
8446 VisitExpr(E);
8447 if (O)
8448 notePostUse(O, E);
8449 }
8450
8451 void VisitBinComma(BinaryOperator *BO) {
8452 // C++11 [expr.comma]p1:
8453 // Every value computation and side effect associated with the left
8454 // expression is sequenced before every value computation and side
8455 // effect associated with the right expression.
8456 SequenceTree::Seq LHS = Tree.allocate(Region);
8457 SequenceTree::Seq RHS = Tree.allocate(Region);
8458 SequenceTree::Seq OldRegion = Region;
8459
8460 {
8461 SequencedSubexpression SeqLHS(*this);
8462 Region = LHS;
8463 Visit(BO->getLHS());
8464 }
8465
8466 Region = RHS;
8467 Visit(BO->getRHS());
8468
8469 Region = OldRegion;
8470
8471 // Forget that LHS and RHS are sequenced. They are both unsequenced
8472 // with respect to other stuff.
8473 Tree.merge(LHS);
8474 Tree.merge(RHS);
8475 }
8476
8477 void VisitBinAssign(BinaryOperator *BO) {
8478 // The modification is sequenced after the value computation of the LHS
8479 // and RHS, so check it before inspecting the operands and update the
8480 // map afterwards.
8481 Object O = getObject(BO->getLHS(), true);
8482 if (!O)
8483 return VisitExpr(BO);
8484
8485 notePreMod(O, BO);
8486
8487 // C++11 [expr.ass]p7:
8488 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8489 // only once.
8490 //
8491 // Therefore, for a compound assignment operator, O is considered used
8492 // everywhere except within the evaluation of E1 itself.
8493 if (isa<CompoundAssignOperator>(BO))
8494 notePreUse(O, BO);
8495
8496 Visit(BO->getLHS());
8497
8498 if (isa<CompoundAssignOperator>(BO))
8499 notePostUse(O, BO);
8500
8501 Visit(BO->getRHS());
8502
Richard Smith83e37bee2013-06-26 23:16:51 +00008503 // C++11 [expr.ass]p1:
8504 // the assignment is sequenced [...] before the value computation of the
8505 // assignment expression.
8506 // C11 6.5.16/3 has no such rule.
8507 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8508 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008509 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008510
Richard Smithc406cb72013-01-17 01:17:56 +00008511 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8512 VisitBinAssign(CAO);
8513 }
8514
8515 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8516 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8517 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8518 Object O = getObject(UO->getSubExpr(), true);
8519 if (!O)
8520 return VisitExpr(UO);
8521
8522 notePreMod(O, UO);
8523 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008524 // C++11 [expr.pre.incr]p1:
8525 // the expression ++x is equivalent to x+=1
8526 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8527 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008528 }
8529
8530 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8531 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8532 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8533 Object O = getObject(UO->getSubExpr(), true);
8534 if (!O)
8535 return VisitExpr(UO);
8536
8537 notePreMod(O, UO);
8538 Visit(UO->getSubExpr());
8539 notePostMod(O, UO, UK_ModAsSideEffect);
8540 }
8541
8542 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8543 void VisitBinLOr(BinaryOperator *BO) {
8544 // The side-effects of the LHS of an '&&' are sequenced before the
8545 // value computation of the RHS, and hence before the value computation
8546 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8547 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008548 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008549 {
8550 SequencedSubexpression Sequenced(*this);
8551 Visit(BO->getLHS());
8552 }
8553
8554 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008555 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008556 if (!Result)
8557 Visit(BO->getRHS());
8558 } else {
8559 // Check for unsequenced operations in the RHS, treating it as an
8560 // entirely separate evaluation.
8561 //
8562 // FIXME: If there are operations in the RHS which are unsequenced
8563 // with respect to operations outside the RHS, and those operations
8564 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008565 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008566 }
Richard Smithc406cb72013-01-17 01:17:56 +00008567 }
8568 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008569 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008570 {
8571 SequencedSubexpression Sequenced(*this);
8572 Visit(BO->getLHS());
8573 }
8574
8575 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008576 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008577 if (Result)
8578 Visit(BO->getRHS());
8579 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008580 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008581 }
Richard Smithc406cb72013-01-17 01:17:56 +00008582 }
8583
8584 // Only visit the condition, unless we can be sure which subexpression will
8585 // be chosen.
8586 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008587 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008588 {
8589 SequencedSubexpression Sequenced(*this);
8590 Visit(CO->getCond());
8591 }
Richard Smithc406cb72013-01-17 01:17:56 +00008592
8593 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008594 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008595 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008596 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008597 WorkList.push_back(CO->getTrueExpr());
8598 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008599 }
Richard Smithc406cb72013-01-17 01:17:56 +00008600 }
8601
Richard Smithe3dbfe02013-06-30 10:40:20 +00008602 void VisitCallExpr(CallExpr *CE) {
8603 // C++11 [intro.execution]p15:
8604 // When calling a function [...], every value computation and side effect
8605 // associated with any argument expression, or with the postfix expression
8606 // designating the called function, is sequenced before execution of every
8607 // expression or statement in the body of the function [and thus before
8608 // the value computation of its result].
8609 SequencedSubexpression Sequenced(*this);
8610 Base::VisitCallExpr(CE);
8611
8612 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8613 }
8614
Richard Smithc406cb72013-01-17 01:17:56 +00008615 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008616 // This is a call, so all subexpressions are sequenced before the result.
8617 SequencedSubexpression Sequenced(*this);
8618
Richard Smithc406cb72013-01-17 01:17:56 +00008619 if (!CCE->isListInitialization())
8620 return VisitExpr(CCE);
8621
8622 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008623 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008624 SequenceTree::Seq Parent = Region;
8625 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8626 E = CCE->arg_end();
8627 I != E; ++I) {
8628 Region = Tree.allocate(Parent);
8629 Elts.push_back(Region);
8630 Visit(*I);
8631 }
8632
8633 // Forget that the initializers are sequenced.
8634 Region = Parent;
8635 for (unsigned I = 0; I < Elts.size(); ++I)
8636 Tree.merge(Elts[I]);
8637 }
8638
8639 void VisitInitListExpr(InitListExpr *ILE) {
8640 if (!SemaRef.getLangOpts().CPlusPlus11)
8641 return VisitExpr(ILE);
8642
8643 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008644 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008645 SequenceTree::Seq Parent = Region;
8646 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8647 Expr *E = ILE->getInit(I);
8648 if (!E) continue;
8649 Region = Tree.allocate(Parent);
8650 Elts.push_back(Region);
8651 Visit(E);
8652 }
8653
8654 // Forget that the initializers are sequenced.
8655 Region = Parent;
8656 for (unsigned I = 0; I < Elts.size(); ++I)
8657 Tree.merge(Elts[I]);
8658 }
8659};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008660} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00008661
8662void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008663 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008664 WorkList.push_back(E);
8665 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008666 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008667 SequenceChecker(*this, Item, WorkList);
8668 }
Richard Smithc406cb72013-01-17 01:17:56 +00008669}
8670
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008671void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8672 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008673 CheckImplicitConversions(E, CheckLoc);
8674 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008675 if (!IsConstexpr && !E->isValueDependent())
8676 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008677}
8678
John McCall1f425642010-11-11 03:21:53 +00008679void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8680 FieldDecl *BitField,
8681 Expr *Init) {
8682 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8683}
8684
David Majnemer61a5bbf2015-04-07 22:08:51 +00008685static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8686 SourceLocation Loc) {
8687 if (!PType->isVariablyModifiedType())
8688 return;
8689 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8690 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8691 return;
8692 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008693 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8694 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8695 return;
8696 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008697 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8698 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8699 return;
8700 }
8701
8702 const ArrayType *AT = S.Context.getAsArrayType(PType);
8703 if (!AT)
8704 return;
8705
8706 if (AT->getSizeModifier() != ArrayType::Star) {
8707 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8708 return;
8709 }
8710
8711 S.Diag(Loc, diag::err_array_star_in_function_definition);
8712}
8713
Mike Stump0c2ec772010-01-21 03:59:47 +00008714/// CheckParmsForFunctionDef - Check that the parameters of the given
8715/// function are appropriate for the definition of a function. This
8716/// takes care of any checks that cannot be performed on the
8717/// declaration itself, e.g., that the types of each of the function
8718/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008719bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8720 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008721 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008722 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008723 for (; P != PEnd; ++P) {
8724 ParmVarDecl *Param = *P;
8725
Mike Stump0c2ec772010-01-21 03:59:47 +00008726 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8727 // function declarator that is part of a function definition of
8728 // that function shall not have incomplete type.
8729 //
8730 // This is also C++ [dcl.fct]p6.
8731 if (!Param->isInvalidDecl() &&
8732 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008733 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008734 Param->setInvalidDecl();
8735 HasInvalidParm = true;
8736 }
8737
8738 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8739 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008740 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008741 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008742 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008743 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008744 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008745
8746 // C99 6.7.5.3p12:
8747 // If the function declarator is not part of a definition of that
8748 // function, parameters may have incomplete type and may use the [*]
8749 // notation in their sequences of declarator specifiers to specify
8750 // variable length array types.
8751 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008752 // FIXME: This diagnostic should point the '[*]' if source-location
8753 // information is added for it.
8754 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008755
8756 // MSVC destroys objects passed by value in the callee. Therefore a
8757 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008758 // object's destructor. However, we don't perform any direct access check
8759 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008760 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8761 .getCXXABI()
8762 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008763 if (!Param->isInvalidDecl()) {
8764 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8765 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8766 if (!ClassDecl->isInvalidDecl() &&
8767 !ClassDecl->hasIrrelevantDestructor() &&
8768 !ClassDecl->isDependentContext()) {
8769 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8770 MarkFunctionReferenced(Param->getLocation(), Destructor);
8771 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8772 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008773 }
8774 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008775 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008776
8777 // Parameters with the pass_object_size attribute only need to be marked
8778 // constant at function definitions. Because we lack information about
8779 // whether we're on a declaration or definition when we're instantiating the
8780 // attribute, we need to check for constness here.
8781 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
8782 if (!Param->getType().isConstQualified())
8783 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
8784 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00008785 }
8786
8787 return HasInvalidParm;
8788}
John McCall2b5c1b22010-08-12 21:44:57 +00008789
8790/// CheckCastAlign - Implements -Wcast-align, which warns when a
8791/// pointer cast increases the alignment requirements.
8792void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8793 // This is actually a lot of work to potentially be doing on every
8794 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008795 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008796 return;
8797
8798 // Ignore dependent types.
8799 if (T->isDependentType() || Op->getType()->isDependentType())
8800 return;
8801
8802 // Require that the destination be a pointer type.
8803 const PointerType *DestPtr = T->getAs<PointerType>();
8804 if (!DestPtr) return;
8805
8806 // If the destination has alignment 1, we're done.
8807 QualType DestPointee = DestPtr->getPointeeType();
8808 if (DestPointee->isIncompleteType()) return;
8809 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8810 if (DestAlign.isOne()) return;
8811
8812 // Require that the source be a pointer type.
8813 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8814 if (!SrcPtr) return;
8815 QualType SrcPointee = SrcPtr->getPointeeType();
8816
8817 // Whitelist casts from cv void*. We already implicitly
8818 // whitelisted casts to cv void*, since they have alignment 1.
8819 // Also whitelist casts involving incomplete types, which implicitly
8820 // includes 'void'.
8821 if (SrcPointee->isIncompleteType()) return;
8822
8823 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8824 if (SrcAlign >= DestAlign) return;
8825
8826 Diag(TRange.getBegin(), diag::warn_cast_align)
8827 << Op->getType() << T
8828 << static_cast<unsigned>(SrcAlign.getQuantity())
8829 << static_cast<unsigned>(DestAlign.getQuantity())
8830 << TRange << Op->getSourceRange();
8831}
8832
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008833static const Type* getElementType(const Expr *BaseExpr) {
8834 const Type* EltType = BaseExpr->getType().getTypePtr();
8835 if (EltType->isAnyPointerType())
8836 return EltType->getPointeeType().getTypePtr();
8837 else if (EltType->isArrayType())
8838 return EltType->getBaseElementTypeUnsafe();
8839 return EltType;
8840}
8841
Chandler Carruth28389f02011-08-05 09:10:50 +00008842/// \brief Check whether this array fits the idiom of a size-one tail padded
8843/// array member of a struct.
8844///
8845/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8846/// commonly used to emulate flexible arrays in C89 code.
8847static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8848 const NamedDecl *ND) {
8849 if (Size != 1 || !ND) return false;
8850
8851 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8852 if (!FD) return false;
8853
8854 // Don't consider sizes resulting from macro expansions or template argument
8855 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008856
8857 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008858 while (TInfo) {
8859 TypeLoc TL = TInfo->getTypeLoc();
8860 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008861 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8862 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008863 TInfo = TDL->getTypeSourceInfo();
8864 continue;
8865 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008866 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8867 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008868 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8869 return false;
8870 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008871 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008872 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008873
8874 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008875 if (!RD) return false;
8876 if (RD->isUnion()) return false;
8877 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8878 if (!CRD->isStandardLayout()) return false;
8879 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008880
Benjamin Kramer8c543672011-08-06 03:04:42 +00008881 // See if this is the last field decl in the record.
8882 const Decl *D = FD;
8883 while ((D = D->getNextDeclInContext()))
8884 if (isa<FieldDecl>(D))
8885 return false;
8886 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008887}
8888
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008889void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008890 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00008891 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008892 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008893 if (IndexExpr->isValueDependent())
8894 return;
8895
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00008896 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008897 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008898 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008899 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008900 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00008901 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00008902
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008903 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00008904 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00008905 return;
Richard Smith13f67182011-12-16 19:31:14 +00008906 if (IndexNegated)
8907 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00008908
Craig Topperc3ec1492014-05-26 06:22:03 +00008909 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00008910 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8911 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00008912 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00008913 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00008914
Ted Kremeneke4b316c2011-02-23 23:06:04 +00008915 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008916 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008917 if (!size.isStrictlyPositive())
8918 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008919
8920 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008921 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008922 // Make sure we're comparing apples to apples when comparing index to size
8923 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8924 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008925 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008926 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008927 if (ptrarith_typesize != array_typesize) {
8928 // There's a cast to a different size type involved
8929 uint64_t ratio = array_typesize / ptrarith_typesize;
8930 // TODO: Be smarter about handling cases where array_typesize is not a
8931 // multiple of ptrarith_typesize
8932 if (ptrarith_typesize * ratio == array_typesize)
8933 size *= llvm::APInt(size.getBitWidth(), ratio);
8934 }
8935 }
8936
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008937 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008938 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008939 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008940 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008941
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008942 // For array subscripting the index must be less than size, but for pointer
8943 // arithmetic also allow the index (offset) to be equal to size since
8944 // computing the next address after the end of the array is legal and
8945 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008946 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008947 return;
8948
8949 // Also don't warn for arrays of size 1 which are members of some
8950 // structure. These are often used to approximate flexible arrays in C89
8951 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008952 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008953 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008954
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008955 // Suppress the warning if the subscript expression (as identified by the
8956 // ']' location) and the index expression are both from macro expansions
8957 // within a system header.
8958 if (ASE) {
8959 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8960 ASE->getRBracketLoc());
8961 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8962 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8963 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008964 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008965 return;
8966 }
8967 }
8968
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008969 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008970 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008971 DiagID = diag::warn_array_index_exceeds_bounds;
8972
8973 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8974 PDiag(DiagID) << index.toString(10, true)
8975 << size.toString(10, true)
8976 << (unsigned)size.getLimitedValue(~0U)
8977 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008978 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008979 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008980 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008981 DiagID = diag::warn_ptr_arith_precedes_bounds;
8982 if (index.isNegative()) index = -index;
8983 }
8984
8985 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8986 PDiag(DiagID) << index.toString(10, true)
8987 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008988 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008989
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008990 if (!ND) {
8991 // Try harder to find a NamedDecl to point at in the note.
8992 while (const ArraySubscriptExpr *ASE =
8993 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8994 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8995 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8996 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8997 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8998 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8999 }
9000
Chandler Carruth1af88f12011-02-17 21:10:52 +00009001 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009002 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9003 PDiag(diag::note_array_index_out_of_bounds)
9004 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009005}
9006
Ted Kremenekdf26df72011-03-01 18:41:00 +00009007void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009008 int AllowOnePastEnd = 0;
9009 while (expr) {
9010 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009011 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009012 case Stmt::ArraySubscriptExprClass: {
9013 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009014 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009015 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009016 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009017 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009018 case Stmt::OMPArraySectionExprClass: {
9019 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9020 if (ASE->getLowerBound())
9021 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9022 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9023 return;
9024 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009025 case Stmt::UnaryOperatorClass: {
9026 // Only unwrap the * and & unary operators
9027 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9028 expr = UO->getSubExpr();
9029 switch (UO->getOpcode()) {
9030 case UO_AddrOf:
9031 AllowOnePastEnd++;
9032 break;
9033 case UO_Deref:
9034 AllowOnePastEnd--;
9035 break;
9036 default:
9037 return;
9038 }
9039 break;
9040 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009041 case Stmt::ConditionalOperatorClass: {
9042 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9043 if (const Expr *lhs = cond->getLHS())
9044 CheckArrayAccess(lhs);
9045 if (const Expr *rhs = cond->getRHS())
9046 CheckArrayAccess(rhs);
9047 return;
9048 }
9049 default:
9050 return;
9051 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009052 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009053}
John McCall31168b02011-06-15 23:02:42 +00009054
9055//===--- CHECK: Objective-C retain cycles ----------------------------------//
9056
9057namespace {
9058 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009059 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009060 VarDecl *Variable;
9061 SourceRange Range;
9062 SourceLocation Loc;
9063 bool Indirect;
9064
9065 void setLocsFrom(Expr *e) {
9066 Loc = e->getExprLoc();
9067 Range = e->getSourceRange();
9068 }
9069 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009070} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009071
9072/// Consider whether capturing the given variable can possibly lead to
9073/// a retain cycle.
9074static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009075 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009076 // lifetime. In MRR, it's captured strongly if the variable is
9077 // __block and has an appropriate type.
9078 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9079 return false;
9080
9081 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009082 if (ref)
9083 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009084 return true;
9085}
9086
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009087static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009088 while (true) {
9089 e = e->IgnoreParens();
9090 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9091 switch (cast->getCastKind()) {
9092 case CK_BitCast:
9093 case CK_LValueBitCast:
9094 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009095 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009096 e = cast->getSubExpr();
9097 continue;
9098
John McCall31168b02011-06-15 23:02:42 +00009099 default:
9100 return false;
9101 }
9102 }
9103
9104 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9105 ObjCIvarDecl *ivar = ref->getDecl();
9106 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9107 return false;
9108
9109 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009110 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009111 return false;
9112
9113 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9114 owner.Indirect = true;
9115 return true;
9116 }
9117
9118 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9119 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9120 if (!var) return false;
9121 return considerVariable(var, ref, owner);
9122 }
9123
John McCall31168b02011-06-15 23:02:42 +00009124 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9125 if (member->isArrow()) return false;
9126
9127 // Don't count this as an indirect ownership.
9128 e = member->getBase();
9129 continue;
9130 }
9131
John McCallfe96e0b2011-11-06 09:01:30 +00009132 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9133 // Only pay attention to pseudo-objects on property references.
9134 ObjCPropertyRefExpr *pre
9135 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9136 ->IgnoreParens());
9137 if (!pre) return false;
9138 if (pre->isImplicitProperty()) return false;
9139 ObjCPropertyDecl *property = pre->getExplicitProperty();
9140 if (!property->isRetaining() &&
9141 !(property->getPropertyIvarDecl() &&
9142 property->getPropertyIvarDecl()->getType()
9143 .getObjCLifetime() == Qualifiers::OCL_Strong))
9144 return false;
9145
9146 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009147 if (pre->isSuperReceiver()) {
9148 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9149 if (!owner.Variable)
9150 return false;
9151 owner.Loc = pre->getLocation();
9152 owner.Range = pre->getSourceRange();
9153 return true;
9154 }
John McCallfe96e0b2011-11-06 09:01:30 +00009155 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9156 ->getSourceExpr());
9157 continue;
9158 }
9159
John McCall31168b02011-06-15 23:02:42 +00009160 // Array ivars?
9161
9162 return false;
9163 }
9164}
9165
9166namespace {
9167 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9168 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9169 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009170 Context(Context), Variable(variable), Capturer(nullptr),
9171 VarWillBeReased(false) {}
9172 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009173 VarDecl *Variable;
9174 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009175 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009176
9177 void VisitDeclRefExpr(DeclRefExpr *ref) {
9178 if (ref->getDecl() == Variable && !Capturer)
9179 Capturer = ref;
9180 }
9181
John McCall31168b02011-06-15 23:02:42 +00009182 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9183 if (Capturer) return;
9184 Visit(ref->getBase());
9185 if (Capturer && ref->isFreeIvar())
9186 Capturer = ref;
9187 }
9188
9189 void VisitBlockExpr(BlockExpr *block) {
9190 // Look inside nested blocks
9191 if (block->getBlockDecl()->capturesVariable(Variable))
9192 Visit(block->getBlockDecl()->getBody());
9193 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009194
9195 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9196 if (Capturer) return;
9197 if (OVE->getSourceExpr())
9198 Visit(OVE->getSourceExpr());
9199 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009200 void VisitBinaryOperator(BinaryOperator *BinOp) {
9201 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9202 return;
9203 Expr *LHS = BinOp->getLHS();
9204 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9205 if (DRE->getDecl() != Variable)
9206 return;
9207 if (Expr *RHS = BinOp->getRHS()) {
9208 RHS = RHS->IgnoreParenCasts();
9209 llvm::APSInt Value;
9210 VarWillBeReased =
9211 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9212 }
9213 }
9214 }
John McCall31168b02011-06-15 23:02:42 +00009215 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009216} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009217
9218/// Check whether the given argument is a block which captures a
9219/// variable.
9220static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9221 assert(owner.Variable && owner.Loc.isValid());
9222
9223 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009224
9225 // Look through [^{...} copy] and Block_copy(^{...}).
9226 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9227 Selector Cmd = ME->getSelector();
9228 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9229 e = ME->getInstanceReceiver();
9230 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009231 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009232 e = e->IgnoreParenCasts();
9233 }
9234 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9235 if (CE->getNumArgs() == 1) {
9236 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009237 if (Fn) {
9238 const IdentifierInfo *FnI = Fn->getIdentifier();
9239 if (FnI && FnI->isStr("_Block_copy")) {
9240 e = CE->getArg(0)->IgnoreParenCasts();
9241 }
9242 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009243 }
9244 }
9245
John McCall31168b02011-06-15 23:02:42 +00009246 BlockExpr *block = dyn_cast<BlockExpr>(e);
9247 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009248 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009249
9250 FindCaptureVisitor visitor(S.Context, owner.Variable);
9251 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009252 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009253}
9254
9255static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9256 RetainCycleOwner &owner) {
9257 assert(capturer);
9258 assert(owner.Variable && owner.Loc.isValid());
9259
9260 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9261 << owner.Variable << capturer->getSourceRange();
9262 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9263 << owner.Indirect << owner.Range;
9264}
9265
9266/// Check for a keyword selector that starts with the word 'add' or
9267/// 'set'.
9268static bool isSetterLikeSelector(Selector sel) {
9269 if (sel.isUnarySelector()) return false;
9270
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009271 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009272 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009273 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009274 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009275 else if (str.startswith("add")) {
9276 // Specially whitelist 'addOperationWithBlock:'.
9277 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9278 return false;
9279 str = str.substr(3);
9280 }
John McCall31168b02011-06-15 23:02:42 +00009281 else
9282 return false;
9283
9284 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009285 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009286}
9287
Benjamin Kramer3a743452015-03-09 15:03:32 +00009288static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9289 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009290 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9291 Message->getReceiverInterface(),
9292 NSAPI::ClassId_NSMutableArray);
9293 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009294 return None;
9295 }
9296
9297 Selector Sel = Message->getSelector();
9298
9299 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9300 S.NSAPIObj->getNSArrayMethodKind(Sel);
9301 if (!MKOpt) {
9302 return None;
9303 }
9304
9305 NSAPI::NSArrayMethodKind MK = *MKOpt;
9306
9307 switch (MK) {
9308 case NSAPI::NSMutableArr_addObject:
9309 case NSAPI::NSMutableArr_insertObjectAtIndex:
9310 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9311 return 0;
9312 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9313 return 1;
9314
9315 default:
9316 return None;
9317 }
9318
9319 return None;
9320}
9321
9322static
9323Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9324 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009325 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9326 Message->getReceiverInterface(),
9327 NSAPI::ClassId_NSMutableDictionary);
9328 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009329 return None;
9330 }
9331
9332 Selector Sel = Message->getSelector();
9333
9334 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9335 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9336 if (!MKOpt) {
9337 return None;
9338 }
9339
9340 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9341
9342 switch (MK) {
9343 case NSAPI::NSMutableDict_setObjectForKey:
9344 case NSAPI::NSMutableDict_setValueForKey:
9345 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9346 return 0;
9347
9348 default:
9349 return None;
9350 }
9351
9352 return None;
9353}
9354
9355static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009356 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9357 Message->getReceiverInterface(),
9358 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009359
Alex Denisov5dfac812015-08-06 04:51:14 +00009360 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9361 Message->getReceiverInterface(),
9362 NSAPI::ClassId_NSMutableOrderedSet);
9363 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009364 return None;
9365 }
9366
9367 Selector Sel = Message->getSelector();
9368
9369 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9370 if (!MKOpt) {
9371 return None;
9372 }
9373
9374 NSAPI::NSSetMethodKind MK = *MKOpt;
9375
9376 switch (MK) {
9377 case NSAPI::NSMutableSet_addObject:
9378 case NSAPI::NSOrderedSet_setObjectAtIndex:
9379 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9380 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9381 return 0;
9382 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9383 return 1;
9384 }
9385
9386 return None;
9387}
9388
9389void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9390 if (!Message->isInstanceMessage()) {
9391 return;
9392 }
9393
9394 Optional<int> ArgOpt;
9395
9396 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9397 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9398 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9399 return;
9400 }
9401
9402 int ArgIndex = *ArgOpt;
9403
Alex Denisove1d882c2015-03-04 17:55:52 +00009404 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9405 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9406 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9407 }
9408
Alex Denisov5dfac812015-08-06 04:51:14 +00009409 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009410 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009411 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009412 Diag(Message->getSourceRange().getBegin(),
9413 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009414 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009415 }
9416 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009417 } else {
9418 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9419
9420 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9421 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9422 }
9423
9424 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9425 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9426 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9427 ValueDecl *Decl = ReceiverRE->getDecl();
9428 Diag(Message->getSourceRange().getBegin(),
9429 diag::warn_objc_circular_container)
9430 << Decl->getName() << Decl->getName();
9431 if (!ArgRE->isObjCSelfExpr()) {
9432 Diag(Decl->getLocation(),
9433 diag::note_objc_circular_container_declared_here)
9434 << Decl->getName();
9435 }
9436 }
9437 }
9438 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9439 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9440 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9441 ObjCIvarDecl *Decl = IvarRE->getDecl();
9442 Diag(Message->getSourceRange().getBegin(),
9443 diag::warn_objc_circular_container)
9444 << Decl->getName() << Decl->getName();
9445 Diag(Decl->getLocation(),
9446 diag::note_objc_circular_container_declared_here)
9447 << Decl->getName();
9448 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009449 }
9450 }
9451 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009452}
9453
John McCall31168b02011-06-15 23:02:42 +00009454/// Check a message send to see if it's likely to cause a retain cycle.
9455void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9456 // Only check instance methods whose selector looks like a setter.
9457 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9458 return;
9459
9460 // Try to find a variable that the receiver is strongly owned by.
9461 RetainCycleOwner owner;
9462 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009463 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009464 return;
9465 } else {
9466 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9467 owner.Variable = getCurMethodDecl()->getSelfDecl();
9468 owner.Loc = msg->getSuperLoc();
9469 owner.Range = msg->getSuperLoc();
9470 }
9471
9472 // Check whether the receiver is captured by any of the arguments.
9473 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9474 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9475 return diagnoseRetainCycle(*this, capturer, owner);
9476}
9477
9478/// Check a property assign to see if it's likely to cause a retain cycle.
9479void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9480 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009481 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009482 return;
9483
9484 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9485 diagnoseRetainCycle(*this, capturer, owner);
9486}
9487
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009488void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9489 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009490 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009491 return;
9492
9493 // Because we don't have an expression for the variable, we have to set the
9494 // location explicitly here.
9495 Owner.Loc = Var->getLocation();
9496 Owner.Range = Var->getSourceRange();
9497
9498 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9499 diagnoseRetainCycle(*this, Capturer, Owner);
9500}
9501
Ted Kremenek9304da92012-12-21 08:04:28 +00009502static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9503 Expr *RHS, bool isProperty) {
9504 // Check if RHS is an Objective-C object literal, which also can get
9505 // immediately zapped in a weak reference. Note that we explicitly
9506 // allow ObjCStringLiterals, since those are designed to never really die.
9507 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009508
Ted Kremenek64873352012-12-21 22:46:35 +00009509 // This enum needs to match with the 'select' in
9510 // warn_objc_arc_literal_assign (off-by-1).
9511 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9512 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9513 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009514
9515 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009516 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009517 << (isProperty ? 0 : 1)
9518 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009519
9520 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009521}
9522
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009523static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9524 Qualifiers::ObjCLifetime LT,
9525 Expr *RHS, bool isProperty) {
9526 // Strip off any implicit cast added to get to the one ARC-specific.
9527 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9528 if (cast->getCastKind() == CK_ARCConsumeObject) {
9529 S.Diag(Loc, diag::warn_arc_retained_assign)
9530 << (LT == Qualifiers::OCL_ExplicitNone)
9531 << (isProperty ? 0 : 1)
9532 << RHS->getSourceRange();
9533 return true;
9534 }
9535 RHS = cast->getSubExpr();
9536 }
9537
9538 if (LT == Qualifiers::OCL_Weak &&
9539 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9540 return true;
9541
9542 return false;
9543}
9544
Ted Kremenekb36234d2012-12-21 08:04:20 +00009545bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9546 QualType LHS, Expr *RHS) {
9547 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9548
9549 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9550 return false;
9551
9552 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9553 return true;
9554
9555 return false;
9556}
9557
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009558void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9559 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009560 QualType LHSType;
9561 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009562 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009563 ObjCPropertyRefExpr *PRE
9564 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9565 if (PRE && !PRE->isImplicitProperty()) {
9566 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9567 if (PD)
9568 LHSType = PD->getType();
9569 }
9570
9571 if (LHSType.isNull())
9572 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009573
9574 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9575
9576 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009577 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009578 getCurFunction()->markSafeWeakUse(LHS);
9579 }
9580
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009581 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9582 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009583
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009584 // FIXME. Check for other life times.
9585 if (LT != Qualifiers::OCL_None)
9586 return;
9587
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009588 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009589 if (PRE->isImplicitProperty())
9590 return;
9591 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9592 if (!PD)
9593 return;
9594
Bill Wendling44426052012-12-20 19:22:21 +00009595 unsigned Attributes = PD->getPropertyAttributes();
9596 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009597 // when 'assign' attribute was not explicitly specified
9598 // by user, ignore it and rely on property type itself
9599 // for lifetime info.
9600 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9601 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9602 LHSType->isObjCRetainableType())
9603 return;
9604
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009605 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009606 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009607 Diag(Loc, diag::warn_arc_retained_property_assign)
9608 << RHS->getSourceRange();
9609 return;
9610 }
9611 RHS = cast->getSubExpr();
9612 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009613 }
Bill Wendling44426052012-12-20 19:22:21 +00009614 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009615 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9616 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009617 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009618 }
9619}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009620
9621//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9622
9623namespace {
9624bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9625 SourceLocation StmtLoc,
9626 const NullStmt *Body) {
9627 // Do not warn if the body is a macro that expands to nothing, e.g:
9628 //
9629 // #define CALL(x)
9630 // if (condition)
9631 // CALL(0);
9632 //
9633 if (Body->hasLeadingEmptyMacro())
9634 return false;
9635
9636 // Get line numbers of statement and body.
9637 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009638 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009639 &StmtLineInvalid);
9640 if (StmtLineInvalid)
9641 return false;
9642
9643 bool BodyLineInvalid;
9644 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9645 &BodyLineInvalid);
9646 if (BodyLineInvalid)
9647 return false;
9648
9649 // Warn if null statement and body are on the same line.
9650 if (StmtLine != BodyLine)
9651 return false;
9652
9653 return true;
9654}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009655} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009656
9657void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9658 const Stmt *Body,
9659 unsigned DiagID) {
9660 // Since this is a syntactic check, don't emit diagnostic for template
9661 // instantiations, this just adds noise.
9662 if (CurrentInstantiationScope)
9663 return;
9664
9665 // The body should be a null statement.
9666 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9667 if (!NBody)
9668 return;
9669
9670 // Do the usual checks.
9671 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9672 return;
9673
9674 Diag(NBody->getSemiLoc(), DiagID);
9675 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9676}
9677
9678void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9679 const Stmt *PossibleBody) {
9680 assert(!CurrentInstantiationScope); // Ensured by caller
9681
9682 SourceLocation StmtLoc;
9683 const Stmt *Body;
9684 unsigned DiagID;
9685 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9686 StmtLoc = FS->getRParenLoc();
9687 Body = FS->getBody();
9688 DiagID = diag::warn_empty_for_body;
9689 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9690 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9691 Body = WS->getBody();
9692 DiagID = diag::warn_empty_while_body;
9693 } else
9694 return; // Neither `for' nor `while'.
9695
9696 // The body should be a null statement.
9697 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9698 if (!NBody)
9699 return;
9700
9701 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009702 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009703 return;
9704
9705 // Do the usual checks.
9706 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9707 return;
9708
9709 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9710 // noise level low, emit diagnostics only if for/while is followed by a
9711 // CompoundStmt, e.g.:
9712 // for (int i = 0; i < n; i++);
9713 // {
9714 // a(i);
9715 // }
9716 // or if for/while is followed by a statement with more indentation
9717 // than for/while itself:
9718 // for (int i = 0; i < n; i++);
9719 // a(i);
9720 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9721 if (!ProbableTypo) {
9722 bool BodyColInvalid;
9723 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9724 PossibleBody->getLocStart(),
9725 &BodyColInvalid);
9726 if (BodyColInvalid)
9727 return;
9728
9729 bool StmtColInvalid;
9730 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9731 S->getLocStart(),
9732 &StmtColInvalid);
9733 if (StmtColInvalid)
9734 return;
9735
9736 if (BodyCol > StmtCol)
9737 ProbableTypo = true;
9738 }
9739
9740 if (ProbableTypo) {
9741 Diag(NBody->getSemiLoc(), DiagID);
9742 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9743 }
9744}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009745
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009746//===--- CHECK: Warn on self move with std::move. -------------------------===//
9747
9748/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9749void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9750 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009751 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9752 return;
9753
9754 if (!ActiveTemplateInstantiations.empty())
9755 return;
9756
9757 // Strip parens and casts away.
9758 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9759 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9760
9761 // Check for a call expression
9762 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9763 if (!CE || CE->getNumArgs() != 1)
9764 return;
9765
9766 // Check for a call to std::move
9767 const FunctionDecl *FD = CE->getDirectCallee();
9768 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9769 !FD->getIdentifier()->isStr("move"))
9770 return;
9771
9772 // Get argument from std::move
9773 RHSExpr = CE->getArg(0);
9774
9775 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9776 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9777
9778 // Two DeclRefExpr's, check that the decls are the same.
9779 if (LHSDeclRef && RHSDeclRef) {
9780 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9781 return;
9782 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9783 RHSDeclRef->getDecl()->getCanonicalDecl())
9784 return;
9785
9786 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9787 << LHSExpr->getSourceRange()
9788 << RHSExpr->getSourceRange();
9789 return;
9790 }
9791
9792 // Member variables require a different approach to check for self moves.
9793 // MemberExpr's are the same if every nested MemberExpr refers to the same
9794 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9795 // the base Expr's are CXXThisExpr's.
9796 const Expr *LHSBase = LHSExpr;
9797 const Expr *RHSBase = RHSExpr;
9798 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9799 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9800 if (!LHSME || !RHSME)
9801 return;
9802
9803 while (LHSME && RHSME) {
9804 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9805 RHSME->getMemberDecl()->getCanonicalDecl())
9806 return;
9807
9808 LHSBase = LHSME->getBase();
9809 RHSBase = RHSME->getBase();
9810 LHSME = dyn_cast<MemberExpr>(LHSBase);
9811 RHSME = dyn_cast<MemberExpr>(RHSBase);
9812 }
9813
9814 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9815 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9816 if (LHSDeclRef && RHSDeclRef) {
9817 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9818 return;
9819 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9820 RHSDeclRef->getDecl()->getCanonicalDecl())
9821 return;
9822
9823 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9824 << LHSExpr->getSourceRange()
9825 << RHSExpr->getSourceRange();
9826 return;
9827 }
9828
9829 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9830 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9831 << LHSExpr->getSourceRange()
9832 << RHSExpr->getSourceRange();
9833}
9834
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009835//===--- Layout compatibility ----------------------------------------------//
9836
9837namespace {
9838
9839bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9840
9841/// \brief Check if two enumeration types are layout-compatible.
9842bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9843 // C++11 [dcl.enum] p8:
9844 // Two enumeration types are layout-compatible if they have the same
9845 // underlying type.
9846 return ED1->isComplete() && ED2->isComplete() &&
9847 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9848}
9849
9850/// \brief Check if two fields are layout-compatible.
9851bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9852 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9853 return false;
9854
9855 if (Field1->isBitField() != Field2->isBitField())
9856 return false;
9857
9858 if (Field1->isBitField()) {
9859 // Make sure that the bit-fields are the same length.
9860 unsigned Bits1 = Field1->getBitWidthValue(C);
9861 unsigned Bits2 = Field2->getBitWidthValue(C);
9862
9863 if (Bits1 != Bits2)
9864 return false;
9865 }
9866
9867 return true;
9868}
9869
9870/// \brief Check if two standard-layout structs are layout-compatible.
9871/// (C++11 [class.mem] p17)
9872bool isLayoutCompatibleStruct(ASTContext &C,
9873 RecordDecl *RD1,
9874 RecordDecl *RD2) {
9875 // If both records are C++ classes, check that base classes match.
9876 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9877 // If one of records is a CXXRecordDecl we are in C++ mode,
9878 // thus the other one is a CXXRecordDecl, too.
9879 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9880 // Check number of base classes.
9881 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9882 return false;
9883
9884 // Check the base classes.
9885 for (CXXRecordDecl::base_class_const_iterator
9886 Base1 = D1CXX->bases_begin(),
9887 BaseEnd1 = D1CXX->bases_end(),
9888 Base2 = D2CXX->bases_begin();
9889 Base1 != BaseEnd1;
9890 ++Base1, ++Base2) {
9891 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9892 return false;
9893 }
9894 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9895 // If only RD2 is a C++ class, it should have zero base classes.
9896 if (D2CXX->getNumBases() > 0)
9897 return false;
9898 }
9899
9900 // Check the fields.
9901 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9902 Field2End = RD2->field_end(),
9903 Field1 = RD1->field_begin(),
9904 Field1End = RD1->field_end();
9905 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9906 if (!isLayoutCompatible(C, *Field1, *Field2))
9907 return false;
9908 }
9909 if (Field1 != Field1End || Field2 != Field2End)
9910 return false;
9911
9912 return true;
9913}
9914
9915/// \brief Check if two standard-layout unions are layout-compatible.
9916/// (C++11 [class.mem] p18)
9917bool isLayoutCompatibleUnion(ASTContext &C,
9918 RecordDecl *RD1,
9919 RecordDecl *RD2) {
9920 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009921 for (auto *Field2 : RD2->fields())
9922 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009923
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009924 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009925 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9926 I = UnmatchedFields.begin(),
9927 E = UnmatchedFields.end();
9928
9929 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009930 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009931 bool Result = UnmatchedFields.erase(*I);
9932 (void) Result;
9933 assert(Result);
9934 break;
9935 }
9936 }
9937 if (I == E)
9938 return false;
9939 }
9940
9941 return UnmatchedFields.empty();
9942}
9943
9944bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9945 if (RD1->isUnion() != RD2->isUnion())
9946 return false;
9947
9948 if (RD1->isUnion())
9949 return isLayoutCompatibleUnion(C, RD1, RD2);
9950 else
9951 return isLayoutCompatibleStruct(C, RD1, RD2);
9952}
9953
9954/// \brief Check if two types are layout-compatible in C++11 sense.
9955bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9956 if (T1.isNull() || T2.isNull())
9957 return false;
9958
9959 // C++11 [basic.types] p11:
9960 // If two types T1 and T2 are the same type, then T1 and T2 are
9961 // layout-compatible types.
9962 if (C.hasSameType(T1, T2))
9963 return true;
9964
9965 T1 = T1.getCanonicalType().getUnqualifiedType();
9966 T2 = T2.getCanonicalType().getUnqualifiedType();
9967
9968 const Type::TypeClass TC1 = T1->getTypeClass();
9969 const Type::TypeClass TC2 = T2->getTypeClass();
9970
9971 if (TC1 != TC2)
9972 return false;
9973
9974 if (TC1 == Type::Enum) {
9975 return isLayoutCompatible(C,
9976 cast<EnumType>(T1)->getDecl(),
9977 cast<EnumType>(T2)->getDecl());
9978 } else if (TC1 == Type::Record) {
9979 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9980 return false;
9981
9982 return isLayoutCompatible(C,
9983 cast<RecordType>(T1)->getDecl(),
9984 cast<RecordType>(T2)->getDecl());
9985 }
9986
9987 return false;
9988}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009989} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009990
9991//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9992
9993namespace {
9994/// \brief Given a type tag expression find the type tag itself.
9995///
9996/// \param TypeExpr Type tag expression, as it appears in user's code.
9997///
9998/// \param VD Declaration of an identifier that appears in a type tag.
9999///
10000/// \param MagicValue Type tag magic value.
10001bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10002 const ValueDecl **VD, uint64_t *MagicValue) {
10003 while(true) {
10004 if (!TypeExpr)
10005 return false;
10006
10007 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10008
10009 switch (TypeExpr->getStmtClass()) {
10010 case Stmt::UnaryOperatorClass: {
10011 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10012 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10013 TypeExpr = UO->getSubExpr();
10014 continue;
10015 }
10016 return false;
10017 }
10018
10019 case Stmt::DeclRefExprClass: {
10020 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10021 *VD = DRE->getDecl();
10022 return true;
10023 }
10024
10025 case Stmt::IntegerLiteralClass: {
10026 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10027 llvm::APInt MagicValueAPInt = IL->getValue();
10028 if (MagicValueAPInt.getActiveBits() <= 64) {
10029 *MagicValue = MagicValueAPInt.getZExtValue();
10030 return true;
10031 } else
10032 return false;
10033 }
10034
10035 case Stmt::BinaryConditionalOperatorClass:
10036 case Stmt::ConditionalOperatorClass: {
10037 const AbstractConditionalOperator *ACO =
10038 cast<AbstractConditionalOperator>(TypeExpr);
10039 bool Result;
10040 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10041 if (Result)
10042 TypeExpr = ACO->getTrueExpr();
10043 else
10044 TypeExpr = ACO->getFalseExpr();
10045 continue;
10046 }
10047 return false;
10048 }
10049
10050 case Stmt::BinaryOperatorClass: {
10051 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10052 if (BO->getOpcode() == BO_Comma) {
10053 TypeExpr = BO->getRHS();
10054 continue;
10055 }
10056 return false;
10057 }
10058
10059 default:
10060 return false;
10061 }
10062 }
10063}
10064
10065/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10066///
10067/// \param TypeExpr Expression that specifies a type tag.
10068///
10069/// \param MagicValues Registered magic values.
10070///
10071/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10072/// kind.
10073///
10074/// \param TypeInfo Information about the corresponding C type.
10075///
10076/// \returns true if the corresponding C type was found.
10077bool GetMatchingCType(
10078 const IdentifierInfo *ArgumentKind,
10079 const Expr *TypeExpr, const ASTContext &Ctx,
10080 const llvm::DenseMap<Sema::TypeTagMagicValue,
10081 Sema::TypeTagData> *MagicValues,
10082 bool &FoundWrongKind,
10083 Sema::TypeTagData &TypeInfo) {
10084 FoundWrongKind = false;
10085
10086 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010087 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010088
10089 uint64_t MagicValue;
10090
10091 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10092 return false;
10093
10094 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010095 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010096 if (I->getArgumentKind() != ArgumentKind) {
10097 FoundWrongKind = true;
10098 return false;
10099 }
10100 TypeInfo.Type = I->getMatchingCType();
10101 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10102 TypeInfo.MustBeNull = I->getMustBeNull();
10103 return true;
10104 }
10105 return false;
10106 }
10107
10108 if (!MagicValues)
10109 return false;
10110
10111 llvm::DenseMap<Sema::TypeTagMagicValue,
10112 Sema::TypeTagData>::const_iterator I =
10113 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10114 if (I == MagicValues->end())
10115 return false;
10116
10117 TypeInfo = I->second;
10118 return true;
10119}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010120} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010121
10122void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10123 uint64_t MagicValue, QualType Type,
10124 bool LayoutCompatible,
10125 bool MustBeNull) {
10126 if (!TypeTagForDatatypeMagicValues)
10127 TypeTagForDatatypeMagicValues.reset(
10128 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10129
10130 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10131 (*TypeTagForDatatypeMagicValues)[Magic] =
10132 TypeTagData(Type, LayoutCompatible, MustBeNull);
10133}
10134
10135namespace {
10136bool IsSameCharType(QualType T1, QualType T2) {
10137 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10138 if (!BT1)
10139 return false;
10140
10141 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10142 if (!BT2)
10143 return false;
10144
10145 BuiltinType::Kind T1Kind = BT1->getKind();
10146 BuiltinType::Kind T2Kind = BT2->getKind();
10147
10148 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10149 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10150 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10151 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10152}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010153} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010154
10155void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10156 const Expr * const *ExprArgs) {
10157 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10158 bool IsPointerAttr = Attr->getIsPointer();
10159
10160 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10161 bool FoundWrongKind;
10162 TypeTagData TypeInfo;
10163 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10164 TypeTagForDatatypeMagicValues.get(),
10165 FoundWrongKind, TypeInfo)) {
10166 if (FoundWrongKind)
10167 Diag(TypeTagExpr->getExprLoc(),
10168 diag::warn_type_tag_for_datatype_wrong_kind)
10169 << TypeTagExpr->getSourceRange();
10170 return;
10171 }
10172
10173 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10174 if (IsPointerAttr) {
10175 // Skip implicit cast of pointer to `void *' (as a function argument).
10176 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010177 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010178 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010179 ArgumentExpr = ICE->getSubExpr();
10180 }
10181 QualType ArgumentType = ArgumentExpr->getType();
10182
10183 // Passing a `void*' pointer shouldn't trigger a warning.
10184 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10185 return;
10186
10187 if (TypeInfo.MustBeNull) {
10188 // Type tag with matching void type requires a null pointer.
10189 if (!ArgumentExpr->isNullPointerConstant(Context,
10190 Expr::NPC_ValueDependentIsNotNull)) {
10191 Diag(ArgumentExpr->getExprLoc(),
10192 diag::warn_type_safety_null_pointer_required)
10193 << ArgumentKind->getName()
10194 << ArgumentExpr->getSourceRange()
10195 << TypeTagExpr->getSourceRange();
10196 }
10197 return;
10198 }
10199
10200 QualType RequiredType = TypeInfo.Type;
10201 if (IsPointerAttr)
10202 RequiredType = Context.getPointerType(RequiredType);
10203
10204 bool mismatch = false;
10205 if (!TypeInfo.LayoutCompatible) {
10206 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10207
10208 // C++11 [basic.fundamental] p1:
10209 // Plain char, signed char, and unsigned char are three distinct types.
10210 //
10211 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10212 // char' depending on the current char signedness mode.
10213 if (mismatch)
10214 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10215 RequiredType->getPointeeType())) ||
10216 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10217 mismatch = false;
10218 } else
10219 if (IsPointerAttr)
10220 mismatch = !isLayoutCompatible(Context,
10221 ArgumentType->getPointeeType(),
10222 RequiredType->getPointeeType());
10223 else
10224 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10225
10226 if (mismatch)
10227 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010228 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010229 << TypeInfo.LayoutCompatible << RequiredType
10230 << ArgumentExpr->getSourceRange()
10231 << TypeTagExpr->getSourceRange();
10232}