blob: 9c3f721ca63fc1a4bc6dba403e00796615b5dcd5 [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>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000042using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000043using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000044
Chris Lattnera26fb342009-02-18 17:49:48 +000045SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
46 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000047 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
48 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000049}
50
John McCallbebede42011-02-26 05:39:39 +000051/// Checks that a call expression's argument count is the desired number.
52/// This is useful when doing custom type-checking. Returns true on error.
53static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
54 unsigned argCount = call->getNumArgs();
55 if (argCount == desiredArgCount) return false;
56
57 if (argCount < desiredArgCount)
58 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
59 << 0 /*function call*/ << desiredArgCount << argCount
60 << call->getSourceRange();
61
62 // Highlight all the excess arguments.
63 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
64 call->getArg(argCount - 1)->getLocEnd());
65
66 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
67 << 0 /*function call*/ << desiredArgCount << argCount
68 << call->getArg(1)->getSourceRange();
69}
70
Julien Lerouge4a5b4442012-04-28 17:39:16 +000071/// Check that the first argument to __builtin_annotation is an integer
72/// and the second argument is a non-wide string literal.
73static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
74 if (checkArgCount(S, TheCall, 2))
75 return true;
76
77 // First argument should be an integer.
78 Expr *ValArg = TheCall->getArg(0);
79 QualType Ty = ValArg->getType();
80 if (!Ty->isIntegerType()) {
81 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
82 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000083 return true;
84 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000085
86 // Second argument should be a constant string.
87 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
88 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
89 if (!Literal || !Literal->isAscii()) {
90 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
91 << StrArg->getSourceRange();
92 return true;
93 }
94
95 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000096 return false;
97}
98
Richard Smith6cbd65d2013-07-11 02:27:57 +000099/// Check that the argument to __builtin_addressof is a glvalue, and set the
100/// result type to the corresponding pointer type.
101static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
102 if (checkArgCount(S, TheCall, 1))
103 return true;
104
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000105 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000106 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
107 if (ResultType.isNull())
108 return true;
109
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000110 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000111 TheCall->setType(ResultType);
112 return false;
113}
114
John McCall03107a42015-10-29 20:48:01 +0000115static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
116 if (checkArgCount(S, TheCall, 3))
117 return true;
118
119 // First two arguments should be integers.
120 for (unsigned I = 0; I < 2; ++I) {
121 Expr *Arg = TheCall->getArg(I);
122 QualType Ty = Arg->getType();
123 if (!Ty->isIntegerType()) {
124 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
125 << Ty << Arg->getSourceRange();
126 return true;
127 }
128 }
129
130 // Third argument should be a pointer to a non-const integer.
131 // IRGen correctly handles volatile, restrict, and address spaces, and
132 // the other qualifiers aren't possible.
133 {
134 Expr *Arg = TheCall->getArg(2);
135 QualType Ty = Arg->getType();
136 const auto *PtrTy = Ty->getAs<PointerType>();
137 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
138 !PtrTy->getPointeeType().isConstQualified())) {
139 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
140 << Ty << Arg->getSourceRange();
141 return true;
142 }
143 }
144
145 return false;
146}
147
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000148static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
149 CallExpr *TheCall, unsigned SizeIdx,
150 unsigned DstSizeIdx) {
151 if (TheCall->getNumArgs() <= SizeIdx ||
152 TheCall->getNumArgs() <= DstSizeIdx)
153 return;
154
155 const Expr *SizeArg = TheCall->getArg(SizeIdx);
156 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
157
158 llvm::APSInt Size, DstSize;
159
160 // find out if both sizes are known at compile time
161 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
162 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
163 return;
164
165 if (Size.ule(DstSize))
166 return;
167
168 // confirmed overflow so generate the diagnostic.
169 IdentifierInfo *FnName = FDecl->getIdentifier();
170 SourceLocation SL = TheCall->getLocStart();
171 SourceRange SR = TheCall->getSourceRange();
172
173 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
174}
175
Peter Collingbournef7706832014-12-12 23:41:25 +0000176static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
177 if (checkArgCount(S, BuiltinCall, 2))
178 return true;
179
180 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
181 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
182 Expr *Call = BuiltinCall->getArg(0);
183 Expr *Chain = BuiltinCall->getArg(1);
184
185 if (Call->getStmtClass() != Stmt::CallExprClass) {
186 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
187 << Call->getSourceRange();
188 return true;
189 }
190
191 auto CE = cast<CallExpr>(Call);
192 if (CE->getCallee()->getType()->isBlockPointerType()) {
193 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
194 << Call->getSourceRange();
195 return true;
196 }
197
198 const Decl *TargetDecl = CE->getCalleeDecl();
199 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
200 if (FD->getBuiltinID()) {
201 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
202 << Call->getSourceRange();
203 return true;
204 }
205
206 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
207 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
208 << Call->getSourceRange();
209 return true;
210 }
211
212 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
213 if (ChainResult.isInvalid())
214 return true;
215 if (!ChainResult.get()->getType()->isPointerType()) {
216 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
217 << Chain->getSourceRange();
218 return true;
219 }
220
David Majnemerced8bdf2015-02-25 17:36:15 +0000221 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000222 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
223 QualType BuiltinTy = S.Context.getFunctionType(
224 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
225 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
226
227 Builtin =
228 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
229
230 BuiltinCall->setType(CE->getType());
231 BuiltinCall->setValueKind(CE->getValueKind());
232 BuiltinCall->setObjectKind(CE->getObjectKind());
233 BuiltinCall->setCallee(Builtin);
234 BuiltinCall->setArg(1, ChainResult.get());
235
236 return false;
237}
238
Reid Kleckner1d59f992015-01-22 01:36:17 +0000239static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
240 Scope::ScopeFlags NeededScopeFlags,
241 unsigned DiagID) {
242 // Scopes aren't available during instantiation. Fortunately, builtin
243 // functions cannot be template args so they cannot be formed through template
244 // instantiation. Therefore checking once during the parse is sufficient.
245 if (!SemaRef.ActiveTemplateInstantiations.empty())
246 return false;
247
248 Scope *S = SemaRef.getCurScope();
249 while (S && !S->isSEHExceptScope())
250 S = S->getParent();
251 if (!S || !(S->getFlags() & NeededScopeFlags)) {
252 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
253 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
254 << DRE->getDecl()->getIdentifier();
255 return true;
256 }
257
258 return false;
259}
260
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000261/// Returns readable name for a call.
262static StringRef getFunctionName(CallExpr *Call) {
263 return cast<FunctionDecl>(Call->getCalleeDecl())->getName();
264}
265
266/// Returns OpenCL access qual.
267// TODO: Refine OpenCLImageAccessAttr to OpenCLAccessAttr since pipe can use
268// it too
269static OpenCLImageAccessAttr *getOpenCLArgAccess(const Decl *D) {
270 if (D->hasAttr<OpenCLImageAccessAttr>())
271 return D->getAttr<OpenCLImageAccessAttr>();
272 return nullptr;
273}
274
275/// Returns true if pipe element type is different from the pointer.
276static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
277 const Expr *Arg0 = Call->getArg(0);
278 // First argument type should always be pipe.
279 if (!Arg0->getType()->isPipeType()) {
280 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
281 << getFunctionName(Call) << Arg0->getSourceRange();
282 return true;
283 }
284 OpenCLImageAccessAttr *AccessQual =
285 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
286 // Validates the access qualifier is compatible with the call.
287 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
288 // read_only and write_only, and assumed to be read_only if no qualifier is
289 // specified.
290 bool isValid = true;
291 bool ReadOnly = getFunctionName(Call).find("read") != StringRef::npos;
292 if (ReadOnly)
293 isValid = AccessQual == nullptr || AccessQual->isReadOnly();
294 else
295 isValid = AccessQual != nullptr && AccessQual->isWriteOnly();
296 if (!isValid) {
297 const char *AM = ReadOnly ? "read_only" : "write_only";
298 S.Diag(Arg0->getLocStart(),
299 diag::err_opencl_builtin_pipe_invalid_access_modifier)
300 << AM << Arg0->getSourceRange();
301 return true;
302 }
303
304 return false;
305}
306
307/// Returns true if pipe element type is different from the pointer.
308static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
309 const Expr *Arg0 = Call->getArg(0);
310 const Expr *ArgIdx = Call->getArg(Idx);
311 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
312 const Type *EltTy = PipeTy->getElementType().getTypePtr();
313 const PointerType *ArgTy =
314 dyn_cast<PointerType>(ArgIdx->getType().getTypePtr());
315 // The Idx argument should be a pointer and the type of the pointer and
316 // the type of pipe element should also be the same.
317 if (!ArgTy || EltTy != ArgTy->getPointeeType().getTypePtr()) {
318 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
319 << getFunctionName(Call)
320 << S.Context.getPointerType(PipeTy->getElementType())
321 << ArgIdx->getSourceRange();
322 return true;
323 }
324 return false;
325}
326
327// \brief Performs semantic analysis for the read/write_pipe call.
328// \param S Reference to the semantic analyzer.
329// \param Call A pointer to the builtin call.
330// \return True if a semantic error has been found, false otherwise.
331static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
332 // Two kinds of read/write pipe
333 // From OpenCL C Specification 6.13.16.2 the built-in read/write
334 // functions have following forms.
335 switch (Call->getNumArgs()) {
336 case 2: {
337 if (checkOpenCLPipeArg(S, Call))
338 return true;
339 // The call with 2 arguments should be
340 // read/write_pipe(pipe T, T*)
341 // check packet type T
342 if (checkOpenCLPipePacketType(S, Call, 1))
343 return true;
344 } break;
345
346 case 4: {
347 if (checkOpenCLPipeArg(S, Call))
348 return true;
349 // The call with 4 arguments should be
350 // read/write_pipe(pipe T, reserve_id_t, uint, T*)
351 // check reserve_id_t
352 if (!Call->getArg(1)->getType()->isReserveIDT()) {
353 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
354 << getFunctionName(Call) << S.Context.OCLReserveIDTy
355 << Call->getArg(1)->getSourceRange();
356 return true;
357 }
358
359 // check the index
360 const Expr *Arg2 = Call->getArg(2);
361 if (!Arg2->getType()->isIntegerType() &&
362 !Arg2->getType()->isUnsignedIntegerType()) {
363 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
364 << getFunctionName(Call) << S.Context.UnsignedIntTy
365 << Arg2->getSourceRange();
366 return true;
367 }
368
369 // check packet type T
370 if (checkOpenCLPipePacketType(S, Call, 3))
371 return true;
372 } break;
373 default:
374 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
375 << getFunctionName(Call) << Call->getSourceRange();
376 return true;
377 }
378
379 return false;
380}
381
382// \brief Performs a semantic analysis on the {work_group_/sub_group_
383// /_}reserve_{read/write}_pipe
384// \param S Reference to the semantic analyzer.
385// \param Call The call to the builtin function to be analyzed.
386// \return True if a semantic error was found, false otherwise.
387static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
388 if (checkArgCount(S, Call, 2))
389 return true;
390
391 if (checkOpenCLPipeArg(S, Call))
392 return true;
393
394 // check the reserve size
395 if (!Call->getArg(1)->getType()->isIntegerType() &&
396 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
397 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
398 << getFunctionName(Call) << S.Context.UnsignedIntTy
399 << Call->getArg(1)->getSourceRange();
400 return true;
401 }
402
403 return false;
404}
405
406// \brief Performs a semantic analysis on {work_group_/sub_group_
407// /_}commit_{read/write}_pipe
408// \param S Reference to the semantic analyzer.
409// \param Call The call to the builtin function to be analyzed.
410// \return True if a semantic error was found, false otherwise.
411static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
412 if (checkArgCount(S, Call, 2))
413 return true;
414
415 if (checkOpenCLPipeArg(S, Call))
416 return true;
417
418 // check reserve_id_t
419 if (!Call->getArg(1)->getType()->isReserveIDT()) {
420 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
421 << getFunctionName(Call) << S.Context.OCLReserveIDTy
422 << Call->getArg(1)->getSourceRange();
423 return true;
424 }
425
426 return false;
427}
428
429// \brief Performs a semantic analysis on the call to built-in Pipe
430// Query Functions.
431// \param S Reference to the semantic analyzer.
432// \param Call The call to the builtin function to be analyzed.
433// \return True if a semantic error was found, false otherwise.
434static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
435 if (checkArgCount(S, Call, 1))
436 return true;
437
438 if (!Call->getArg(0)->getType()->isPipeType()) {
439 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
440 << getFunctionName(Call) << Call->getArg(0)->getSourceRange();
441 return true;
442 }
443
444 return false;
445}
446
John McCalldadc5752010-08-24 06:29:42 +0000447ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000448Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
449 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000450 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000451
Chris Lattner3be167f2010-10-01 23:23:24 +0000452 // Find out if any arguments are required to be integer constant expressions.
453 unsigned ICEArguments = 0;
454 ASTContext::GetBuiltinTypeError Error;
455 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
456 if (Error != ASTContext::GE_None)
457 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
458
459 // If any arguments are required to be ICE's, check and diagnose.
460 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
461 // Skip arguments not required to be ICE's.
462 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
463
464 llvm::APSInt Result;
465 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
466 return true;
467 ICEArguments &= ~(1 << ArgNo);
468 }
469
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000470 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000471 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000472 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000473 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000474 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000475 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000476 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000477 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000478 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000479 if (SemaBuiltinVAStart(TheCall))
480 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000481 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000482 case Builtin::BI__va_start: {
483 switch (Context.getTargetInfo().getTriple().getArch()) {
484 case llvm::Triple::arm:
485 case llvm::Triple::thumb:
486 if (SemaBuiltinVAStartARM(TheCall))
487 return ExprError();
488 break;
489 default:
490 if (SemaBuiltinVAStart(TheCall))
491 return ExprError();
492 break;
493 }
494 break;
495 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000496 case Builtin::BI__builtin_isgreater:
497 case Builtin::BI__builtin_isgreaterequal:
498 case Builtin::BI__builtin_isless:
499 case Builtin::BI__builtin_islessequal:
500 case Builtin::BI__builtin_islessgreater:
501 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000502 if (SemaBuiltinUnorderedCompare(TheCall))
503 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000504 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000505 case Builtin::BI__builtin_fpclassify:
506 if (SemaBuiltinFPClassification(TheCall, 6))
507 return ExprError();
508 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000509 case Builtin::BI__builtin_isfinite:
510 case Builtin::BI__builtin_isinf:
511 case Builtin::BI__builtin_isinf_sign:
512 case Builtin::BI__builtin_isnan:
513 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000514 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000515 return ExprError();
516 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000517 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000518 return SemaBuiltinShuffleVector(TheCall);
519 // TheCall will be freed by the smart pointer here, but that's fine, since
520 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000521 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000522 if (SemaBuiltinPrefetch(TheCall))
523 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000524 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000525 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000526 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000527 if (SemaBuiltinAssume(TheCall))
528 return ExprError();
529 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000530 case Builtin::BI__builtin_assume_aligned:
531 if (SemaBuiltinAssumeAligned(TheCall))
532 return ExprError();
533 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000534 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000535 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000536 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000537 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000538 case Builtin::BI__builtin_longjmp:
539 if (SemaBuiltinLongjmp(TheCall))
540 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000541 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000542 case Builtin::BI__builtin_setjmp:
543 if (SemaBuiltinSetjmp(TheCall))
544 return ExprError();
545 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000546 case Builtin::BI_setjmp:
547 case Builtin::BI_setjmpex:
548 if (checkArgCount(*this, TheCall, 1))
549 return true;
550 break;
John McCallbebede42011-02-26 05:39:39 +0000551
552 case Builtin::BI__builtin_classify_type:
553 if (checkArgCount(*this, TheCall, 1)) return true;
554 TheCall->setType(Context.IntTy);
555 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000556 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000557 if (checkArgCount(*this, TheCall, 1)) return true;
558 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000559 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000560 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000561 case Builtin::BI__sync_fetch_and_add_1:
562 case Builtin::BI__sync_fetch_and_add_2:
563 case Builtin::BI__sync_fetch_and_add_4:
564 case Builtin::BI__sync_fetch_and_add_8:
565 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000566 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000567 case Builtin::BI__sync_fetch_and_sub_1:
568 case Builtin::BI__sync_fetch_and_sub_2:
569 case Builtin::BI__sync_fetch_and_sub_4:
570 case Builtin::BI__sync_fetch_and_sub_8:
571 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000572 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000573 case Builtin::BI__sync_fetch_and_or_1:
574 case Builtin::BI__sync_fetch_and_or_2:
575 case Builtin::BI__sync_fetch_and_or_4:
576 case Builtin::BI__sync_fetch_and_or_8:
577 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000578 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000579 case Builtin::BI__sync_fetch_and_and_1:
580 case Builtin::BI__sync_fetch_and_and_2:
581 case Builtin::BI__sync_fetch_and_and_4:
582 case Builtin::BI__sync_fetch_and_and_8:
583 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000584 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000585 case Builtin::BI__sync_fetch_and_xor_1:
586 case Builtin::BI__sync_fetch_and_xor_2:
587 case Builtin::BI__sync_fetch_and_xor_4:
588 case Builtin::BI__sync_fetch_and_xor_8:
589 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000590 case Builtin::BI__sync_fetch_and_nand:
591 case Builtin::BI__sync_fetch_and_nand_1:
592 case Builtin::BI__sync_fetch_and_nand_2:
593 case Builtin::BI__sync_fetch_and_nand_4:
594 case Builtin::BI__sync_fetch_and_nand_8:
595 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000596 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000597 case Builtin::BI__sync_add_and_fetch_1:
598 case Builtin::BI__sync_add_and_fetch_2:
599 case Builtin::BI__sync_add_and_fetch_4:
600 case Builtin::BI__sync_add_and_fetch_8:
601 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000602 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000603 case Builtin::BI__sync_sub_and_fetch_1:
604 case Builtin::BI__sync_sub_and_fetch_2:
605 case Builtin::BI__sync_sub_and_fetch_4:
606 case Builtin::BI__sync_sub_and_fetch_8:
607 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000608 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000609 case Builtin::BI__sync_and_and_fetch_1:
610 case Builtin::BI__sync_and_and_fetch_2:
611 case Builtin::BI__sync_and_and_fetch_4:
612 case Builtin::BI__sync_and_and_fetch_8:
613 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000614 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000615 case Builtin::BI__sync_or_and_fetch_1:
616 case Builtin::BI__sync_or_and_fetch_2:
617 case Builtin::BI__sync_or_and_fetch_4:
618 case Builtin::BI__sync_or_and_fetch_8:
619 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000620 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000621 case Builtin::BI__sync_xor_and_fetch_1:
622 case Builtin::BI__sync_xor_and_fetch_2:
623 case Builtin::BI__sync_xor_and_fetch_4:
624 case Builtin::BI__sync_xor_and_fetch_8:
625 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000626 case Builtin::BI__sync_nand_and_fetch:
627 case Builtin::BI__sync_nand_and_fetch_1:
628 case Builtin::BI__sync_nand_and_fetch_2:
629 case Builtin::BI__sync_nand_and_fetch_4:
630 case Builtin::BI__sync_nand_and_fetch_8:
631 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000632 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000633 case Builtin::BI__sync_val_compare_and_swap_1:
634 case Builtin::BI__sync_val_compare_and_swap_2:
635 case Builtin::BI__sync_val_compare_and_swap_4:
636 case Builtin::BI__sync_val_compare_and_swap_8:
637 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000638 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000639 case Builtin::BI__sync_bool_compare_and_swap_1:
640 case Builtin::BI__sync_bool_compare_and_swap_2:
641 case Builtin::BI__sync_bool_compare_and_swap_4:
642 case Builtin::BI__sync_bool_compare_and_swap_8:
643 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000644 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000645 case Builtin::BI__sync_lock_test_and_set_1:
646 case Builtin::BI__sync_lock_test_and_set_2:
647 case Builtin::BI__sync_lock_test_and_set_4:
648 case Builtin::BI__sync_lock_test_and_set_8:
649 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000650 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000651 case Builtin::BI__sync_lock_release_1:
652 case Builtin::BI__sync_lock_release_2:
653 case Builtin::BI__sync_lock_release_4:
654 case Builtin::BI__sync_lock_release_8:
655 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000656 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000657 case Builtin::BI__sync_swap_1:
658 case Builtin::BI__sync_swap_2:
659 case Builtin::BI__sync_swap_4:
660 case Builtin::BI__sync_swap_8:
661 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000662 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000663 case Builtin::BI__builtin_nontemporal_load:
664 case Builtin::BI__builtin_nontemporal_store:
665 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000666#define BUILTIN(ID, TYPE, ATTRS)
667#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
668 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000669 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000670#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000671 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000672 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000673 return ExprError();
674 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000675 case Builtin::BI__builtin_addressof:
676 if (SemaBuiltinAddressof(*this, TheCall))
677 return ExprError();
678 break;
John McCall03107a42015-10-29 20:48:01 +0000679 case Builtin::BI__builtin_add_overflow:
680 case Builtin::BI__builtin_sub_overflow:
681 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000682 if (SemaBuiltinOverflow(*this, TheCall))
683 return ExprError();
684 break;
Richard Smith760520b2014-06-03 23:27:44 +0000685 case Builtin::BI__builtin_operator_new:
686 case Builtin::BI__builtin_operator_delete:
687 if (!getLangOpts().CPlusPlus) {
688 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
689 << (BuiltinID == Builtin::BI__builtin_operator_new
690 ? "__builtin_operator_new"
691 : "__builtin_operator_delete")
692 << "C++";
693 return ExprError();
694 }
695 // CodeGen assumes it can find the global new and delete to call,
696 // so ensure that they are declared.
697 DeclareGlobalNewDelete();
698 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000699
700 // check secure string manipulation functions where overflows
701 // are detectable at compile time
702 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000703 case Builtin::BI__builtin___memmove_chk:
704 case Builtin::BI__builtin___memset_chk:
705 case Builtin::BI__builtin___strlcat_chk:
706 case Builtin::BI__builtin___strlcpy_chk:
707 case Builtin::BI__builtin___strncat_chk:
708 case Builtin::BI__builtin___strncpy_chk:
709 case Builtin::BI__builtin___stpncpy_chk:
710 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
711 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000712 case Builtin::BI__builtin___memccpy_chk:
713 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
714 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000715 case Builtin::BI__builtin___snprintf_chk:
716 case Builtin::BI__builtin___vsnprintf_chk:
717 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
718 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000719
720 case Builtin::BI__builtin_call_with_static_chain:
721 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
722 return ExprError();
723 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000724
725 case Builtin::BI__exception_code:
726 case Builtin::BI_exception_code: {
727 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
728 diag::err_seh___except_block))
729 return ExprError();
730 break;
731 }
732 case Builtin::BI__exception_info:
733 case Builtin::BI_exception_info: {
734 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
735 diag::err_seh___except_filter))
736 return ExprError();
737 break;
738 }
739
David Majnemerba3e5ec2015-03-13 18:26:17 +0000740 case Builtin::BI__GetExceptionInfo:
741 if (checkArgCount(*this, TheCall, 1))
742 return ExprError();
743
744 if (CheckCXXThrowOperand(
745 TheCall->getLocStart(),
746 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
747 TheCall))
748 return ExprError();
749
750 TheCall->setType(Context.VoidPtrTy);
751 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000752 case Builtin::BIread_pipe:
753 case Builtin::BIwrite_pipe:
754 // Since those two functions are declared with var args, we need a semantic
755 // check for the argument.
756 if (SemaBuiltinRWPipe(*this, TheCall))
757 return ExprError();
758 break;
759 case Builtin::BIreserve_read_pipe:
760 case Builtin::BIreserve_write_pipe:
761 case Builtin::BIwork_group_reserve_read_pipe:
762 case Builtin::BIwork_group_reserve_write_pipe:
763 case Builtin::BIsub_group_reserve_read_pipe:
764 case Builtin::BIsub_group_reserve_write_pipe:
765 if (SemaBuiltinReserveRWPipe(*this, TheCall))
766 return ExprError();
767 // Since return type of reserve_read/write_pipe built-in function is
768 // reserve_id_t, which is not defined in the builtin def file , we used int
769 // as return type and need to override the return type of these functions.
770 TheCall->setType(Context.OCLReserveIDTy);
771 break;
772 case Builtin::BIcommit_read_pipe:
773 case Builtin::BIcommit_write_pipe:
774 case Builtin::BIwork_group_commit_read_pipe:
775 case Builtin::BIwork_group_commit_write_pipe:
776 case Builtin::BIsub_group_commit_read_pipe:
777 case Builtin::BIsub_group_commit_write_pipe:
778 if (SemaBuiltinCommitRWPipe(*this, TheCall))
779 return ExprError();
780 break;
781 case Builtin::BIget_pipe_num_packets:
782 case Builtin::BIget_pipe_max_packets:
783 if (SemaBuiltinPipePackets(*this, TheCall))
784 return ExprError();
785 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +0000786
Nate Begeman4904e322010-06-08 02:47:44 +0000787 }
Richard Smith760520b2014-06-03 23:27:44 +0000788
Nate Begeman4904e322010-06-08 02:47:44 +0000789 // Since the target specific builtins for each arch overlap, only check those
790 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +0000791 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000792 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000793 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000794 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000795 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000796 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000797 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
798 return ExprError();
799 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000800 case llvm::Triple::aarch64:
801 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000802 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000803 return ExprError();
804 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000805 case llvm::Triple::mips:
806 case llvm::Triple::mipsel:
807 case llvm::Triple::mips64:
808 case llvm::Triple::mips64el:
809 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
810 return ExprError();
811 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000812 case llvm::Triple::systemz:
813 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
814 return ExprError();
815 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000816 case llvm::Triple::x86:
817 case llvm::Triple::x86_64:
818 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
819 return ExprError();
820 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000821 case llvm::Triple::ppc:
822 case llvm::Triple::ppc64:
823 case llvm::Triple::ppc64le:
824 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
825 return ExprError();
826 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000827 default:
828 break;
829 }
830 }
831
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000832 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000833}
834
Nate Begeman91e1fea2010-06-14 05:21:25 +0000835// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000836static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000837 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000838 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000839 switch (Type.getEltType()) {
840 case NeonTypeFlags::Int8:
841 case NeonTypeFlags::Poly8:
842 return shift ? 7 : (8 << IsQuad) - 1;
843 case NeonTypeFlags::Int16:
844 case NeonTypeFlags::Poly16:
845 return shift ? 15 : (4 << IsQuad) - 1;
846 case NeonTypeFlags::Int32:
847 return shift ? 31 : (2 << IsQuad) - 1;
848 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000849 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000850 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000851 case NeonTypeFlags::Poly128:
852 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000853 case NeonTypeFlags::Float16:
854 assert(!shift && "cannot shift float types!");
855 return (4 << IsQuad) - 1;
856 case NeonTypeFlags::Float32:
857 assert(!shift && "cannot shift float types!");
858 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000859 case NeonTypeFlags::Float64:
860 assert(!shift && "cannot shift float types!");
861 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000862 }
David Blaikie8a40f702012-01-17 06:56:22 +0000863 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000864}
865
Bob Wilsone4d77232011-11-08 05:04:11 +0000866/// getNeonEltType - Return the QualType corresponding to the elements of
867/// the vector type specified by the NeonTypeFlags. This is used to check
868/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000869static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000870 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000871 switch (Flags.getEltType()) {
872 case NeonTypeFlags::Int8:
873 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
874 case NeonTypeFlags::Int16:
875 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
876 case NeonTypeFlags::Int32:
877 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
878 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000879 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000880 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
881 else
882 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
883 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000884 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000885 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000886 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000887 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000888 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000889 if (IsInt64Long)
890 return Context.UnsignedLongTy;
891 else
892 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000893 case NeonTypeFlags::Poly128:
894 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000895 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000896 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000897 case NeonTypeFlags::Float32:
898 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000899 case NeonTypeFlags::Float64:
900 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000901 }
David Blaikie8a40f702012-01-17 06:56:22 +0000902 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000903}
904
Tim Northover12670412014-02-19 10:37:05 +0000905bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000906 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000907 uint64_t mask = 0;
908 unsigned TV = 0;
909 int PtrArgNum = -1;
910 bool HasConstPtr = false;
911 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000912#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000913#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000914#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000915 }
916
917 // For NEON intrinsics which are overloaded on vector element type, validate
918 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000919 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000920 if (mask) {
921 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
922 return true;
923
924 TV = Result.getLimitedValue(64);
925 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
926 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000927 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000928 }
929
930 if (PtrArgNum >= 0) {
931 // Check that pointer arguments have the specified type.
932 Expr *Arg = TheCall->getArg(PtrArgNum);
933 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
934 Arg = ICE->getSubExpr();
935 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
936 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000937
Tim Northovera2ee4332014-03-29 15:09:45 +0000938 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000939 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000940 bool IsInt64Long =
941 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
942 QualType EltTy =
943 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000944 if (HasConstPtr)
945 EltTy = EltTy.withConst();
946 QualType LHSTy = Context.getPointerType(EltTy);
947 AssignConvertType ConvTy;
948 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
949 if (RHS.isInvalid())
950 return true;
951 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
952 RHS.get(), AA_Assigning))
953 return true;
954 }
955
956 // For NEON intrinsics which take an immediate value as part of the
957 // instruction, range check them here.
958 unsigned i = 0, l = 0, u = 0;
959 switch (BuiltinID) {
960 default:
961 return false;
Tim Northover12670412014-02-19 10:37:05 +0000962#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000963#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000964#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000965 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000966
Richard Sandiford28940af2014-04-16 08:47:51 +0000967 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000968}
969
Tim Northovera2ee4332014-03-29 15:09:45 +0000970bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
971 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000972 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000973 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000974 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000975 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000976 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000977 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
978 BuiltinID == AArch64::BI__builtin_arm_strex ||
979 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000980 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000981 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000982 BuiltinID == ARM::BI__builtin_arm_ldaex ||
983 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
984 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000985
986 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
987
988 // Ensure that we have the proper number of arguments.
989 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
990 return true;
991
992 // Inspect the pointer argument of the atomic builtin. This should always be
993 // a pointer type, whose element is an integral scalar or pointer type.
994 // Because it is a pointer type, we don't have to worry about any implicit
995 // casts here.
996 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
997 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
998 if (PointerArgRes.isInvalid())
999 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001000 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001001
1002 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1003 if (!pointerType) {
1004 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1005 << PointerArg->getType() << PointerArg->getSourceRange();
1006 return true;
1007 }
1008
1009 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1010 // task is to insert the appropriate casts into the AST. First work out just
1011 // what the appropriate type is.
1012 QualType ValType = pointerType->getPointeeType();
1013 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1014 if (IsLdrex)
1015 AddrType.addConst();
1016
1017 // Issue a warning if the cast is dodgy.
1018 CastKind CastNeeded = CK_NoOp;
1019 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1020 CastNeeded = CK_BitCast;
1021 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1022 << PointerArg->getType()
1023 << Context.getPointerType(AddrType)
1024 << AA_Passing << PointerArg->getSourceRange();
1025 }
1026
1027 // Finally, do the cast and replace the argument with the corrected version.
1028 AddrType = Context.getPointerType(AddrType);
1029 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1030 if (PointerArgRes.isInvalid())
1031 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001032 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001033
1034 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1035
1036 // In general, we allow ints, floats and pointers to be loaded and stored.
1037 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1038 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1039 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1040 << PointerArg->getType() << PointerArg->getSourceRange();
1041 return true;
1042 }
1043
1044 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001045 if (Context.getTypeSize(ValType) > MaxWidth) {
1046 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001047 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1048 << PointerArg->getType() << PointerArg->getSourceRange();
1049 return true;
1050 }
1051
1052 switch (ValType.getObjCLifetime()) {
1053 case Qualifiers::OCL_None:
1054 case Qualifiers::OCL_ExplicitNone:
1055 // okay
1056 break;
1057
1058 case Qualifiers::OCL_Weak:
1059 case Qualifiers::OCL_Strong:
1060 case Qualifiers::OCL_Autoreleasing:
1061 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1062 << ValType << PointerArg->getSourceRange();
1063 return true;
1064 }
1065
1066
1067 if (IsLdrex) {
1068 TheCall->setType(ValType);
1069 return false;
1070 }
1071
1072 // Initialize the argument to be stored.
1073 ExprResult ValArg = TheCall->getArg(0);
1074 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1075 Context, ValType, /*consume*/ false);
1076 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1077 if (ValArg.isInvalid())
1078 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001079 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001080
1081 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1082 // but the custom checker bypasses all default analysis.
1083 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001084 return false;
1085}
1086
Nate Begeman4904e322010-06-08 02:47:44 +00001087bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001088 llvm::APSInt Result;
1089
Tim Northover6aacd492013-07-16 09:47:53 +00001090 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001091 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1092 BuiltinID == ARM::BI__builtin_arm_strex ||
1093 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001094 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001095 }
1096
Yi Kong26d104a2014-08-13 19:18:14 +00001097 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1098 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1099 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1100 }
1101
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001102 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1103 BuiltinID == ARM::BI__builtin_arm_wsr64)
1104 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1105
1106 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1107 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1108 BuiltinID == ARM::BI__builtin_arm_wsr ||
1109 BuiltinID == ARM::BI__builtin_arm_wsrp)
1110 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1111
Tim Northover12670412014-02-19 10:37:05 +00001112 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1113 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001114
Yi Kong4efadfb2014-07-03 16:01:25 +00001115 // For intrinsics which take an immediate value as part of the instruction,
1116 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001117 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001118 switch (BuiltinID) {
1119 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001120 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1121 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001122 case ARM::BI__builtin_arm_vcvtr_f:
1123 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001124 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001125 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001126 case ARM::BI__builtin_arm_isb:
1127 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001128 }
Nate Begemand773fe62010-06-13 04:47:52 +00001129
Nate Begemanf568b072010-08-03 21:32:34 +00001130 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001131 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001132}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001133
Tim Northover573cbee2014-05-24 12:52:07 +00001134bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001135 CallExpr *TheCall) {
1136 llvm::APSInt Result;
1137
Tim Northover573cbee2014-05-24 12:52:07 +00001138 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001139 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1140 BuiltinID == AArch64::BI__builtin_arm_strex ||
1141 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001142 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1143 }
1144
Yi Konga5548432014-08-13 19:18:20 +00001145 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1146 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1147 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1148 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1149 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1150 }
1151
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001152 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1153 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1154 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
1155
1156 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1157 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1158 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1159 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1160 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1161
Tim Northovera2ee4332014-03-29 15:09:45 +00001162 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1163 return true;
1164
Yi Kong19a29ac2014-07-17 10:52:06 +00001165 // For intrinsics which take an immediate value as part of the instruction,
1166 // range check them here.
1167 unsigned i = 0, l = 0, u = 0;
1168 switch (BuiltinID) {
1169 default: return false;
1170 case AArch64::BI__builtin_arm_dmb:
1171 case AArch64::BI__builtin_arm_dsb:
1172 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1173 }
1174
Yi Kong19a29ac2014-07-17 10:52:06 +00001175 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001176}
1177
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001178bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1179 unsigned i = 0, l = 0, u = 0;
1180 switch (BuiltinID) {
1181 default: return false;
1182 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1183 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001184 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1185 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1186 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1187 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1188 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001189 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001190
Richard Sandiford28940af2014-04-16 08:47:51 +00001191 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001192}
1193
Kit Bartone50adcb2015-03-30 19:40:59 +00001194bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1195 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001196 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1197 BuiltinID == PPC::BI__builtin_divdeu ||
1198 BuiltinID == PPC::BI__builtin_bpermd;
1199 bool IsTarget64Bit = Context.getTargetInfo()
1200 .getTypeWidth(Context
1201 .getTargetInfo()
1202 .getIntPtrType()) == 64;
1203 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1204 BuiltinID == PPC::BI__builtin_divweu ||
1205 BuiltinID == PPC::BI__builtin_divde ||
1206 BuiltinID == PPC::BI__builtin_divdeu;
1207
1208 if (Is64BitBltin && !IsTarget64Bit)
1209 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1210 << TheCall->getSourceRange();
1211
1212 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1213 (BuiltinID == PPC::BI__builtin_bpermd &&
1214 !Context.getTargetInfo().hasFeature("bpermd")))
1215 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1216 << TheCall->getSourceRange();
1217
Kit Bartone50adcb2015-03-30 19:40:59 +00001218 switch (BuiltinID) {
1219 default: return false;
1220 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1221 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1222 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1223 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1224 case PPC::BI__builtin_tbegin:
1225 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1226 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1227 case PPC::BI__builtin_tabortwc:
1228 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1229 case PPC::BI__builtin_tabortwci:
1230 case PPC::BI__builtin_tabortdci:
1231 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1232 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1233 }
1234 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1235}
1236
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001237bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1238 CallExpr *TheCall) {
1239 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1240 Expr *Arg = TheCall->getArg(0);
1241 llvm::APSInt AbortCode(32);
1242 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1243 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1244 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1245 << Arg->getSourceRange();
1246 }
1247
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001248 // For intrinsics which take an immediate value as part of the instruction,
1249 // range check them here.
1250 unsigned i = 0, l = 0, u = 0;
1251 switch (BuiltinID) {
1252 default: return false;
1253 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1254 case SystemZ::BI__builtin_s390_verimb:
1255 case SystemZ::BI__builtin_s390_verimh:
1256 case SystemZ::BI__builtin_s390_verimf:
1257 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1258 case SystemZ::BI__builtin_s390_vfaeb:
1259 case SystemZ::BI__builtin_s390_vfaeh:
1260 case SystemZ::BI__builtin_s390_vfaef:
1261 case SystemZ::BI__builtin_s390_vfaebs:
1262 case SystemZ::BI__builtin_s390_vfaehs:
1263 case SystemZ::BI__builtin_s390_vfaefs:
1264 case SystemZ::BI__builtin_s390_vfaezb:
1265 case SystemZ::BI__builtin_s390_vfaezh:
1266 case SystemZ::BI__builtin_s390_vfaezf:
1267 case SystemZ::BI__builtin_s390_vfaezbs:
1268 case SystemZ::BI__builtin_s390_vfaezhs:
1269 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1270 case SystemZ::BI__builtin_s390_vfidb:
1271 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1272 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1273 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1274 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1275 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1276 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1277 case SystemZ::BI__builtin_s390_vstrcb:
1278 case SystemZ::BI__builtin_s390_vstrch:
1279 case SystemZ::BI__builtin_s390_vstrcf:
1280 case SystemZ::BI__builtin_s390_vstrczb:
1281 case SystemZ::BI__builtin_s390_vstrczh:
1282 case SystemZ::BI__builtin_s390_vstrczf:
1283 case SystemZ::BI__builtin_s390_vstrcbs:
1284 case SystemZ::BI__builtin_s390_vstrchs:
1285 case SystemZ::BI__builtin_s390_vstrcfs:
1286 case SystemZ::BI__builtin_s390_vstrczbs:
1287 case SystemZ::BI__builtin_s390_vstrczhs:
1288 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1289 }
1290 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001291}
1292
Craig Topper5ba2c502015-11-07 08:08:31 +00001293/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1294/// This checks that the target supports __builtin_cpu_supports and
1295/// that the string argument is constant and valid.
1296static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1297 Expr *Arg = TheCall->getArg(0);
1298
1299 // Check if the argument is a string literal.
1300 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1301 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1302 << Arg->getSourceRange();
1303
1304 // Check the contents of the string.
1305 StringRef Feature =
1306 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1307 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1308 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1309 << Arg->getSourceRange();
1310 return false;
1311}
1312
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001313bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001314 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001315 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001316 default: return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001317 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001318 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001319 case X86::BI__builtin_ms_va_start:
1320 return SemaBuiltinMSVAStart(TheCall);
Craig Topperdd84ec52014-12-27 07:00:08 +00001321 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +00001322 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001323 case X86::BI__builtin_ia32_vpermil2pd:
1324 case X86::BI__builtin_ia32_vpermil2pd256:
1325 case X86::BI__builtin_ia32_vpermil2ps:
1326 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +00001327 case X86::BI__builtin_ia32_cmpb128_mask:
1328 case X86::BI__builtin_ia32_cmpw128_mask:
1329 case X86::BI__builtin_ia32_cmpd128_mask:
1330 case X86::BI__builtin_ia32_cmpq128_mask:
1331 case X86::BI__builtin_ia32_cmpb256_mask:
1332 case X86::BI__builtin_ia32_cmpw256_mask:
1333 case X86::BI__builtin_ia32_cmpd256_mask:
1334 case X86::BI__builtin_ia32_cmpq256_mask:
1335 case X86::BI__builtin_ia32_cmpb512_mask:
1336 case X86::BI__builtin_ia32_cmpw512_mask:
1337 case X86::BI__builtin_ia32_cmpd512_mask:
1338 case X86::BI__builtin_ia32_cmpq512_mask:
1339 case X86::BI__builtin_ia32_ucmpb128_mask:
1340 case X86::BI__builtin_ia32_ucmpw128_mask:
1341 case X86::BI__builtin_ia32_ucmpd128_mask:
1342 case X86::BI__builtin_ia32_ucmpq128_mask:
1343 case X86::BI__builtin_ia32_ucmpb256_mask:
1344 case X86::BI__builtin_ia32_ucmpw256_mask:
1345 case X86::BI__builtin_ia32_ucmpd256_mask:
1346 case X86::BI__builtin_ia32_ucmpq256_mask:
1347 case X86::BI__builtin_ia32_ucmpb512_mask:
1348 case X86::BI__builtin_ia32_ucmpw512_mask:
1349 case X86::BI__builtin_ia32_ucmpd512_mask:
1350 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +00001351 case X86::BI__builtin_ia32_roundps:
1352 case X86::BI__builtin_ia32_roundpd:
1353 case X86::BI__builtin_ia32_roundps256:
1354 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1355 case X86::BI__builtin_ia32_roundss:
1356 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1357 case X86::BI__builtin_ia32_cmpps:
1358 case X86::BI__builtin_ia32_cmpss:
1359 case X86::BI__builtin_ia32_cmppd:
1360 case X86::BI__builtin_ia32_cmpsd:
1361 case X86::BI__builtin_ia32_cmpps256:
1362 case X86::BI__builtin_ia32_cmppd256:
1363 case X86::BI__builtin_ia32_cmpps512_mask:
1364 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001365 case X86::BI__builtin_ia32_vpcomub:
1366 case X86::BI__builtin_ia32_vpcomuw:
1367 case X86::BI__builtin_ia32_vpcomud:
1368 case X86::BI__builtin_ia32_vpcomuq:
1369 case X86::BI__builtin_ia32_vpcomb:
1370 case X86::BI__builtin_ia32_vpcomw:
1371 case X86::BI__builtin_ia32_vpcomd:
1372 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001373 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001374 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001375}
1376
Richard Smith55ce3522012-06-25 20:30:08 +00001377/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1378/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1379/// Returns true when the format fits the function and the FormatStringInfo has
1380/// been populated.
1381bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1382 FormatStringInfo *FSI) {
1383 FSI->HasVAListArg = Format->getFirstArg() == 0;
1384 FSI->FormatIdx = Format->getFormatIdx() - 1;
1385 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001386
Richard Smith55ce3522012-06-25 20:30:08 +00001387 // The way the format attribute works in GCC, the implicit this argument
1388 // of member functions is counted. However, it doesn't appear in our own
1389 // lists, so decrement format_idx in that case.
1390 if (IsCXXMember) {
1391 if(FSI->FormatIdx == 0)
1392 return false;
1393 --FSI->FormatIdx;
1394 if (FSI->FirstDataArg != 0)
1395 --FSI->FirstDataArg;
1396 }
1397 return true;
1398}
Mike Stump11289f42009-09-09 15:08:12 +00001399
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001400/// Checks if a the given expression evaluates to null.
1401///
1402/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001403static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001404 // If the expression has non-null type, it doesn't evaluate to null.
1405 if (auto nullability
1406 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1407 if (*nullability == NullabilityKind::NonNull)
1408 return false;
1409 }
1410
Ted Kremeneka146db32014-01-17 06:24:47 +00001411 // As a special case, transparent unions initialized with zero are
1412 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001413 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001414 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1415 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001416 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001417 if (const InitListExpr *ILE =
1418 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001419 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001420 }
1421
1422 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001423 return (!Expr->isValueDependent() &&
1424 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1425 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001426}
1427
1428static void CheckNonNullArgument(Sema &S,
1429 const Expr *ArgExpr,
1430 SourceLocation CallSiteLoc) {
1431 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001432 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1433 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001434}
1435
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001436bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1437 FormatStringInfo FSI;
1438 if ((GetFormatStringType(Format) == FST_NSString) &&
1439 getFormatStringInfo(Format, false, &FSI)) {
1440 Idx = FSI.FormatIdx;
1441 return true;
1442 }
1443 return false;
1444}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001445/// \brief Diagnose use of %s directive in an NSString which is being passed
1446/// as formatting string to formatting method.
1447static void
1448DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1449 const NamedDecl *FDecl,
1450 Expr **Args,
1451 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001452 unsigned Idx = 0;
1453 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001454 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1455 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001456 Idx = 2;
1457 Format = true;
1458 }
1459 else
1460 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1461 if (S.GetFormatNSStringIdx(I, Idx)) {
1462 Format = true;
1463 break;
1464 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001465 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001466 if (!Format || NumArgs <= Idx)
1467 return;
1468 const Expr *FormatExpr = Args[Idx];
1469 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1470 FormatExpr = CSCE->getSubExpr();
1471 const StringLiteral *FormatString;
1472 if (const ObjCStringLiteral *OSL =
1473 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1474 FormatString = OSL->getString();
1475 else
1476 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1477 if (!FormatString)
1478 return;
1479 if (S.FormatStringHasSArg(FormatString)) {
1480 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1481 << "%s" << 1 << 1;
1482 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1483 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001484 }
1485}
1486
Douglas Gregorb4866e82015-06-19 18:13:19 +00001487/// Determine whether the given type has a non-null nullability annotation.
1488static bool isNonNullType(ASTContext &ctx, QualType type) {
1489 if (auto nullability = type->getNullability(ctx))
1490 return *nullability == NullabilityKind::NonNull;
1491
1492 return false;
1493}
1494
Ted Kremenek2bc73332014-01-17 06:24:43 +00001495static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001496 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001497 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001498 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001499 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001500 assert((FDecl || Proto) && "Need a function declaration or prototype");
1501
Ted Kremenek9aedc152014-01-17 06:24:56 +00001502 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001503 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001504 if (FDecl) {
1505 // Handle the nonnull attribute on the function/method declaration itself.
1506 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1507 if (!NonNull->args_size()) {
1508 // Easy case: all pointer arguments are nonnull.
1509 for (const auto *Arg : Args)
1510 if (S.isValidPointerAttrType(Arg->getType()))
1511 CheckNonNullArgument(S, Arg, CallSiteLoc);
1512 return;
1513 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001514
Douglas Gregorb4866e82015-06-19 18:13:19 +00001515 for (unsigned Val : NonNull->args()) {
1516 if (Val >= Args.size())
1517 continue;
1518 if (NonNullArgs.empty())
1519 NonNullArgs.resize(Args.size());
1520 NonNullArgs.set(Val);
1521 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001522 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001523 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001524
Douglas Gregorb4866e82015-06-19 18:13:19 +00001525 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1526 // Handle the nonnull attribute on the parameters of the
1527 // function/method.
1528 ArrayRef<ParmVarDecl*> parms;
1529 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1530 parms = FD->parameters();
1531 else
1532 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1533
1534 unsigned ParamIndex = 0;
1535 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1536 I != E; ++I, ++ParamIndex) {
1537 const ParmVarDecl *PVD = *I;
1538 if (PVD->hasAttr<NonNullAttr>() ||
1539 isNonNullType(S.Context, PVD->getType())) {
1540 if (NonNullArgs.empty())
1541 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001542
Douglas Gregorb4866e82015-06-19 18:13:19 +00001543 NonNullArgs.set(ParamIndex);
1544 }
1545 }
1546 } else {
1547 // If we have a non-function, non-method declaration but no
1548 // function prototype, try to dig out the function prototype.
1549 if (!Proto) {
1550 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1551 QualType type = VD->getType().getNonReferenceType();
1552 if (auto pointerType = type->getAs<PointerType>())
1553 type = pointerType->getPointeeType();
1554 else if (auto blockType = type->getAs<BlockPointerType>())
1555 type = blockType->getPointeeType();
1556 // FIXME: data member pointers?
1557
1558 // Dig out the function prototype, if there is one.
1559 Proto = type->getAs<FunctionProtoType>();
1560 }
1561 }
1562
1563 // Fill in non-null argument information from the nullability
1564 // information on the parameter types (if we have them).
1565 if (Proto) {
1566 unsigned Index = 0;
1567 for (auto paramType : Proto->getParamTypes()) {
1568 if (isNonNullType(S.Context, paramType)) {
1569 if (NonNullArgs.empty())
1570 NonNullArgs.resize(Args.size());
1571
1572 NonNullArgs.set(Index);
1573 }
1574
1575 ++Index;
1576 }
1577 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001578 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001579
Douglas Gregorb4866e82015-06-19 18:13:19 +00001580 // Check for non-null arguments.
1581 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1582 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001583 if (NonNullArgs[ArgIndex])
1584 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001585 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001586}
1587
Richard Smith55ce3522012-06-25 20:30:08 +00001588/// Handles the checks for format strings, non-POD arguments to vararg
1589/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001590void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1591 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001592 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001593 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001594 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001595 if (CurContext->isDependentContext())
1596 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001597
Ted Kremenekb8176da2010-09-09 04:33:05 +00001598 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001599 llvm::SmallBitVector CheckedVarArgs;
1600 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001601 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001602 // Only create vector if there are format attributes.
1603 CheckedVarArgs.resize(Args.size());
1604
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001605 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001606 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001607 }
Richard Smithd7293d72013-08-05 18:49:43 +00001608 }
Richard Smith55ce3522012-06-25 20:30:08 +00001609
1610 // Refuse POD arguments that weren't caught by the format string
1611 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001612 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001613 unsigned NumParams = Proto ? Proto->getNumParams()
1614 : FDecl && isa<FunctionDecl>(FDecl)
1615 ? cast<FunctionDecl>(FDecl)->getNumParams()
1616 : FDecl && isa<ObjCMethodDecl>(FDecl)
1617 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1618 : 0;
1619
Alp Toker9cacbab2014-01-20 20:26:09 +00001620 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001621 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001622 if (const Expr *Arg = Args[ArgIdx]) {
1623 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1624 checkVariadicArgument(Arg, CallType);
1625 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001626 }
Richard Smithd7293d72013-08-05 18:49:43 +00001627 }
Mike Stump11289f42009-09-09 15:08:12 +00001628
Douglas Gregorb4866e82015-06-19 18:13:19 +00001629 if (FDecl || Proto) {
1630 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001631
Richard Trieu41bc0992013-06-22 00:20:41 +00001632 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001633 if (FDecl) {
1634 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1635 CheckArgumentWithTypeTag(I, Args.data());
1636 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001637 }
Richard Smith55ce3522012-06-25 20:30:08 +00001638}
1639
1640/// CheckConstructorCall - Check a constructor call for correctness and safety
1641/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001642void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1643 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001644 const FunctionProtoType *Proto,
1645 SourceLocation Loc) {
1646 VariadicCallType CallType =
1647 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001648 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1649 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001650}
1651
1652/// CheckFunctionCall - Check a direct function call for various correctness
1653/// and safety properties not strictly enforced by the C type system.
1654bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1655 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001656 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1657 isa<CXXMethodDecl>(FDecl);
1658 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1659 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001660 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1661 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001662 Expr** Args = TheCall->getArgs();
1663 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001664 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001665 // If this is a call to a member operator, hide the first argument
1666 // from checkCall.
1667 // FIXME: Our choice of AST representation here is less than ideal.
1668 ++Args;
1669 --NumArgs;
1670 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001671 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001672 IsMemberFunction, TheCall->getRParenLoc(),
1673 TheCall->getCallee()->getSourceRange(), CallType);
1674
1675 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1676 // None of the checks below are needed for functions that don't have
1677 // simple names (e.g., C++ conversion functions).
1678 if (!FnInfo)
1679 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001680
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001681 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001682 if (getLangOpts().ObjC1)
1683 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001684
Anna Zaks22122702012-01-17 00:37:07 +00001685 unsigned CMId = FDecl->getMemoryFunctionKind();
1686 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001687 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001688
Anna Zaks201d4892012-01-13 21:52:01 +00001689 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001690 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001691 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001692 else if (CMId == Builtin::BIstrncat)
1693 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001694 else
Anna Zaks22122702012-01-17 00:37:07 +00001695 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001696
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001697 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001698}
1699
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001700bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001701 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001702 VariadicCallType CallType =
1703 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001704
Douglas Gregorb4866e82015-06-19 18:13:19 +00001705 checkCall(Method, nullptr, Args,
1706 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1707 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001708
1709 return false;
1710}
1711
Richard Trieu664c4c62013-06-20 21:03:13 +00001712bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1713 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001714 QualType Ty;
1715 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001716 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001717 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001718 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001719 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001720 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001721
Douglas Gregorb4866e82015-06-19 18:13:19 +00001722 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1723 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001724 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001725
Richard Trieu664c4c62013-06-20 21:03:13 +00001726 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001727 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001728 CallType = VariadicDoesNotApply;
1729 } else if (Ty->isBlockPointerType()) {
1730 CallType = VariadicBlock;
1731 } else { // Ty->isFunctionPointerType()
1732 CallType = VariadicFunction;
1733 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001734
Douglas Gregorb4866e82015-06-19 18:13:19 +00001735 checkCall(NDecl, Proto,
1736 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1737 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001738 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001739
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001740 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001741}
1742
Richard Trieu41bc0992013-06-22 00:20:41 +00001743/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1744/// such as function pointers returned from functions.
1745bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001746 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001747 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001748 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001749 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001750 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001751 TheCall->getCallee()->getSourceRange(), CallType);
1752
1753 return false;
1754}
1755
Tim Northovere94a34c2014-03-11 10:49:14 +00001756static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1757 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1758 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1759 return false;
1760
1761 switch (Op) {
1762 case AtomicExpr::AO__c11_atomic_init:
1763 llvm_unreachable("There is no ordering argument for an init");
1764
1765 case AtomicExpr::AO__c11_atomic_load:
1766 case AtomicExpr::AO__atomic_load_n:
1767 case AtomicExpr::AO__atomic_load:
1768 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1769 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1770
1771 case AtomicExpr::AO__c11_atomic_store:
1772 case AtomicExpr::AO__atomic_store:
1773 case AtomicExpr::AO__atomic_store_n:
1774 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1775 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1776 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1777
1778 default:
1779 return true;
1780 }
1781}
1782
Richard Smithfeea8832012-04-12 05:08:17 +00001783ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1784 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001785 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1786 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001787
Richard Smithfeea8832012-04-12 05:08:17 +00001788 // All these operations take one of the following forms:
1789 enum {
1790 // C __c11_atomic_init(A *, C)
1791 Init,
1792 // C __c11_atomic_load(A *, int)
1793 Load,
1794 // void __atomic_load(A *, CP, int)
1795 Copy,
1796 // C __c11_atomic_add(A *, M, int)
1797 Arithmetic,
1798 // C __atomic_exchange_n(A *, CP, int)
1799 Xchg,
1800 // void __atomic_exchange(A *, C *, CP, int)
1801 GNUXchg,
1802 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1803 C11CmpXchg,
1804 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1805 GNUCmpXchg
1806 } Form = Init;
1807 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1808 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1809 // where:
1810 // C is an appropriate type,
1811 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1812 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1813 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1814 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001815
Gabor Horvath98bd0982015-03-16 09:59:54 +00001816 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1817 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1818 AtomicExpr::AO__atomic_load,
1819 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001820 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1821 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1822 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1823 Op == AtomicExpr::AO__atomic_store_n ||
1824 Op == AtomicExpr::AO__atomic_exchange_n ||
1825 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1826 bool IsAddSub = false;
1827
1828 switch (Op) {
1829 case AtomicExpr::AO__c11_atomic_init:
1830 Form = Init;
1831 break;
1832
1833 case AtomicExpr::AO__c11_atomic_load:
1834 case AtomicExpr::AO__atomic_load_n:
1835 Form = Load;
1836 break;
1837
1838 case AtomicExpr::AO__c11_atomic_store:
1839 case AtomicExpr::AO__atomic_load:
1840 case AtomicExpr::AO__atomic_store:
1841 case AtomicExpr::AO__atomic_store_n:
1842 Form = Copy;
1843 break;
1844
1845 case AtomicExpr::AO__c11_atomic_fetch_add:
1846 case AtomicExpr::AO__c11_atomic_fetch_sub:
1847 case AtomicExpr::AO__atomic_fetch_add:
1848 case AtomicExpr::AO__atomic_fetch_sub:
1849 case AtomicExpr::AO__atomic_add_fetch:
1850 case AtomicExpr::AO__atomic_sub_fetch:
1851 IsAddSub = true;
1852 // Fall through.
1853 case AtomicExpr::AO__c11_atomic_fetch_and:
1854 case AtomicExpr::AO__c11_atomic_fetch_or:
1855 case AtomicExpr::AO__c11_atomic_fetch_xor:
1856 case AtomicExpr::AO__atomic_fetch_and:
1857 case AtomicExpr::AO__atomic_fetch_or:
1858 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001859 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001860 case AtomicExpr::AO__atomic_and_fetch:
1861 case AtomicExpr::AO__atomic_or_fetch:
1862 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001863 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001864 Form = Arithmetic;
1865 break;
1866
1867 case AtomicExpr::AO__c11_atomic_exchange:
1868 case AtomicExpr::AO__atomic_exchange_n:
1869 Form = Xchg;
1870 break;
1871
1872 case AtomicExpr::AO__atomic_exchange:
1873 Form = GNUXchg;
1874 break;
1875
1876 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1877 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1878 Form = C11CmpXchg;
1879 break;
1880
1881 case AtomicExpr::AO__atomic_compare_exchange:
1882 case AtomicExpr::AO__atomic_compare_exchange_n:
1883 Form = GNUCmpXchg;
1884 break;
1885 }
1886
1887 // Check we have the right number of arguments.
1888 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001889 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001890 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001891 << TheCall->getCallee()->getSourceRange();
1892 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001893 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1894 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001895 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001896 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001897 << TheCall->getCallee()->getSourceRange();
1898 return ExprError();
1899 }
1900
Richard Smithfeea8832012-04-12 05:08:17 +00001901 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001902 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001903 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1904 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1905 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001906 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001907 << Ptr->getType() << Ptr->getSourceRange();
1908 return ExprError();
1909 }
1910
Richard Smithfeea8832012-04-12 05:08:17 +00001911 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1912 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1913 QualType ValType = AtomTy; // 'C'
1914 if (IsC11) {
1915 if (!AtomTy->isAtomicType()) {
1916 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1917 << Ptr->getType() << Ptr->getSourceRange();
1918 return ExprError();
1919 }
Richard Smithe00921a2012-09-15 06:09:58 +00001920 if (AtomTy.isConstQualified()) {
1921 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1922 << Ptr->getType() << Ptr->getSourceRange();
1923 return ExprError();
1924 }
Richard Smithfeea8832012-04-12 05:08:17 +00001925 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001926 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1927 if (ValType.isConstQualified()) {
1928 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1929 << Ptr->getType() << Ptr->getSourceRange();
1930 return ExprError();
1931 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001932 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001933
Richard Smithfeea8832012-04-12 05:08:17 +00001934 // For an arithmetic operation, the implied arithmetic must be well-formed.
1935 if (Form == Arithmetic) {
1936 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1937 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1938 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1939 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1940 return ExprError();
1941 }
1942 if (!IsAddSub && !ValType->isIntegerType()) {
1943 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1944 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1945 return ExprError();
1946 }
David Majnemere85cff82015-01-28 05:48:06 +00001947 if (IsC11 && ValType->isPointerType() &&
1948 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1949 diag::err_incomplete_type)) {
1950 return ExprError();
1951 }
Richard Smithfeea8832012-04-12 05:08:17 +00001952 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1953 // For __atomic_*_n operations, the value type must be a scalar integral or
1954 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001955 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001956 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1957 return ExprError();
1958 }
1959
Eli Friedmanaa769812013-09-11 03:49:34 +00001960 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1961 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001962 // For GNU atomics, require a trivially-copyable type. This is not part of
1963 // the GNU atomics specification, but we enforce it for sanity.
1964 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001965 << Ptr->getType() << Ptr->getSourceRange();
1966 return ExprError();
1967 }
1968
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001969 switch (ValType.getObjCLifetime()) {
1970 case Qualifiers::OCL_None:
1971 case Qualifiers::OCL_ExplicitNone:
1972 // okay
1973 break;
1974
1975 case Qualifiers::OCL_Weak:
1976 case Qualifiers::OCL_Strong:
1977 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001978 // FIXME: Can this happen? By this point, ValType should be known
1979 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001980 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1981 << ValType << Ptr->getSourceRange();
1982 return ExprError();
1983 }
1984
David Majnemerc6eb6502015-06-03 00:26:35 +00001985 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
1986 // volatile-ness of the pointee-type inject itself into the result or the
1987 // other operands.
1988 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001989 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001990 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001991 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001992 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001993 ResultType = Context.BoolTy;
1994
Richard Smithfeea8832012-04-12 05:08:17 +00001995 // The type of a parameter passed 'by value'. In the GNU atomics, such
1996 // arguments are actually passed as pointers.
1997 QualType ByValType = ValType; // 'CP'
1998 if (!IsC11 && !IsN)
1999 ByValType = Ptr->getType();
2000
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002001 // FIXME: __atomic_load allows the first argument to be a a pointer to const
2002 // but not the second argument. We need to manually remove possible const
2003 // qualifiers.
2004
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002005 // The first argument --- the pointer --- has a fixed type; we
2006 // deduce the types of the rest of the arguments accordingly. Walk
2007 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002008 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002009 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002010 if (i < NumVals[Form] + 1) {
2011 switch (i) {
2012 case 1:
2013 // The second argument is the non-atomic operand. For arithmetic, this
2014 // is always passed by value, and for a compare_exchange it is always
2015 // passed by address. For the rest, GNU uses by-address and C11 uses
2016 // by-value.
2017 assert(Form != Load);
2018 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2019 Ty = ValType;
2020 else if (Form == Copy || Form == Xchg)
2021 Ty = ByValType;
2022 else if (Form == Arithmetic)
2023 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002024 else {
2025 Expr *ValArg = TheCall->getArg(i);
2026 unsigned AS = 0;
2027 // Keep address space of non-atomic pointer type.
2028 if (const PointerType *PtrTy =
2029 ValArg->getType()->getAs<PointerType>()) {
2030 AS = PtrTy->getPointeeType().getAddressSpace();
2031 }
2032 Ty = Context.getPointerType(
2033 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2034 }
Richard Smithfeea8832012-04-12 05:08:17 +00002035 break;
2036 case 2:
2037 // The third argument to compare_exchange / GNU exchange is a
2038 // (pointer to a) desired value.
2039 Ty = ByValType;
2040 break;
2041 case 3:
2042 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2043 Ty = Context.BoolTy;
2044 break;
2045 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002046 } else {
2047 // The order(s) are always converted to int.
2048 Ty = Context.IntTy;
2049 }
Richard Smithfeea8832012-04-12 05:08:17 +00002050
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002051 InitializedEntity Entity =
2052 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002053 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002054 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2055 if (Arg.isInvalid())
2056 return true;
2057 TheCall->setArg(i, Arg.get());
2058 }
2059
Richard Smithfeea8832012-04-12 05:08:17 +00002060 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002061 SmallVector<Expr*, 5> SubExprs;
2062 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002063 switch (Form) {
2064 case Init:
2065 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002066 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002067 break;
2068 case Load:
2069 SubExprs.push_back(TheCall->getArg(1)); // Order
2070 break;
2071 case Copy:
2072 case Arithmetic:
2073 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002074 SubExprs.push_back(TheCall->getArg(2)); // Order
2075 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002076 break;
2077 case GNUXchg:
2078 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2079 SubExprs.push_back(TheCall->getArg(3)); // Order
2080 SubExprs.push_back(TheCall->getArg(1)); // Val1
2081 SubExprs.push_back(TheCall->getArg(2)); // Val2
2082 break;
2083 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002084 SubExprs.push_back(TheCall->getArg(3)); // Order
2085 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002086 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002087 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002088 break;
2089 case GNUCmpXchg:
2090 SubExprs.push_back(TheCall->getArg(4)); // Order
2091 SubExprs.push_back(TheCall->getArg(1)); // Val1
2092 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2093 SubExprs.push_back(TheCall->getArg(2)); // Val2
2094 SubExprs.push_back(TheCall->getArg(3)); // Weak
2095 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002096 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002097
2098 if (SubExprs.size() >= 2 && Form != Init) {
2099 llvm::APSInt Result(32);
2100 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2101 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002102 Diag(SubExprs[1]->getLocStart(),
2103 diag::warn_atomic_op_has_invalid_memory_order)
2104 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002105 }
2106
Fariborz Jahanian615de762013-05-28 17:37:39 +00002107 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2108 SubExprs, ResultType, Op,
2109 TheCall->getRParenLoc());
2110
2111 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2112 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2113 Context.AtomicUsesUnsupportedLibcall(AE))
2114 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2115 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002116
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002117 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002118}
2119
2120
John McCall29ad95b2011-08-27 01:09:30 +00002121/// checkBuiltinArgument - Given a call to a builtin function, perform
2122/// normal type-checking on the given argument, updating the call in
2123/// place. This is useful when a builtin function requires custom
2124/// type-checking for some of its arguments but not necessarily all of
2125/// them.
2126///
2127/// Returns true on error.
2128static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2129 FunctionDecl *Fn = E->getDirectCallee();
2130 assert(Fn && "builtin call without direct callee!");
2131
2132 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2133 InitializedEntity Entity =
2134 InitializedEntity::InitializeParameter(S.Context, Param);
2135
2136 ExprResult Arg = E->getArg(0);
2137 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2138 if (Arg.isInvalid())
2139 return true;
2140
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002141 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002142 return false;
2143}
2144
Chris Lattnerdc046542009-05-08 06:58:22 +00002145/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2146/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2147/// type of its first argument. The main ActOnCallExpr routines have already
2148/// promoted the types of arguments because all of these calls are prototyped as
2149/// void(...).
2150///
2151/// This function goes through and does final semantic checking for these
2152/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002153ExprResult
2154Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002155 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002156 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2157 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2158
2159 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002160 if (TheCall->getNumArgs() < 1) {
2161 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2162 << 0 << 1 << TheCall->getNumArgs()
2163 << TheCall->getCallee()->getSourceRange();
2164 return ExprError();
2165 }
Mike Stump11289f42009-09-09 15:08:12 +00002166
Chris Lattnerdc046542009-05-08 06:58:22 +00002167 // Inspect the first argument of the atomic builtin. This should always be
2168 // a pointer type, whose element is an integral scalar or pointer type.
2169 // Because it is a pointer type, we don't have to worry about any implicit
2170 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002171 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002172 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002173 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2174 if (FirstArgResult.isInvalid())
2175 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002176 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002177 TheCall->setArg(0, FirstArg);
2178
John McCall31168b02011-06-15 23:02:42 +00002179 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2180 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002181 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2182 << FirstArg->getType() << FirstArg->getSourceRange();
2183 return ExprError();
2184 }
Mike Stump11289f42009-09-09 15:08:12 +00002185
John McCall31168b02011-06-15 23:02:42 +00002186 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002187 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002188 !ValType->isBlockPointerType()) {
2189 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2190 << FirstArg->getType() << FirstArg->getSourceRange();
2191 return ExprError();
2192 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002193
John McCall31168b02011-06-15 23:02:42 +00002194 switch (ValType.getObjCLifetime()) {
2195 case Qualifiers::OCL_None:
2196 case Qualifiers::OCL_ExplicitNone:
2197 // okay
2198 break;
2199
2200 case Qualifiers::OCL_Weak:
2201 case Qualifiers::OCL_Strong:
2202 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002203 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002204 << ValType << FirstArg->getSourceRange();
2205 return ExprError();
2206 }
2207
John McCallb50451a2011-10-05 07:41:44 +00002208 // Strip any qualifiers off ValType.
2209 ValType = ValType.getUnqualifiedType();
2210
Chandler Carruth3973af72010-07-18 20:54:12 +00002211 // The majority of builtins return a value, but a few have special return
2212 // types, so allow them to override appropriately below.
2213 QualType ResultType = ValType;
2214
Chris Lattnerdc046542009-05-08 06:58:22 +00002215 // We need to figure out which concrete builtin this maps onto. For example,
2216 // __sync_fetch_and_add with a 2 byte object turns into
2217 // __sync_fetch_and_add_2.
2218#define BUILTIN_ROW(x) \
2219 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2220 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002221
Chris Lattnerdc046542009-05-08 06:58:22 +00002222 static const unsigned BuiltinIndices[][5] = {
2223 BUILTIN_ROW(__sync_fetch_and_add),
2224 BUILTIN_ROW(__sync_fetch_and_sub),
2225 BUILTIN_ROW(__sync_fetch_and_or),
2226 BUILTIN_ROW(__sync_fetch_and_and),
2227 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002228 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002229
Chris Lattnerdc046542009-05-08 06:58:22 +00002230 BUILTIN_ROW(__sync_add_and_fetch),
2231 BUILTIN_ROW(__sync_sub_and_fetch),
2232 BUILTIN_ROW(__sync_and_and_fetch),
2233 BUILTIN_ROW(__sync_or_and_fetch),
2234 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002235 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002236
Chris Lattnerdc046542009-05-08 06:58:22 +00002237 BUILTIN_ROW(__sync_val_compare_and_swap),
2238 BUILTIN_ROW(__sync_bool_compare_and_swap),
2239 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002240 BUILTIN_ROW(__sync_lock_release),
2241 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002242 };
Mike Stump11289f42009-09-09 15:08:12 +00002243#undef BUILTIN_ROW
2244
Chris Lattnerdc046542009-05-08 06:58:22 +00002245 // Determine the index of the size.
2246 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002247 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002248 case 1: SizeIndex = 0; break;
2249 case 2: SizeIndex = 1; break;
2250 case 4: SizeIndex = 2; break;
2251 case 8: SizeIndex = 3; break;
2252 case 16: SizeIndex = 4; break;
2253 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002254 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2255 << FirstArg->getType() << FirstArg->getSourceRange();
2256 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002257 }
Mike Stump11289f42009-09-09 15:08:12 +00002258
Chris Lattnerdc046542009-05-08 06:58:22 +00002259 // Each of these builtins has one pointer argument, followed by some number of
2260 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2261 // that we ignore. Find out which row of BuiltinIndices to read from as well
2262 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002263 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002264 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002265 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002266 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002267 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002268 case Builtin::BI__sync_fetch_and_add:
2269 case Builtin::BI__sync_fetch_and_add_1:
2270 case Builtin::BI__sync_fetch_and_add_2:
2271 case Builtin::BI__sync_fetch_and_add_4:
2272 case Builtin::BI__sync_fetch_and_add_8:
2273 case Builtin::BI__sync_fetch_and_add_16:
2274 BuiltinIndex = 0;
2275 break;
2276
2277 case Builtin::BI__sync_fetch_and_sub:
2278 case Builtin::BI__sync_fetch_and_sub_1:
2279 case Builtin::BI__sync_fetch_and_sub_2:
2280 case Builtin::BI__sync_fetch_and_sub_4:
2281 case Builtin::BI__sync_fetch_and_sub_8:
2282 case Builtin::BI__sync_fetch_and_sub_16:
2283 BuiltinIndex = 1;
2284 break;
2285
2286 case Builtin::BI__sync_fetch_and_or:
2287 case Builtin::BI__sync_fetch_and_or_1:
2288 case Builtin::BI__sync_fetch_and_or_2:
2289 case Builtin::BI__sync_fetch_and_or_4:
2290 case Builtin::BI__sync_fetch_and_or_8:
2291 case Builtin::BI__sync_fetch_and_or_16:
2292 BuiltinIndex = 2;
2293 break;
2294
2295 case Builtin::BI__sync_fetch_and_and:
2296 case Builtin::BI__sync_fetch_and_and_1:
2297 case Builtin::BI__sync_fetch_and_and_2:
2298 case Builtin::BI__sync_fetch_and_and_4:
2299 case Builtin::BI__sync_fetch_and_and_8:
2300 case Builtin::BI__sync_fetch_and_and_16:
2301 BuiltinIndex = 3;
2302 break;
Mike Stump11289f42009-09-09 15:08:12 +00002303
Douglas Gregor73722482011-11-28 16:30:08 +00002304 case Builtin::BI__sync_fetch_and_xor:
2305 case Builtin::BI__sync_fetch_and_xor_1:
2306 case Builtin::BI__sync_fetch_and_xor_2:
2307 case Builtin::BI__sync_fetch_and_xor_4:
2308 case Builtin::BI__sync_fetch_and_xor_8:
2309 case Builtin::BI__sync_fetch_and_xor_16:
2310 BuiltinIndex = 4;
2311 break;
2312
Hal Finkeld2208b52014-10-02 20:53:50 +00002313 case Builtin::BI__sync_fetch_and_nand:
2314 case Builtin::BI__sync_fetch_and_nand_1:
2315 case Builtin::BI__sync_fetch_and_nand_2:
2316 case Builtin::BI__sync_fetch_and_nand_4:
2317 case Builtin::BI__sync_fetch_and_nand_8:
2318 case Builtin::BI__sync_fetch_and_nand_16:
2319 BuiltinIndex = 5;
2320 WarnAboutSemanticsChange = true;
2321 break;
2322
Douglas Gregor73722482011-11-28 16:30:08 +00002323 case Builtin::BI__sync_add_and_fetch:
2324 case Builtin::BI__sync_add_and_fetch_1:
2325 case Builtin::BI__sync_add_and_fetch_2:
2326 case Builtin::BI__sync_add_and_fetch_4:
2327 case Builtin::BI__sync_add_and_fetch_8:
2328 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002329 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002330 break;
2331
2332 case Builtin::BI__sync_sub_and_fetch:
2333 case Builtin::BI__sync_sub_and_fetch_1:
2334 case Builtin::BI__sync_sub_and_fetch_2:
2335 case Builtin::BI__sync_sub_and_fetch_4:
2336 case Builtin::BI__sync_sub_and_fetch_8:
2337 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002338 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002339 break;
2340
2341 case Builtin::BI__sync_and_and_fetch:
2342 case Builtin::BI__sync_and_and_fetch_1:
2343 case Builtin::BI__sync_and_and_fetch_2:
2344 case Builtin::BI__sync_and_and_fetch_4:
2345 case Builtin::BI__sync_and_and_fetch_8:
2346 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002347 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002348 break;
2349
2350 case Builtin::BI__sync_or_and_fetch:
2351 case Builtin::BI__sync_or_and_fetch_1:
2352 case Builtin::BI__sync_or_and_fetch_2:
2353 case Builtin::BI__sync_or_and_fetch_4:
2354 case Builtin::BI__sync_or_and_fetch_8:
2355 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002356 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002357 break;
2358
2359 case Builtin::BI__sync_xor_and_fetch:
2360 case Builtin::BI__sync_xor_and_fetch_1:
2361 case Builtin::BI__sync_xor_and_fetch_2:
2362 case Builtin::BI__sync_xor_and_fetch_4:
2363 case Builtin::BI__sync_xor_and_fetch_8:
2364 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002365 BuiltinIndex = 10;
2366 break;
2367
2368 case Builtin::BI__sync_nand_and_fetch:
2369 case Builtin::BI__sync_nand_and_fetch_1:
2370 case Builtin::BI__sync_nand_and_fetch_2:
2371 case Builtin::BI__sync_nand_and_fetch_4:
2372 case Builtin::BI__sync_nand_and_fetch_8:
2373 case Builtin::BI__sync_nand_and_fetch_16:
2374 BuiltinIndex = 11;
2375 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002376 break;
Mike Stump11289f42009-09-09 15:08:12 +00002377
Chris Lattnerdc046542009-05-08 06:58:22 +00002378 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002379 case Builtin::BI__sync_val_compare_and_swap_1:
2380 case Builtin::BI__sync_val_compare_and_swap_2:
2381 case Builtin::BI__sync_val_compare_and_swap_4:
2382 case Builtin::BI__sync_val_compare_and_swap_8:
2383 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002384 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002385 NumFixed = 2;
2386 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002387
Chris Lattnerdc046542009-05-08 06:58:22 +00002388 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002389 case Builtin::BI__sync_bool_compare_and_swap_1:
2390 case Builtin::BI__sync_bool_compare_and_swap_2:
2391 case Builtin::BI__sync_bool_compare_and_swap_4:
2392 case Builtin::BI__sync_bool_compare_and_swap_8:
2393 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002394 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002395 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002396 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002397 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002398
2399 case Builtin::BI__sync_lock_test_and_set:
2400 case Builtin::BI__sync_lock_test_and_set_1:
2401 case Builtin::BI__sync_lock_test_and_set_2:
2402 case Builtin::BI__sync_lock_test_and_set_4:
2403 case Builtin::BI__sync_lock_test_and_set_8:
2404 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002405 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002406 break;
2407
Chris Lattnerdc046542009-05-08 06:58:22 +00002408 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002409 case Builtin::BI__sync_lock_release_1:
2410 case Builtin::BI__sync_lock_release_2:
2411 case Builtin::BI__sync_lock_release_4:
2412 case Builtin::BI__sync_lock_release_8:
2413 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002414 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002415 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002416 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002417 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002418
2419 case Builtin::BI__sync_swap:
2420 case Builtin::BI__sync_swap_1:
2421 case Builtin::BI__sync_swap_2:
2422 case Builtin::BI__sync_swap_4:
2423 case Builtin::BI__sync_swap_8:
2424 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002425 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002426 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002427 }
Mike Stump11289f42009-09-09 15:08:12 +00002428
Chris Lattnerdc046542009-05-08 06:58:22 +00002429 // Now that we know how many fixed arguments we expect, first check that we
2430 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002431 if (TheCall->getNumArgs() < 1+NumFixed) {
2432 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2433 << 0 << 1+NumFixed << TheCall->getNumArgs()
2434 << TheCall->getCallee()->getSourceRange();
2435 return ExprError();
2436 }
Mike Stump11289f42009-09-09 15:08:12 +00002437
Hal Finkeld2208b52014-10-02 20:53:50 +00002438 if (WarnAboutSemanticsChange) {
2439 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2440 << TheCall->getCallee()->getSourceRange();
2441 }
2442
Chris Lattner5b9241b2009-05-08 15:36:58 +00002443 // Get the decl for the concrete builtin from this, we can tell what the
2444 // concrete integer type we should convert to is.
2445 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002446 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002447 FunctionDecl *NewBuiltinDecl;
2448 if (NewBuiltinID == BuiltinID)
2449 NewBuiltinDecl = FDecl;
2450 else {
2451 // Perform builtin lookup to avoid redeclaring it.
2452 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2453 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2454 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2455 assert(Res.getFoundDecl());
2456 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002457 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002458 return ExprError();
2459 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002460
John McCallcf142162010-08-07 06:22:56 +00002461 // The first argument --- the pointer --- has a fixed type; we
2462 // deduce the types of the rest of the arguments accordingly. Walk
2463 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002464 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002465 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002466
Chris Lattnerdc046542009-05-08 06:58:22 +00002467 // GCC does an implicit conversion to the pointer or integer ValType. This
2468 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002469 // Initialize the argument.
2470 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2471 ValType, /*consume*/ false);
2472 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002473 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002474 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002475
Chris Lattnerdc046542009-05-08 06:58:22 +00002476 // Okay, we have something that *can* be converted to the right type. Check
2477 // to see if there is a potentially weird extension going on here. This can
2478 // happen when you do an atomic operation on something like an char* and
2479 // pass in 42. The 42 gets converted to char. This is even more strange
2480 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002481 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002482 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002483 }
Mike Stump11289f42009-09-09 15:08:12 +00002484
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002485 ASTContext& Context = this->getASTContext();
2486
2487 // Create a new DeclRefExpr to refer to the new decl.
2488 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2489 Context,
2490 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002491 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002492 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002493 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002494 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002495 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002496 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002497
Chris Lattnerdc046542009-05-08 06:58:22 +00002498 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002499 // FIXME: This loses syntactic information.
2500 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2501 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2502 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002503 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002504
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002505 // Change the result type of the call to match the original value type. This
2506 // is arbitrary, but the codegen for these builtins ins design to handle it
2507 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002508 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002509
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002510 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002511}
2512
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002513/// SemaBuiltinNontemporalOverloaded - We have a call to
2514/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2515/// overloaded function based on the pointer type of its last argument.
2516///
2517/// This function goes through and does final semantic checking for these
2518/// builtins.
2519ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2520 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2521 DeclRefExpr *DRE =
2522 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2523 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2524 unsigned BuiltinID = FDecl->getBuiltinID();
2525 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2526 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2527 "Unexpected nontemporal load/store builtin!");
2528 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2529 unsigned numArgs = isStore ? 2 : 1;
2530
2531 // Ensure that we have the proper number of arguments.
2532 if (checkArgCount(*this, TheCall, numArgs))
2533 return ExprError();
2534
2535 // Inspect the last argument of the nontemporal builtin. This should always
2536 // be a pointer type, from which we imply the type of the memory access.
2537 // Because it is a pointer type, we don't have to worry about any implicit
2538 // casts here.
2539 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2540 ExprResult PointerArgResult =
2541 DefaultFunctionArrayLvalueConversion(PointerArg);
2542
2543 if (PointerArgResult.isInvalid())
2544 return ExprError();
2545 PointerArg = PointerArgResult.get();
2546 TheCall->setArg(numArgs - 1, PointerArg);
2547
2548 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2549 if (!pointerType) {
2550 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2551 << PointerArg->getType() << PointerArg->getSourceRange();
2552 return ExprError();
2553 }
2554
2555 QualType ValType = pointerType->getPointeeType();
2556
2557 // Strip any qualifiers off ValType.
2558 ValType = ValType.getUnqualifiedType();
2559 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2560 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2561 !ValType->isVectorType()) {
2562 Diag(DRE->getLocStart(),
2563 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2564 << PointerArg->getType() << PointerArg->getSourceRange();
2565 return ExprError();
2566 }
2567
2568 if (!isStore) {
2569 TheCall->setType(ValType);
2570 return TheCallResult;
2571 }
2572
2573 ExprResult ValArg = TheCall->getArg(0);
2574 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2575 Context, ValType, /*consume*/ false);
2576 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2577 if (ValArg.isInvalid())
2578 return ExprError();
2579
2580 TheCall->setArg(0, ValArg.get());
2581 TheCall->setType(Context.VoidTy);
2582 return TheCallResult;
2583}
2584
Chris Lattner6436fb62009-02-18 06:01:06 +00002585/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002586/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002587/// Note: It might also make sense to do the UTF-16 conversion here (would
2588/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002589bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002590 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002591 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2592
Douglas Gregorfb65e592011-07-27 05:40:30 +00002593 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002594 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2595 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002596 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002597 }
Mike Stump11289f42009-09-09 15:08:12 +00002598
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002599 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002600 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002601 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002602 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002603 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002604 UTF16 *ToPtr = &ToBuf[0];
2605
2606 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2607 &ToPtr, ToPtr + NumBytes,
2608 strictConversion);
2609 // Check for conversion failure.
2610 if (Result != conversionOK)
2611 Diag(Arg->getLocStart(),
2612 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2613 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002614 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002615}
2616
Charles Davisc7d5c942015-09-17 20:55:33 +00002617/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2618/// for validity. Emit an error and return true on failure; return false
2619/// on success.
2620bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002621 Expr *Fn = TheCall->getCallee();
2622 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002623 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002624 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002625 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2626 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002627 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002628 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002629 return true;
2630 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002631
2632 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002633 return Diag(TheCall->getLocEnd(),
2634 diag::err_typecheck_call_too_few_args_at_least)
2635 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002636 }
2637
John McCall29ad95b2011-08-27 01:09:30 +00002638 // Type-check the first argument normally.
2639 if (checkBuiltinArgument(*this, TheCall, 0))
2640 return true;
2641
Chris Lattnere202e6a2007-12-20 00:05:45 +00002642 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002643 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002644 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002645 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002646 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002647 else if (FunctionDecl *FD = getCurFunctionDecl())
2648 isVariadic = FD->isVariadic();
2649 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002650 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002651
Chris Lattnere202e6a2007-12-20 00:05:45 +00002652 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002653 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2654 return true;
2655 }
Mike Stump11289f42009-09-09 15:08:12 +00002656
Chris Lattner43be2e62007-12-19 23:59:04 +00002657 // Verify that the second argument to the builtin is the last argument of the
2658 // current function or method.
2659 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002660 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002661
Nico Weber9eea7642013-05-24 23:31:57 +00002662 // These are valid if SecondArgIsLastNamedArgument is false after the next
2663 // block.
2664 QualType Type;
2665 SourceLocation ParamLoc;
2666
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002667 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2668 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002669 // FIXME: This isn't correct for methods (results in bogus warning).
2670 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002671 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002672 if (CurBlock)
2673 LastArg = *(CurBlock->TheDecl->param_end()-1);
2674 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002675 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002676 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002677 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002678 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002679
2680 Type = PV->getType();
2681 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002682 }
2683 }
Mike Stump11289f42009-09-09 15:08:12 +00002684
Chris Lattner43be2e62007-12-19 23:59:04 +00002685 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002686 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002687 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002688 else if (Type->isReferenceType()) {
2689 Diag(Arg->getLocStart(),
2690 diag::warn_va_start_of_reference_type_is_undefined);
2691 Diag(ParamLoc, diag::note_parameter_type) << Type;
2692 }
2693
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002694 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002695 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002696}
Chris Lattner43be2e62007-12-19 23:59:04 +00002697
Charles Davisc7d5c942015-09-17 20:55:33 +00002698/// Check the arguments to '__builtin_va_start' for validity, and that
2699/// it was called from a function of the native ABI.
2700/// Emit an error and return true on failure; return false on success.
2701bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2702 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2703 // On x64 Windows, don't allow this in System V ABI functions.
2704 // (Yes, that means there's no corresponding way to support variadic
2705 // System V ABI functions on Windows.)
2706 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2707 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2708 clang::CallingConv CC = CC_C;
2709 if (const FunctionDecl *FD = getCurFunctionDecl())
2710 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2711 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2712 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2713 return Diag(TheCall->getCallee()->getLocStart(),
2714 diag::err_va_start_used_in_wrong_abi_function)
2715 << (OS != llvm::Triple::Win32);
2716 }
2717 return SemaBuiltinVAStartImpl(TheCall);
2718}
2719
2720/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2721/// it was called from a Win64 ABI function.
2722/// Emit an error and return true on failure; return false on success.
2723bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2724 // This only makes sense for x86-64.
2725 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2726 Expr *Callee = TheCall->getCallee();
2727 if (TT.getArch() != llvm::Triple::x86_64)
2728 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2729 // Don't allow this in System V ABI functions.
2730 clang::CallingConv CC = CC_C;
2731 if (const FunctionDecl *FD = getCurFunctionDecl())
2732 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2733 if (CC == CC_X86_64SysV ||
2734 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2735 return Diag(Callee->getLocStart(),
2736 diag::err_ms_va_start_used_in_sysv_function);
2737 return SemaBuiltinVAStartImpl(TheCall);
2738}
2739
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002740bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2741 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2742 // const char *named_addr);
2743
2744 Expr *Func = Call->getCallee();
2745
2746 if (Call->getNumArgs() < 3)
2747 return Diag(Call->getLocEnd(),
2748 diag::err_typecheck_call_too_few_args_at_least)
2749 << 0 /*function call*/ << 3 << Call->getNumArgs();
2750
2751 // Determine whether the current function is variadic or not.
2752 bool IsVariadic;
2753 if (BlockScopeInfo *CurBlock = getCurBlock())
2754 IsVariadic = CurBlock->TheDecl->isVariadic();
2755 else if (FunctionDecl *FD = getCurFunctionDecl())
2756 IsVariadic = FD->isVariadic();
2757 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2758 IsVariadic = MD->isVariadic();
2759 else
2760 llvm_unreachable("unexpected statement type");
2761
2762 if (!IsVariadic) {
2763 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2764 return true;
2765 }
2766
2767 // Type-check the first argument normally.
2768 if (checkBuiltinArgument(*this, Call, 0))
2769 return true;
2770
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002771 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002772 unsigned ArgNo;
2773 QualType Type;
2774 } ArgumentTypes[] = {
2775 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2776 { 2, Context.getSizeType() },
2777 };
2778
2779 for (const auto &AT : ArgumentTypes) {
2780 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2781 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2782 continue;
2783 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2784 << Arg->getType() << AT.Type << 1 /* different class */
2785 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2786 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2787 }
2788
2789 return false;
2790}
2791
Chris Lattner2da14fb2007-12-20 00:26:33 +00002792/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2793/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002794bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2795 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002796 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002797 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002798 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002799 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002800 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002801 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002802 << SourceRange(TheCall->getArg(2)->getLocStart(),
2803 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002804
John Wiegley01296292011-04-08 18:41:53 +00002805 ExprResult OrigArg0 = TheCall->getArg(0);
2806 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002807
Chris Lattner2da14fb2007-12-20 00:26:33 +00002808 // Do standard promotions between the two arguments, returning their common
2809 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002810 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002811 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2812 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002813
2814 // Make sure any conversions are pushed back into the call; this is
2815 // type safe since unordered compare builtins are declared as "_Bool
2816 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002817 TheCall->setArg(0, OrigArg0.get());
2818 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002819
John Wiegley01296292011-04-08 18:41:53 +00002820 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002821 return false;
2822
Chris Lattner2da14fb2007-12-20 00:26:33 +00002823 // If the common type isn't a real floating type, then the arguments were
2824 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002825 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002826 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002827 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002828 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2829 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002830
Chris Lattner2da14fb2007-12-20 00:26:33 +00002831 return false;
2832}
2833
Benjamin Kramer634fc102010-02-15 22:42:31 +00002834/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2835/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002836/// to check everything. We expect the last argument to be a floating point
2837/// value.
2838bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2839 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002840 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002841 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002842 if (TheCall->getNumArgs() > NumArgs)
2843 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002844 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002845 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002846 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002847 (*(TheCall->arg_end()-1))->getLocEnd());
2848
Benjamin Kramer64aae502010-02-16 10:07:31 +00002849 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002850
Eli Friedman7e4faac2009-08-31 20:06:00 +00002851 if (OrigArg->isTypeDependent())
2852 return false;
2853
Chris Lattner68784ef2010-05-06 05:50:07 +00002854 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002855 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002856 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002857 diag::err_typecheck_call_invalid_unary_fp)
2858 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002859
Chris Lattner68784ef2010-05-06 05:50:07 +00002860 // If this is an implicit conversion from float -> double, remove it.
2861 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2862 Expr *CastArg = Cast->getSubExpr();
2863 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2864 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2865 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002866 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002867 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002868 }
2869 }
2870
Eli Friedman7e4faac2009-08-31 20:06:00 +00002871 return false;
2872}
2873
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002874/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2875// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002876ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002877 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002878 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002879 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002880 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2881 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002882
Nate Begemana0110022010-06-08 00:16:34 +00002883 // Determine which of the following types of shufflevector we're checking:
2884 // 1) unary, vector mask: (lhs, mask)
2885 // 2) binary, vector mask: (lhs, rhs, mask)
2886 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2887 QualType resType = TheCall->getArg(0)->getType();
2888 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002889
Douglas Gregorc25f7662009-05-19 22:10:17 +00002890 if (!TheCall->getArg(0)->isTypeDependent() &&
2891 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002892 QualType LHSType = TheCall->getArg(0)->getType();
2893 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002894
Craig Topperbaca3892013-07-29 06:47:04 +00002895 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2896 return ExprError(Diag(TheCall->getLocStart(),
2897 diag::err_shufflevector_non_vector)
2898 << SourceRange(TheCall->getArg(0)->getLocStart(),
2899 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002900
Nate Begemana0110022010-06-08 00:16:34 +00002901 numElements = LHSType->getAs<VectorType>()->getNumElements();
2902 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002903
Nate Begemana0110022010-06-08 00:16:34 +00002904 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2905 // with mask. If so, verify that RHS is an integer vector type with the
2906 // same number of elts as lhs.
2907 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002908 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002909 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002910 return ExprError(Diag(TheCall->getLocStart(),
2911 diag::err_shufflevector_incompatible_vector)
2912 << SourceRange(TheCall->getArg(1)->getLocStart(),
2913 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002914 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002915 return ExprError(Diag(TheCall->getLocStart(),
2916 diag::err_shufflevector_incompatible_vector)
2917 << SourceRange(TheCall->getArg(0)->getLocStart(),
2918 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002919 } else if (numElements != numResElements) {
2920 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002921 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002922 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002923 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002924 }
2925
2926 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002927 if (TheCall->getArg(i)->isTypeDependent() ||
2928 TheCall->getArg(i)->isValueDependent())
2929 continue;
2930
Nate Begemana0110022010-06-08 00:16:34 +00002931 llvm::APSInt Result(32);
2932 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2933 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002934 diag::err_shufflevector_nonconstant_argument)
2935 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002936
Craig Topper50ad5b72013-08-03 17:40:38 +00002937 // Allow -1 which will be translated to undef in the IR.
2938 if (Result.isSigned() && Result.isAllOnesValue())
2939 continue;
2940
Chris Lattner7ab824e2008-08-10 02:05:13 +00002941 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002942 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002943 diag::err_shufflevector_argument_too_large)
2944 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002945 }
2946
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002947 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002948
Chris Lattner7ab824e2008-08-10 02:05:13 +00002949 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002950 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002951 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002952 }
2953
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002954 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2955 TheCall->getCallee()->getLocStart(),
2956 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002957}
Chris Lattner43be2e62007-12-19 23:59:04 +00002958
Hal Finkelc4d7c822013-09-18 03:29:45 +00002959/// SemaConvertVectorExpr - Handle __builtin_convertvector
2960ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2961 SourceLocation BuiltinLoc,
2962 SourceLocation RParenLoc) {
2963 ExprValueKind VK = VK_RValue;
2964 ExprObjectKind OK = OK_Ordinary;
2965 QualType DstTy = TInfo->getType();
2966 QualType SrcTy = E->getType();
2967
2968 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2969 return ExprError(Diag(BuiltinLoc,
2970 diag::err_convertvector_non_vector)
2971 << E->getSourceRange());
2972 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2973 return ExprError(Diag(BuiltinLoc,
2974 diag::err_convertvector_non_vector_type));
2975
2976 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2977 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2978 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2979 if (SrcElts != DstElts)
2980 return ExprError(Diag(BuiltinLoc,
2981 diag::err_convertvector_incompatible_vector)
2982 << E->getSourceRange());
2983 }
2984
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002985 return new (Context)
2986 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002987}
2988
Daniel Dunbarb7257262008-07-21 22:59:13 +00002989/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2990// This is declared to take (const void*, ...) and can take two
2991// optional constant int args.
2992bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002993 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002994
Chris Lattner3b054132008-11-19 05:08:23 +00002995 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002996 return Diag(TheCall->getLocEnd(),
2997 diag::err_typecheck_call_too_many_args_at_most)
2998 << 0 /*function call*/ << 3 << NumArgs
2999 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003000
3001 // Argument 0 is checked for us and the remaining arguments must be
3002 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003003 for (unsigned i = 1; i != NumArgs; ++i)
3004 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003005 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003006
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003007 return false;
3008}
3009
Hal Finkelf0417332014-07-17 14:25:55 +00003010/// SemaBuiltinAssume - Handle __assume (MS Extension).
3011// __assume does not evaluate its arguments, and should warn if its argument
3012// has side effects.
3013bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3014 Expr *Arg = TheCall->getArg(0);
3015 if (Arg->isInstantiationDependent()) return false;
3016
3017 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003018 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003019 << Arg->getSourceRange()
3020 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3021
3022 return false;
3023}
3024
3025/// Handle __builtin_assume_aligned. This is declared
3026/// as (const void*, size_t, ...) and can take one optional constant int arg.
3027bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3028 unsigned NumArgs = TheCall->getNumArgs();
3029
3030 if (NumArgs > 3)
3031 return Diag(TheCall->getLocEnd(),
3032 diag::err_typecheck_call_too_many_args_at_most)
3033 << 0 /*function call*/ << 3 << NumArgs
3034 << TheCall->getSourceRange();
3035
3036 // The alignment must be a constant integer.
3037 Expr *Arg = TheCall->getArg(1);
3038
3039 // We can't check the value of a dependent argument.
3040 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3041 llvm::APSInt Result;
3042 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3043 return true;
3044
3045 if (!Result.isPowerOf2())
3046 return Diag(TheCall->getLocStart(),
3047 diag::err_alignment_not_power_of_two)
3048 << Arg->getSourceRange();
3049 }
3050
3051 if (NumArgs > 2) {
3052 ExprResult Arg(TheCall->getArg(2));
3053 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3054 Context.getSizeType(), false);
3055 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3056 if (Arg.isInvalid()) return true;
3057 TheCall->setArg(2, Arg.get());
3058 }
Hal Finkelf0417332014-07-17 14:25:55 +00003059
3060 return false;
3061}
3062
Eric Christopher8d0c6212010-04-17 02:26:23 +00003063/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3064/// TheCall is a constant expression.
3065bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3066 llvm::APSInt &Result) {
3067 Expr *Arg = TheCall->getArg(ArgNum);
3068 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3069 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3070
3071 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3072
3073 if (!Arg->isIntegerConstantExpr(Result, Context))
3074 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003075 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003076
Chris Lattnerd545ad12009-09-23 06:06:36 +00003077 return false;
3078}
3079
Richard Sandiford28940af2014-04-16 08:47:51 +00003080/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3081/// TheCall is a constant expression in the range [Low, High].
3082bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3083 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003084 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003085
3086 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003087 Expr *Arg = TheCall->getArg(ArgNum);
3088 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003089 return false;
3090
Eric Christopher8d0c6212010-04-17 02:26:23 +00003091 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003092 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003093 return true;
3094
Richard Sandiford28940af2014-04-16 08:47:51 +00003095 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003096 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003097 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003098
3099 return false;
3100}
3101
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003102/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3103/// TheCall is an ARM/AArch64 special register string literal.
3104bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3105 int ArgNum, unsigned ExpectedFieldNum,
3106 bool AllowName) {
3107 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3108 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3109 BuiltinID == ARM::BI__builtin_arm_rsr ||
3110 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3111 BuiltinID == ARM::BI__builtin_arm_wsr ||
3112 BuiltinID == ARM::BI__builtin_arm_wsrp;
3113 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3114 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3115 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3116 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3117 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3118 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3119 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3120
3121 // We can't check the value of a dependent argument.
3122 Expr *Arg = TheCall->getArg(ArgNum);
3123 if (Arg->isTypeDependent() || Arg->isValueDependent())
3124 return false;
3125
3126 // Check if the argument is a string literal.
3127 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3128 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3129 << Arg->getSourceRange();
3130
3131 // Check the type of special register given.
3132 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3133 SmallVector<StringRef, 6> Fields;
3134 Reg.split(Fields, ":");
3135
3136 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3137 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3138 << Arg->getSourceRange();
3139
3140 // If the string is the name of a register then we cannot check that it is
3141 // valid here but if the string is of one the forms described in ACLE then we
3142 // can check that the supplied fields are integers and within the valid
3143 // ranges.
3144 if (Fields.size() > 1) {
3145 bool FiveFields = Fields.size() == 5;
3146
3147 bool ValidString = true;
3148 if (IsARMBuiltin) {
3149 ValidString &= Fields[0].startswith_lower("cp") ||
3150 Fields[0].startswith_lower("p");
3151 if (ValidString)
3152 Fields[0] =
3153 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3154
3155 ValidString &= Fields[2].startswith_lower("c");
3156 if (ValidString)
3157 Fields[2] = Fields[2].drop_front(1);
3158
3159 if (FiveFields) {
3160 ValidString &= Fields[3].startswith_lower("c");
3161 if (ValidString)
3162 Fields[3] = Fields[3].drop_front(1);
3163 }
3164 }
3165
3166 SmallVector<int, 5> Ranges;
3167 if (FiveFields)
3168 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3169 else
3170 Ranges.append({15, 7, 15});
3171
3172 for (unsigned i=0; i<Fields.size(); ++i) {
3173 int IntField;
3174 ValidString &= !Fields[i].getAsInteger(10, IntField);
3175 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3176 }
3177
3178 if (!ValidString)
3179 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3180 << Arg->getSourceRange();
3181
3182 } else if (IsAArch64Builtin && Fields.size() == 1) {
3183 // If the register name is one of those that appear in the condition below
3184 // and the special register builtin being used is one of the write builtins,
3185 // then we require that the argument provided for writing to the register
3186 // is an integer constant expression. This is because it will be lowered to
3187 // an MSR (immediate) instruction, so we need to know the immediate at
3188 // compile time.
3189 if (TheCall->getNumArgs() != 2)
3190 return false;
3191
3192 std::string RegLower = Reg.lower();
3193 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3194 RegLower != "pan" && RegLower != "uao")
3195 return false;
3196
3197 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3198 }
3199
3200 return false;
3201}
3202
Eli Friedmanc97d0142009-05-03 06:04:26 +00003203/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003204/// This checks that the target supports __builtin_longjmp and
3205/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003206bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003207 if (!Context.getTargetInfo().hasSjLjLowering())
3208 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3209 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3210
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003211 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003212 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003213
Eric Christopher8d0c6212010-04-17 02:26:23 +00003214 // TODO: This is less than ideal. Overload this to take a value.
3215 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3216 return true;
3217
3218 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003219 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3220 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3221
3222 return false;
3223}
3224
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003225
3226/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3227/// This checks that the target supports __builtin_setjmp.
3228bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3229 if (!Context.getTargetInfo().hasSjLjLowering())
3230 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3231 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3232 return false;
3233}
3234
Richard Smithd7293d72013-08-05 18:49:43 +00003235namespace {
3236enum StringLiteralCheckType {
3237 SLCT_NotALiteral,
3238 SLCT_UncheckedLiteral,
3239 SLCT_CheckedLiteral
3240};
3241}
3242
Richard Smith55ce3522012-06-25 20:30:08 +00003243// Determine if an expression is a string literal or constant string.
3244// If this function returns false on the arguments to a function expecting a
3245// format string, we will usually need to emit a warning.
3246// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003247static StringLiteralCheckType
3248checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3249 bool HasVAListArg, unsigned format_idx,
3250 unsigned firstDataArg, Sema::FormatStringType Type,
3251 Sema::VariadicCallType CallType, bool InFunctionCall,
3252 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00003253 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003254 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003255 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003256
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003257 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003258
Richard Smithd7293d72013-08-05 18:49:43 +00003259 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003260 // Technically -Wformat-nonliteral does not warn about this case.
3261 // The behavior of printf and friends in this case is implementation
3262 // dependent. Ideally if the format string cannot be null then
3263 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003264 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003265
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003266 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003267 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003268 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003269 // The expression is a literal if both sub-expressions were, and it was
3270 // completely checked only if both sub-expressions were checked.
3271 const AbstractConditionalOperator *C =
3272 cast<AbstractConditionalOperator>(E);
3273 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00003274 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003275 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003276 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003277 if (Left == SLCT_NotALiteral)
3278 return SLCT_NotALiteral;
3279 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003280 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003281 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003282 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003283 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003284 }
3285
3286 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003287 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3288 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003289 }
3290
John McCallc07a0c72011-02-17 10:25:35 +00003291 case Stmt::OpaqueValueExprClass:
3292 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3293 E = src;
3294 goto tryAgain;
3295 }
Richard Smith55ce3522012-06-25 20:30:08 +00003296 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003297
Ted Kremeneka8890832011-02-24 23:03:04 +00003298 case Stmt::PredefinedExprClass:
3299 // While __func__, etc., are technically not string literals, they
3300 // cannot contain format specifiers and thus are not a security
3301 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003302 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003303
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003304 case Stmt::DeclRefExprClass: {
3305 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003306
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003307 // As an exception, do not flag errors for variables binding to
3308 // const string literals.
3309 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3310 bool isConstant = false;
3311 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003312
Richard Smithd7293d72013-08-05 18:49:43 +00003313 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3314 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003315 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003316 isConstant = T.isConstant(S.Context) &&
3317 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003318 } else if (T->isObjCObjectPointerType()) {
3319 // In ObjC, there is usually no "const ObjectPointer" type,
3320 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003321 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003322 }
Mike Stump11289f42009-09-09 15:08:12 +00003323
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003324 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003325 if (const Expr *Init = VD->getAnyInitializer()) {
3326 // Look through initializers like const char c[] = { "foo" }
3327 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3328 if (InitList->isStringLiteralInit())
3329 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3330 }
Richard Smithd7293d72013-08-05 18:49:43 +00003331 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003332 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003333 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003334 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003335 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003336 }
Mike Stump11289f42009-09-09 15:08:12 +00003337
Anders Carlssonb012ca92009-06-28 19:55:58 +00003338 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3339 // special check to see if the format string is a function parameter
3340 // of the function calling the printf function. If the function
3341 // has an attribute indicating it is a printf-like function, then we
3342 // should suppress warnings concerning non-literals being used in a call
3343 // to a vprintf function. For example:
3344 //
3345 // void
3346 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3347 // va_list ap;
3348 // va_start(ap, fmt);
3349 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3350 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003351 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003352 if (HasVAListArg) {
3353 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3354 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3355 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003356 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003357 // adjust for implicit parameter
3358 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3359 if (MD->isInstance())
3360 ++PVIndex;
3361 // We also check if the formats are compatible.
3362 // We can't pass a 'scanf' string to a 'printf' function.
3363 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003364 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003365 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003366 }
3367 }
3368 }
3369 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003370 }
Mike Stump11289f42009-09-09 15:08:12 +00003371
Richard Smith55ce3522012-06-25 20:30:08 +00003372 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003373 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003374
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003375 case Stmt::CallExprClass:
3376 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003377 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003378 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3379 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3380 unsigned ArgIndex = FA->getFormatIdx();
3381 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3382 if (MD->isInstance())
3383 --ArgIndex;
3384 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003385
Richard Smithd7293d72013-08-05 18:49:43 +00003386 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003387 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003388 Type, CallType, InFunctionCall,
3389 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003390 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3391 unsigned BuiltinID = FD->getBuiltinID();
3392 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3393 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3394 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003395 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003396 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003397 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003398 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003399 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003400 }
3401 }
Mike Stump11289f42009-09-09 15:08:12 +00003402
Richard Smith55ce3522012-06-25 20:30:08 +00003403 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003404 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003405 case Stmt::ObjCStringLiteralClass:
3406 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003407 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003408
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003409 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003410 StrE = ObjCFExpr->getString();
3411 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003412 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003413
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003414 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00003415 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
3416 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003417 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003418 }
Mike Stump11289f42009-09-09 15:08:12 +00003419
Richard Smith55ce3522012-06-25 20:30:08 +00003420 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003421 }
Mike Stump11289f42009-09-09 15:08:12 +00003422
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003423 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003424 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003425 }
3426}
3427
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003428Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003429 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003430 .Case("scanf", FST_Scanf)
3431 .Cases("printf", "printf0", FST_Printf)
3432 .Cases("NSString", "CFString", FST_NSString)
3433 .Case("strftime", FST_Strftime)
3434 .Case("strfmon", FST_Strfmon)
3435 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003436 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003437 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003438 .Default(FST_Unknown);
3439}
3440
Jordan Rose3e0ec582012-07-19 18:10:23 +00003441/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003442/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003443/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003444bool Sema::CheckFormatArguments(const FormatAttr *Format,
3445 ArrayRef<const Expr *> Args,
3446 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003447 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003448 SourceLocation Loc, SourceRange Range,
3449 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003450 FormatStringInfo FSI;
3451 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003452 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003453 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003454 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003455 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003456}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003457
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003458bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003459 bool HasVAListArg, unsigned format_idx,
3460 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003461 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003462 SourceLocation Loc, SourceRange Range,
3463 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003464 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003465 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003466 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003467 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003468 }
Mike Stump11289f42009-09-09 15:08:12 +00003469
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003470 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003471
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003472 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003473 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003474 // Dynamically generated format strings are difficult to
3475 // automatically vet at compile time. Requiring that format strings
3476 // are string literals: (1) permits the checking of format strings by
3477 // the compiler and thereby (2) can practically remove the source of
3478 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003479
Mike Stump11289f42009-09-09 15:08:12 +00003480 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003481 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003482 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003483 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003484 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003485 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3486 format_idx, firstDataArg, Type, CallType,
3487 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003488 if (CT != SLCT_NotALiteral)
3489 // Literal format string found, check done!
3490 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003491
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003492 // Strftime is particular as it always uses a single 'time' argument,
3493 // so it is safe to pass a non-literal string.
3494 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003495 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003496
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003497 // Do not emit diag when the string param is a macro expansion and the
3498 // format is either NSString or CFString. This is a hack to prevent
3499 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3500 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003501 if (Type == FST_NSString &&
3502 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003503 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003504
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003505 // If there are no arguments specified, warn with -Wformat-security, otherwise
3506 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003507 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003508 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003509 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003510 << OrigFormatExpr->getSourceRange();
3511 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003512 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003513 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003514 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003515 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003516}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003517
Ted Kremenekab278de2010-01-28 23:39:18 +00003518namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003519class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3520protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003521 Sema &S;
3522 const StringLiteral *FExpr;
3523 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003524 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003525 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003526 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003527 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003528 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003529 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003530 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003531 bool usesPositionalArgs;
3532 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003533 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003534 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003535 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003536public:
Ted Kremenek02087932010-07-16 02:11:22 +00003537 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003538 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003539 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003540 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003541 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003542 Sema::VariadicCallType callType,
3543 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00003544 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003545 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3546 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003547 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003548 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003549 inFunctionCall(inFunctionCall), CallType(callType),
3550 CheckedVarArgs(CheckedVarArgs) {
3551 CoveredArgs.resize(numDataArgs);
3552 CoveredArgs.reset();
3553 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003554
Ted Kremenek019d2242010-01-29 01:50:07 +00003555 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003556
Ted Kremenek02087932010-07-16 02:11:22 +00003557 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003558 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003559
Jordan Rose92303592012-09-08 04:00:03 +00003560 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003561 const analyze_format_string::FormatSpecifier &FS,
3562 const analyze_format_string::ConversionSpecifier &CS,
3563 const char *startSpecifier, unsigned specifierLen,
3564 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003565
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003566 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003567 const analyze_format_string::FormatSpecifier &FS,
3568 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003569
3570 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003571 const analyze_format_string::ConversionSpecifier &CS,
3572 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003573
Craig Toppere14c0f82014-03-12 04:55:44 +00003574 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003575
Craig Toppere14c0f82014-03-12 04:55:44 +00003576 void HandleInvalidPosition(const char *startSpecifier,
3577 unsigned specifierLen,
3578 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003579
Craig Toppere14c0f82014-03-12 04:55:44 +00003580 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003581
Craig Toppere14c0f82014-03-12 04:55:44 +00003582 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003583
Richard Trieu03cf7b72011-10-28 00:41:25 +00003584 template <typename Range>
3585 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3586 const Expr *ArgumentExpr,
3587 PartialDiagnostic PDiag,
3588 SourceLocation StringLoc,
3589 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003590 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003591
Ted Kremenek02087932010-07-16 02:11:22 +00003592protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003593 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3594 const char *startSpec,
3595 unsigned specifierLen,
3596 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003597
3598 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3599 const char *startSpec,
3600 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003601
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003602 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003603 CharSourceRange getSpecifierRange(const char *startSpecifier,
3604 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003605 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003606
Ted Kremenek5739de72010-01-29 01:06:55 +00003607 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003608
3609 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3610 const analyze_format_string::ConversionSpecifier &CS,
3611 const char *startSpecifier, unsigned specifierLen,
3612 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003613
3614 template <typename Range>
3615 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3616 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003617 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003618};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003619}
Ted Kremenekab278de2010-01-28 23:39:18 +00003620
Ted Kremenek02087932010-07-16 02:11:22 +00003621SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003622 return OrigFormatExpr->getSourceRange();
3623}
3624
Ted Kremenek02087932010-07-16 02:11:22 +00003625CharSourceRange CheckFormatHandler::
3626getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003627 SourceLocation Start = getLocationOfByte(startSpecifier);
3628 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3629
3630 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003631 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003632
3633 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003634}
3635
Ted Kremenek02087932010-07-16 02:11:22 +00003636SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003637 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003638}
3639
Ted Kremenek02087932010-07-16 02:11:22 +00003640void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3641 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003642 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3643 getLocationOfByte(startSpecifier),
3644 /*IsStringLocation*/true,
3645 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003646}
3647
Jordan Rose92303592012-09-08 04:00:03 +00003648void CheckFormatHandler::HandleInvalidLengthModifier(
3649 const analyze_format_string::FormatSpecifier &FS,
3650 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003651 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003652 using namespace analyze_format_string;
3653
3654 const LengthModifier &LM = FS.getLengthModifier();
3655 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3656
3657 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003658 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003659 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003660 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003661 getLocationOfByte(LM.getStart()),
3662 /*IsStringLocation*/true,
3663 getSpecifierRange(startSpecifier, specifierLen));
3664
3665 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3666 << FixedLM->toString()
3667 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3668
3669 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003670 FixItHint Hint;
3671 if (DiagID == diag::warn_format_nonsensical_length)
3672 Hint = FixItHint::CreateRemoval(LMRange);
3673
3674 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003675 getLocationOfByte(LM.getStart()),
3676 /*IsStringLocation*/true,
3677 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003678 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003679 }
3680}
3681
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003682void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003683 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003684 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003685 using namespace analyze_format_string;
3686
3687 const LengthModifier &LM = FS.getLengthModifier();
3688 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3689
3690 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003691 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003692 if (FixedLM) {
3693 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3694 << LM.toString() << 0,
3695 getLocationOfByte(LM.getStart()),
3696 /*IsStringLocation*/true,
3697 getSpecifierRange(startSpecifier, specifierLen));
3698
3699 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3700 << FixedLM->toString()
3701 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3702
3703 } else {
3704 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3705 << LM.toString() << 0,
3706 getLocationOfByte(LM.getStart()),
3707 /*IsStringLocation*/true,
3708 getSpecifierRange(startSpecifier, specifierLen));
3709 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003710}
3711
3712void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3713 const analyze_format_string::ConversionSpecifier &CS,
3714 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003715 using namespace analyze_format_string;
3716
3717 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003718 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003719 if (FixedCS) {
3720 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3721 << CS.toString() << /*conversion specifier*/1,
3722 getLocationOfByte(CS.getStart()),
3723 /*IsStringLocation*/true,
3724 getSpecifierRange(startSpecifier, specifierLen));
3725
3726 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3727 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3728 << FixedCS->toString()
3729 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3730 } else {
3731 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3732 << CS.toString() << /*conversion specifier*/1,
3733 getLocationOfByte(CS.getStart()),
3734 /*IsStringLocation*/true,
3735 getSpecifierRange(startSpecifier, specifierLen));
3736 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003737}
3738
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003739void CheckFormatHandler::HandlePosition(const char *startPos,
3740 unsigned posLen) {
3741 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3742 getLocationOfByte(startPos),
3743 /*IsStringLocation*/true,
3744 getSpecifierRange(startPos, posLen));
3745}
3746
Ted Kremenekd1668192010-02-27 01:41:03 +00003747void
Ted Kremenek02087932010-07-16 02:11:22 +00003748CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3749 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003750 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3751 << (unsigned) p,
3752 getLocationOfByte(startPos), /*IsStringLocation*/true,
3753 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003754}
3755
Ted Kremenek02087932010-07-16 02:11:22 +00003756void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003757 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003758 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3759 getLocationOfByte(startPos),
3760 /*IsStringLocation*/true,
3761 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003762}
3763
Ted Kremenek02087932010-07-16 02:11:22 +00003764void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003765 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003766 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003767 EmitFormatDiagnostic(
3768 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3769 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3770 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003771 }
Ted Kremenek02087932010-07-16 02:11:22 +00003772}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003773
Jordan Rose58bbe422012-07-19 18:10:08 +00003774// Note that this may return NULL if there was an error parsing or building
3775// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003776const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003777 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003778}
3779
3780void CheckFormatHandler::DoneProcessing() {
3781 // Does the number of data arguments exceed the number of
3782 // format conversions in the format string?
3783 if (!HasVAListArg) {
3784 // Find any arguments that weren't covered.
3785 CoveredArgs.flip();
3786 signed notCoveredArg = CoveredArgs.find_first();
3787 if (notCoveredArg >= 0) {
3788 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003789 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3790 SourceLocation Loc = E->getLocStart();
3791 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3792 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3793 Loc, /*IsStringLocation*/false,
3794 getFormatStringRange());
3795 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003796 }
Ted Kremenek02087932010-07-16 02:11:22 +00003797 }
3798 }
3799}
3800
Ted Kremenekce815422010-07-19 21:25:57 +00003801bool
3802CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3803 SourceLocation Loc,
3804 const char *startSpec,
3805 unsigned specifierLen,
3806 const char *csStart,
3807 unsigned csLen) {
3808
3809 bool keepGoing = true;
3810 if (argIndex < NumDataArgs) {
3811 // Consider the argument coverered, even though the specifier doesn't
3812 // make sense.
3813 CoveredArgs.set(argIndex);
3814 }
3815 else {
3816 // If argIndex exceeds the number of data arguments we
3817 // don't issue a warning because that is just a cascade of warnings (and
3818 // they may have intended '%%' anyway). We don't want to continue processing
3819 // the format string after this point, however, as we will like just get
3820 // gibberish when trying to match arguments.
3821 keepGoing = false;
3822 }
3823
Richard Trieu03cf7b72011-10-28 00:41:25 +00003824 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3825 << StringRef(csStart, csLen),
3826 Loc, /*IsStringLocation*/true,
3827 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003828
3829 return keepGoing;
3830}
3831
Richard Trieu03cf7b72011-10-28 00:41:25 +00003832void
3833CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3834 const char *startSpec,
3835 unsigned specifierLen) {
3836 EmitFormatDiagnostic(
3837 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3838 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3839}
3840
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003841bool
3842CheckFormatHandler::CheckNumArgs(
3843 const analyze_format_string::FormatSpecifier &FS,
3844 const analyze_format_string::ConversionSpecifier &CS,
3845 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3846
3847 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003848 PartialDiagnostic PDiag = FS.usesPositionalArg()
3849 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3850 << (argIndex+1) << NumDataArgs)
3851 : S.PDiag(diag::warn_printf_insufficient_data_args);
3852 EmitFormatDiagnostic(
3853 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3854 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003855 return false;
3856 }
3857 return true;
3858}
3859
Richard Trieu03cf7b72011-10-28 00:41:25 +00003860template<typename Range>
3861void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3862 SourceLocation Loc,
3863 bool IsStringLocation,
3864 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003865 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003866 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003867 Loc, IsStringLocation, StringRange, FixIt);
3868}
3869
3870/// \brief If the format string is not within the funcion call, emit a note
3871/// so that the function call and string are in diagnostic messages.
3872///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003873/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003874/// call and only one diagnostic message will be produced. Otherwise, an
3875/// extra note will be emitted pointing to location of the format string.
3876///
3877/// \param ArgumentExpr the expression that is passed as the format string
3878/// argument in the function call. Used for getting locations when two
3879/// diagnostics are emitted.
3880///
3881/// \param PDiag the callee should already have provided any strings for the
3882/// diagnostic message. This function only adds locations and fixits
3883/// to diagnostics.
3884///
3885/// \param Loc primary location for diagnostic. If two diagnostics are
3886/// required, one will be at Loc and a new SourceLocation will be created for
3887/// the other one.
3888///
3889/// \param IsStringLocation if true, Loc points to the format string should be
3890/// used for the note. Otherwise, Loc points to the argument list and will
3891/// be used with PDiag.
3892///
3893/// \param StringRange some or all of the string to highlight. This is
3894/// templated so it can accept either a CharSourceRange or a SourceRange.
3895///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003896/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003897template<typename Range>
3898void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3899 const Expr *ArgumentExpr,
3900 PartialDiagnostic PDiag,
3901 SourceLocation Loc,
3902 bool IsStringLocation,
3903 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003904 ArrayRef<FixItHint> FixIt) {
3905 if (InFunctionCall) {
3906 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3907 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003908 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003909 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003910 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3911 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003912
3913 const Sema::SemaDiagnosticBuilder &Note =
3914 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3915 diag::note_format_string_defined);
3916
3917 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003918 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003919 }
3920}
3921
Ted Kremenek02087932010-07-16 02:11:22 +00003922//===--- CHECK: Printf format string checking ------------------------------===//
3923
3924namespace {
3925class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003926 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003927public:
3928 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3929 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003930 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003931 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003932 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003933 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003934 Sema::VariadicCallType CallType,
3935 llvm::SmallBitVector &CheckedVarArgs)
3936 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3937 numDataArgs, beg, hasVAListArg, Args,
3938 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3939 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003940 {}
3941
Craig Toppere14c0f82014-03-12 04:55:44 +00003942
Ted Kremenek02087932010-07-16 02:11:22 +00003943 bool HandleInvalidPrintfConversionSpecifier(
3944 const analyze_printf::PrintfSpecifier &FS,
3945 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003946 unsigned specifierLen) override;
3947
Ted Kremenek02087932010-07-16 02:11:22 +00003948 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3949 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003950 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003951 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3952 const char *StartSpecifier,
3953 unsigned SpecifierLen,
3954 const Expr *E);
3955
Ted Kremenek02087932010-07-16 02:11:22 +00003956 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3957 const char *startSpecifier, unsigned specifierLen);
3958 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3959 const analyze_printf::OptionalAmount &Amt,
3960 unsigned type,
3961 const char *startSpecifier, unsigned specifierLen);
3962 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3963 const analyze_printf::OptionalFlag &flag,
3964 const char *startSpecifier, unsigned specifierLen);
3965 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3966 const analyze_printf::OptionalFlag &ignoredFlag,
3967 const analyze_printf::OptionalFlag &flag,
3968 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003969 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003970 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00003971
3972 void HandleEmptyObjCModifierFlag(const char *startFlag,
3973 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003974
Ted Kremenek2b417712015-07-02 05:39:16 +00003975 void HandleInvalidObjCModifierFlag(const char *startFlag,
3976 unsigned flagLen) override;
3977
3978 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
3979 const char *flagsEnd,
3980 const char *conversionPosition)
3981 override;
3982};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003983}
Ted Kremenek02087932010-07-16 02:11:22 +00003984
3985bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3986 const analyze_printf::PrintfSpecifier &FS,
3987 const char *startSpecifier,
3988 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003989 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003990 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003991
Ted Kremenekce815422010-07-19 21:25:57 +00003992 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3993 getLocationOfByte(CS.getStart()),
3994 startSpecifier, specifierLen,
3995 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003996}
3997
Ted Kremenek02087932010-07-16 02:11:22 +00003998bool CheckPrintfHandler::HandleAmount(
3999 const analyze_format_string::OptionalAmount &Amt,
4000 unsigned k, const char *startSpecifier,
4001 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004002
4003 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004004 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004005 unsigned argIndex = Amt.getArgIndex();
4006 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004007 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4008 << k,
4009 getLocationOfByte(Amt.getStart()),
4010 /*IsStringLocation*/true,
4011 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004012 // Don't do any more checking. We will just emit
4013 // spurious errors.
4014 return false;
4015 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004016
Ted Kremenek5739de72010-01-29 01:06:55 +00004017 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004018 // Although not in conformance with C99, we also allow the argument to be
4019 // an 'unsigned int' as that is a reasonably safe case. GCC also
4020 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004021 CoveredArgs.set(argIndex);
4022 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004023 if (!Arg)
4024 return false;
4025
Ted Kremenek5739de72010-01-29 01:06:55 +00004026 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004027
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004028 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4029 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004030
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004031 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004032 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004033 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004034 << T << Arg->getSourceRange(),
4035 getLocationOfByte(Amt.getStart()),
4036 /*IsStringLocation*/true,
4037 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004038 // Don't do any more checking. We will just emit
4039 // spurious errors.
4040 return false;
4041 }
4042 }
4043 }
4044 return true;
4045}
Ted Kremenek5739de72010-01-29 01:06:55 +00004046
Tom Careb49ec692010-06-17 19:00:27 +00004047void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004048 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004049 const analyze_printf::OptionalAmount &Amt,
4050 unsigned type,
4051 const char *startSpecifier,
4052 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004053 const analyze_printf::PrintfConversionSpecifier &CS =
4054 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004055
Richard Trieu03cf7b72011-10-28 00:41:25 +00004056 FixItHint fixit =
4057 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4058 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4059 Amt.getConstantLength()))
4060 : FixItHint();
4061
4062 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4063 << type << CS.toString(),
4064 getLocationOfByte(Amt.getStart()),
4065 /*IsStringLocation*/true,
4066 getSpecifierRange(startSpecifier, specifierLen),
4067 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004068}
4069
Ted Kremenek02087932010-07-16 02:11:22 +00004070void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004071 const analyze_printf::OptionalFlag &flag,
4072 const char *startSpecifier,
4073 unsigned specifierLen) {
4074 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004075 const analyze_printf::PrintfConversionSpecifier &CS =
4076 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004077 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4078 << flag.toString() << CS.toString(),
4079 getLocationOfByte(flag.getPosition()),
4080 /*IsStringLocation*/true,
4081 getSpecifierRange(startSpecifier, specifierLen),
4082 FixItHint::CreateRemoval(
4083 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004084}
4085
4086void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004087 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004088 const analyze_printf::OptionalFlag &ignoredFlag,
4089 const analyze_printf::OptionalFlag &flag,
4090 const char *startSpecifier,
4091 unsigned specifierLen) {
4092 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004093 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4094 << ignoredFlag.toString() << flag.toString(),
4095 getLocationOfByte(ignoredFlag.getPosition()),
4096 /*IsStringLocation*/true,
4097 getSpecifierRange(startSpecifier, specifierLen),
4098 FixItHint::CreateRemoval(
4099 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004100}
4101
Ted Kremenek2b417712015-07-02 05:39:16 +00004102// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4103// bool IsStringLocation, Range StringRange,
4104// ArrayRef<FixItHint> Fixit = None);
4105
4106void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4107 unsigned flagLen) {
4108 // Warn about an empty flag.
4109 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4110 getLocationOfByte(startFlag),
4111 /*IsStringLocation*/true,
4112 getSpecifierRange(startFlag, flagLen));
4113}
4114
4115void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4116 unsigned flagLen) {
4117 // Warn about an invalid flag.
4118 auto Range = getSpecifierRange(startFlag, flagLen);
4119 StringRef flag(startFlag, flagLen);
4120 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4121 getLocationOfByte(startFlag),
4122 /*IsStringLocation*/true,
4123 Range, FixItHint::CreateRemoval(Range));
4124}
4125
4126void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4127 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4128 // Warn about using '[...]' without a '@' conversion.
4129 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4130 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4131 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4132 getLocationOfByte(conversionPosition),
4133 /*IsStringLocation*/true,
4134 Range, FixItHint::CreateRemoval(Range));
4135}
4136
Richard Smith55ce3522012-06-25 20:30:08 +00004137// Determines if the specified is a C++ class or struct containing
4138// a member with the specified name and kind (e.g. a CXXMethodDecl named
4139// "c_str()").
4140template<typename MemberKind>
4141static llvm::SmallPtrSet<MemberKind*, 1>
4142CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4143 const RecordType *RT = Ty->getAs<RecordType>();
4144 llvm::SmallPtrSet<MemberKind*, 1> Results;
4145
4146 if (!RT)
4147 return Results;
4148 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004149 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004150 return Results;
4151
Alp Tokerb6cc5922014-05-03 03:45:55 +00004152 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004153 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004154 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004155
4156 // We just need to include all members of the right kind turned up by the
4157 // filter, at this point.
4158 if (S.LookupQualifiedName(R, RT->getDecl()))
4159 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4160 NamedDecl *decl = (*I)->getUnderlyingDecl();
4161 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4162 Results.insert(FK);
4163 }
4164 return Results;
4165}
4166
Richard Smith2868a732014-02-28 01:36:39 +00004167/// Check if we could call '.c_str()' on an object.
4168///
4169/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4170/// allow the call, or if it would be ambiguous).
4171bool Sema::hasCStrMethod(const Expr *E) {
4172 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4173 MethodSet Results =
4174 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4175 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4176 MI != ME; ++MI)
4177 if ((*MI)->getMinRequiredArguments() == 0)
4178 return true;
4179 return false;
4180}
4181
Richard Smith55ce3522012-06-25 20:30:08 +00004182// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004183// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004184// Returns true when a c_str() conversion method is found.
4185bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004186 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004187 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4188
4189 MethodSet Results =
4190 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4191
4192 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4193 MI != ME; ++MI) {
4194 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004195 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004196 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004197 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004198 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004199 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4200 << "c_str()"
4201 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4202 return true;
4203 }
4204 }
4205
4206 return false;
4207}
4208
Ted Kremenekab278de2010-01-28 23:39:18 +00004209bool
Ted Kremenek02087932010-07-16 02:11:22 +00004210CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004211 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004212 const char *startSpecifier,
4213 unsigned specifierLen) {
4214
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004215 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004216 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004217 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004218
Ted Kremenek6cd69422010-07-19 22:01:06 +00004219 if (FS.consumesDataArgument()) {
4220 if (atFirstArg) {
4221 atFirstArg = false;
4222 usesPositionalArgs = FS.usesPositionalArg();
4223 }
4224 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004225 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4226 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004227 return false;
4228 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004229 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004230
Ted Kremenekd1668192010-02-27 01:41:03 +00004231 // First check if the field width, precision, and conversion specifier
4232 // have matching data arguments.
4233 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4234 startSpecifier, specifierLen)) {
4235 return false;
4236 }
4237
4238 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4239 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004240 return false;
4241 }
4242
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004243 if (!CS.consumesDataArgument()) {
4244 // FIXME: Technically specifying a precision or field width here
4245 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004246 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004247 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004248
Ted Kremenek4a49d982010-02-26 19:18:41 +00004249 // Consume the argument.
4250 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004251 if (argIndex < NumDataArgs) {
4252 // The check to see if the argIndex is valid will come later.
4253 // We set the bit here because we may exit early from this
4254 // function if we encounter some other error.
4255 CoveredArgs.set(argIndex);
4256 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004257
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004258 // FreeBSD kernel extensions.
4259 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4260 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4261 // We need at least two arguments.
4262 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4263 return false;
4264
4265 // Claim the second argument.
4266 CoveredArgs.set(argIndex + 1);
4267
4268 // Type check the first argument (int for %b, pointer for %D)
4269 const Expr *Ex = getDataArg(argIndex);
4270 const analyze_printf::ArgType &AT =
4271 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4272 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4273 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4274 EmitFormatDiagnostic(
4275 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4276 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4277 << false << Ex->getSourceRange(),
4278 Ex->getLocStart(), /*IsStringLocation*/false,
4279 getSpecifierRange(startSpecifier, specifierLen));
4280
4281 // Type check the second argument (char * for both %b and %D)
4282 Ex = getDataArg(argIndex + 1);
4283 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4284 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4285 EmitFormatDiagnostic(
4286 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4287 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4288 << false << Ex->getSourceRange(),
4289 Ex->getLocStart(), /*IsStringLocation*/false,
4290 getSpecifierRange(startSpecifier, specifierLen));
4291
4292 return true;
4293 }
4294
Ted Kremenek4a49d982010-02-26 19:18:41 +00004295 // Check for using an Objective-C specific conversion specifier
4296 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004297 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004298 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4299 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004300 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004301
Tom Careb49ec692010-06-17 19:00:27 +00004302 // Check for invalid use of field width
4303 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004304 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004305 startSpecifier, specifierLen);
4306 }
4307
4308 // Check for invalid use of precision
4309 if (!FS.hasValidPrecision()) {
4310 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4311 startSpecifier, specifierLen);
4312 }
4313
4314 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004315 if (!FS.hasValidThousandsGroupingPrefix())
4316 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004317 if (!FS.hasValidLeadingZeros())
4318 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4319 if (!FS.hasValidPlusPrefix())
4320 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004321 if (!FS.hasValidSpacePrefix())
4322 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004323 if (!FS.hasValidAlternativeForm())
4324 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4325 if (!FS.hasValidLeftJustified())
4326 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4327
4328 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004329 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4330 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4331 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004332 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4333 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4334 startSpecifier, specifierLen);
4335
4336 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004337 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004338 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4339 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004340 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004341 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004342 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004343 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4344 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004345
Jordan Rose92303592012-09-08 04:00:03 +00004346 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4347 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4348
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004349 // The remaining checks depend on the data arguments.
4350 if (HasVAListArg)
4351 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004352
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004353 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004354 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004355
Jordan Rose58bbe422012-07-19 18:10:08 +00004356 const Expr *Arg = getDataArg(argIndex);
4357 if (!Arg)
4358 return true;
4359
4360 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004361}
4362
Jordan Roseaee34382012-09-05 22:56:26 +00004363static bool requiresParensToAddCast(const Expr *E) {
4364 // FIXME: We should have a general way to reason about operator
4365 // precedence and whether parens are actually needed here.
4366 // Take care of a few common cases where they aren't.
4367 const Expr *Inside = E->IgnoreImpCasts();
4368 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4369 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4370
4371 switch (Inside->getStmtClass()) {
4372 case Stmt::ArraySubscriptExprClass:
4373 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004374 case Stmt::CharacterLiteralClass:
4375 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004376 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004377 case Stmt::FloatingLiteralClass:
4378 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004379 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004380 case Stmt::ObjCArrayLiteralClass:
4381 case Stmt::ObjCBoolLiteralExprClass:
4382 case Stmt::ObjCBoxedExprClass:
4383 case Stmt::ObjCDictionaryLiteralClass:
4384 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004385 case Stmt::ObjCIvarRefExprClass:
4386 case Stmt::ObjCMessageExprClass:
4387 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004388 case Stmt::ObjCStringLiteralClass:
4389 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004390 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004391 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004392 case Stmt::UnaryOperatorClass:
4393 return false;
4394 default:
4395 return true;
4396 }
4397}
4398
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004399static std::pair<QualType, StringRef>
4400shouldNotPrintDirectly(const ASTContext &Context,
4401 QualType IntendedTy,
4402 const Expr *E) {
4403 // Use a 'while' to peel off layers of typedefs.
4404 QualType TyTy = IntendedTy;
4405 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4406 StringRef Name = UserTy->getDecl()->getName();
4407 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4408 .Case("NSInteger", Context.LongTy)
4409 .Case("NSUInteger", Context.UnsignedLongTy)
4410 .Case("SInt32", Context.IntTy)
4411 .Case("UInt32", Context.UnsignedIntTy)
4412 .Default(QualType());
4413
4414 if (!CastTy.isNull())
4415 return std::make_pair(CastTy, Name);
4416
4417 TyTy = UserTy->desugar();
4418 }
4419
4420 // Strip parens if necessary.
4421 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4422 return shouldNotPrintDirectly(Context,
4423 PE->getSubExpr()->getType(),
4424 PE->getSubExpr());
4425
4426 // If this is a conditional expression, then its result type is constructed
4427 // via usual arithmetic conversions and thus there might be no necessary
4428 // typedef sugar there. Recurse to operands to check for NSInteger &
4429 // Co. usage condition.
4430 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4431 QualType TrueTy, FalseTy;
4432 StringRef TrueName, FalseName;
4433
4434 std::tie(TrueTy, TrueName) =
4435 shouldNotPrintDirectly(Context,
4436 CO->getTrueExpr()->getType(),
4437 CO->getTrueExpr());
4438 std::tie(FalseTy, FalseName) =
4439 shouldNotPrintDirectly(Context,
4440 CO->getFalseExpr()->getType(),
4441 CO->getFalseExpr());
4442
4443 if (TrueTy == FalseTy)
4444 return std::make_pair(TrueTy, TrueName);
4445 else if (TrueTy.isNull())
4446 return std::make_pair(FalseTy, FalseName);
4447 else if (FalseTy.isNull())
4448 return std::make_pair(TrueTy, TrueName);
4449 }
4450
4451 return std::make_pair(QualType(), StringRef());
4452}
4453
Richard Smith55ce3522012-06-25 20:30:08 +00004454bool
4455CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4456 const char *StartSpecifier,
4457 unsigned SpecifierLen,
4458 const Expr *E) {
4459 using namespace analyze_format_string;
4460 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004461 // Now type check the data expression that matches the
4462 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004463 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4464 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004465 if (!AT.isValid())
4466 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004467
Jordan Rose598ec092012-12-05 18:44:40 +00004468 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004469 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4470 ExprTy = TET->getUnderlyingExpr()->getType();
4471 }
4472
Seth Cantrellb4802962015-03-04 03:12:10 +00004473 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4474
4475 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004476 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004477 }
Jordan Rose98709982012-06-04 22:48:57 +00004478
Jordan Rose22b74712012-09-05 22:56:19 +00004479 // Look through argument promotions for our error message's reported type.
4480 // This includes the integral and floating promotions, but excludes array
4481 // and function pointer decay; seeing that an argument intended to be a
4482 // string has type 'char [6]' is probably more confusing than 'char *'.
4483 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4484 if (ICE->getCastKind() == CK_IntegralCast ||
4485 ICE->getCastKind() == CK_FloatingCast) {
4486 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004487 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004488
4489 // Check if we didn't match because of an implicit cast from a 'char'
4490 // or 'short' to an 'int'. This is done because printf is a varargs
4491 // function.
4492 if (ICE->getType() == S.Context.IntTy ||
4493 ICE->getType() == S.Context.UnsignedIntTy) {
4494 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004495 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004496 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004497 }
Jordan Rose98709982012-06-04 22:48:57 +00004498 }
Jordan Rose598ec092012-12-05 18:44:40 +00004499 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4500 // Special case for 'a', which has type 'int' in C.
4501 // Note, however, that we do /not/ want to treat multibyte constants like
4502 // 'MooV' as characters! This form is deprecated but still exists.
4503 if (ExprTy == S.Context.IntTy)
4504 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4505 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004506 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004507
Jordan Rosebc53ed12014-05-31 04:12:14 +00004508 // Look through enums to their underlying type.
4509 bool IsEnum = false;
4510 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4511 ExprTy = EnumTy->getDecl()->getIntegerType();
4512 IsEnum = true;
4513 }
4514
Jordan Rose0e5badd2012-12-05 18:44:49 +00004515 // %C in an Objective-C context prints a unichar, not a wchar_t.
4516 // If the argument is an integer of some kind, believe the %C and suggest
4517 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004518 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004519 if (ObjCContext &&
4520 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4521 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4522 !ExprTy->isCharType()) {
4523 // 'unichar' is defined as a typedef of unsigned short, but we should
4524 // prefer using the typedef if it is visible.
4525 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004526
4527 // While we are here, check if the value is an IntegerLiteral that happens
4528 // to be within the valid range.
4529 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4530 const llvm::APInt &V = IL->getValue();
4531 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4532 return true;
4533 }
4534
Jordan Rose0e5badd2012-12-05 18:44:49 +00004535 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4536 Sema::LookupOrdinaryName);
4537 if (S.LookupName(Result, S.getCurScope())) {
4538 NamedDecl *ND = Result.getFoundDecl();
4539 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4540 if (TD->getUnderlyingType() == IntendedTy)
4541 IntendedTy = S.Context.getTypedefType(TD);
4542 }
4543 }
4544 }
4545
4546 // Special-case some of Darwin's platform-independence types by suggesting
4547 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004548 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004549 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004550 QualType CastTy;
4551 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4552 if (!CastTy.isNull()) {
4553 IntendedTy = CastTy;
4554 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004555 }
4556 }
4557
Jordan Rose22b74712012-09-05 22:56:19 +00004558 // We may be able to offer a FixItHint if it is a supported type.
4559 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004560 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004561 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004562
Jordan Rose22b74712012-09-05 22:56:19 +00004563 if (success) {
4564 // Get the fix string from the fixed format specifier
4565 SmallString<16> buf;
4566 llvm::raw_svector_ostream os(buf);
4567 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004568
Jordan Roseaee34382012-09-05 22:56:26 +00004569 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4570
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004571 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004572 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4573 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4574 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4575 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004576 // In this case, the specifier is wrong and should be changed to match
4577 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004578 EmitFormatDiagnostic(S.PDiag(diag)
4579 << AT.getRepresentativeTypeName(S.Context)
4580 << IntendedTy << IsEnum << E->getSourceRange(),
4581 E->getLocStart(),
4582 /*IsStringLocation*/ false, SpecRange,
4583 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004584
4585 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004586 // The canonical type for formatting this value is different from the
4587 // actual type of the expression. (This occurs, for example, with Darwin's
4588 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4589 // should be printed as 'long' for 64-bit compatibility.)
4590 // Rather than emitting a normal format/argument mismatch, we want to
4591 // add a cast to the recommended type (and correct the format string
4592 // if necessary).
4593 SmallString<16> CastBuf;
4594 llvm::raw_svector_ostream CastFix(CastBuf);
4595 CastFix << "(";
4596 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4597 CastFix << ")";
4598
4599 SmallVector<FixItHint,4> Hints;
4600 if (!AT.matchesType(S.Context, IntendedTy))
4601 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4602
4603 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4604 // If there's already a cast present, just replace it.
4605 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4606 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4607
4608 } else if (!requiresParensToAddCast(E)) {
4609 // If the expression has high enough precedence,
4610 // just write the C-style cast.
4611 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4612 CastFix.str()));
4613 } else {
4614 // Otherwise, add parens around the expression as well as the cast.
4615 CastFix << "(";
4616 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4617 CastFix.str()));
4618
Alp Tokerb6cc5922014-05-03 03:45:55 +00004619 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004620 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4621 }
4622
Jordan Rose0e5badd2012-12-05 18:44:49 +00004623 if (ShouldNotPrintDirectly) {
4624 // The expression has a type that should not be printed directly.
4625 // We extract the name from the typedef because we don't want to show
4626 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004627 StringRef Name;
4628 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4629 Name = TypedefTy->getDecl()->getName();
4630 else
4631 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004632 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004633 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004634 << E->getSourceRange(),
4635 E->getLocStart(), /*IsStringLocation=*/false,
4636 SpecRange, Hints);
4637 } else {
4638 // In this case, the expression could be printed using a different
4639 // specifier, but we've decided that the specifier is probably correct
4640 // and we should cast instead. Just use the normal warning message.
4641 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004642 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4643 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004644 << E->getSourceRange(),
4645 E->getLocStart(), /*IsStringLocation*/false,
4646 SpecRange, Hints);
4647 }
Jordan Roseaee34382012-09-05 22:56:26 +00004648 }
Jordan Rose22b74712012-09-05 22:56:19 +00004649 } else {
4650 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4651 SpecifierLen);
4652 // Since the warning for passing non-POD types to variadic functions
4653 // was deferred until now, we emit a warning for non-POD
4654 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004655 switch (S.isValidVarArgType(ExprTy)) {
4656 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004657 case Sema::VAK_ValidInCXX11: {
4658 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4659 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4660 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4661 }
Richard Smithd7293d72013-08-05 18:49:43 +00004662
Seth Cantrellb4802962015-03-04 03:12:10 +00004663 EmitFormatDiagnostic(
4664 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4665 << IsEnum << CSR << E->getSourceRange(),
4666 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4667 break;
4668 }
Richard Smithd7293d72013-08-05 18:49:43 +00004669 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004670 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004671 EmitFormatDiagnostic(
4672 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004673 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004674 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004675 << CallType
4676 << AT.getRepresentativeTypeName(S.Context)
4677 << CSR
4678 << E->getSourceRange(),
4679 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004680 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004681 break;
4682
4683 case Sema::VAK_Invalid:
4684 if (ExprTy->isObjCObjectType())
4685 EmitFormatDiagnostic(
4686 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4687 << S.getLangOpts().CPlusPlus11
4688 << ExprTy
4689 << CallType
4690 << AT.getRepresentativeTypeName(S.Context)
4691 << CSR
4692 << E->getSourceRange(),
4693 E->getLocStart(), /*IsStringLocation*/false, CSR);
4694 else
4695 // FIXME: If this is an initializer list, suggest removing the braces
4696 // or inserting a cast to the target type.
4697 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4698 << isa<InitListExpr>(E) << ExprTy << CallType
4699 << AT.getRepresentativeTypeName(S.Context)
4700 << E->getSourceRange();
4701 break;
4702 }
4703
4704 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4705 "format string specifier index out of range");
4706 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004707 }
4708
Ted Kremenekab278de2010-01-28 23:39:18 +00004709 return true;
4710}
4711
Ted Kremenek02087932010-07-16 02:11:22 +00004712//===--- CHECK: Scanf format string checking ------------------------------===//
4713
4714namespace {
4715class CheckScanfHandler : public CheckFormatHandler {
4716public:
4717 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4718 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004719 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004720 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004721 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004722 Sema::VariadicCallType CallType,
4723 llvm::SmallBitVector &CheckedVarArgs)
4724 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4725 numDataArgs, beg, hasVAListArg,
4726 Args, formatIdx, inFunctionCall, CallType,
4727 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004728 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004729
4730 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4731 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004732 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004733
4734 bool HandleInvalidScanfConversionSpecifier(
4735 const analyze_scanf::ScanfSpecifier &FS,
4736 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004737 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004738
Craig Toppere14c0f82014-03-12 04:55:44 +00004739 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004740};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004741}
Ted Kremenekab278de2010-01-28 23:39:18 +00004742
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004743void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4744 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004745 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4746 getLocationOfByte(end), /*IsStringLocation*/true,
4747 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004748}
4749
Ted Kremenekce815422010-07-19 21:25:57 +00004750bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4751 const analyze_scanf::ScanfSpecifier &FS,
4752 const char *startSpecifier,
4753 unsigned specifierLen) {
4754
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004755 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004756 FS.getConversionSpecifier();
4757
4758 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4759 getLocationOfByte(CS.getStart()),
4760 startSpecifier, specifierLen,
4761 CS.getStart(), CS.getLength());
4762}
4763
Ted Kremenek02087932010-07-16 02:11:22 +00004764bool CheckScanfHandler::HandleScanfSpecifier(
4765 const analyze_scanf::ScanfSpecifier &FS,
4766 const char *startSpecifier,
4767 unsigned specifierLen) {
4768
4769 using namespace analyze_scanf;
4770 using namespace analyze_format_string;
4771
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004772 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004773
Ted Kremenek6cd69422010-07-19 22:01:06 +00004774 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4775 // be used to decide if we are using positional arguments consistently.
4776 if (FS.consumesDataArgument()) {
4777 if (atFirstArg) {
4778 atFirstArg = false;
4779 usesPositionalArgs = FS.usesPositionalArg();
4780 }
4781 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004782 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4783 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004784 return false;
4785 }
Ted Kremenek02087932010-07-16 02:11:22 +00004786 }
4787
4788 // Check if the field with is non-zero.
4789 const OptionalAmount &Amt = FS.getFieldWidth();
4790 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4791 if (Amt.getConstantAmount() == 0) {
4792 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4793 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004794 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4795 getLocationOfByte(Amt.getStart()),
4796 /*IsStringLocation*/true, R,
4797 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004798 }
4799 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004800
Ted Kremenek02087932010-07-16 02:11:22 +00004801 if (!FS.consumesDataArgument()) {
4802 // FIXME: Technically specifying a precision or field width here
4803 // makes no sense. Worth issuing a warning at some point.
4804 return true;
4805 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004806
Ted Kremenek02087932010-07-16 02:11:22 +00004807 // Consume the argument.
4808 unsigned argIndex = FS.getArgIndex();
4809 if (argIndex < NumDataArgs) {
4810 // The check to see if the argIndex is valid will come later.
4811 // We set the bit here because we may exit early from this
4812 // function if we encounter some other error.
4813 CoveredArgs.set(argIndex);
4814 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004815
Ted Kremenek4407ea42010-07-20 20:04:47 +00004816 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004817 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004818 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4819 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004820 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004821 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004822 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004823 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4824 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004825
Jordan Rose92303592012-09-08 04:00:03 +00004826 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4827 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4828
Ted Kremenek02087932010-07-16 02:11:22 +00004829 // The remaining checks depend on the data arguments.
4830 if (HasVAListArg)
4831 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004832
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004833 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004834 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004835
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004836 // Check that the argument type matches the format specifier.
4837 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004838 if (!Ex)
4839 return true;
4840
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004841 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004842
4843 if (!AT.isValid()) {
4844 return true;
4845 }
4846
Seth Cantrellb4802962015-03-04 03:12:10 +00004847 analyze_format_string::ArgType::MatchKind match =
4848 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004849 if (match == analyze_format_string::ArgType::Match) {
4850 return true;
4851 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004852
Seth Cantrell79340072015-03-04 05:58:08 +00004853 ScanfSpecifier fixedFS = FS;
4854 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4855 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004856
Seth Cantrell79340072015-03-04 05:58:08 +00004857 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4858 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4859 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4860 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004861
Seth Cantrell79340072015-03-04 05:58:08 +00004862 if (success) {
4863 // Get the fix string from the fixed format specifier.
4864 SmallString<128> buf;
4865 llvm::raw_svector_ostream os(buf);
4866 fixedFS.toString(os);
4867
4868 EmitFormatDiagnostic(
4869 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4870 << Ex->getType() << false << Ex->getSourceRange(),
4871 Ex->getLocStart(),
4872 /*IsStringLocation*/ false,
4873 getSpecifierRange(startSpecifier, specifierLen),
4874 FixItHint::CreateReplacement(
4875 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4876 } else {
4877 EmitFormatDiagnostic(S.PDiag(diag)
4878 << AT.getRepresentativeTypeName(S.Context)
4879 << Ex->getType() << false << Ex->getSourceRange(),
4880 Ex->getLocStart(),
4881 /*IsStringLocation*/ false,
4882 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004883 }
4884
Ted Kremenek02087932010-07-16 02:11:22 +00004885 return true;
4886}
4887
4888void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004889 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004890 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004891 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004892 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004893 bool inFunctionCall, VariadicCallType CallType,
4894 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004895
Ted Kremenekab278de2010-01-28 23:39:18 +00004896 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004897 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004898 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004899 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004900 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4901 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004902 return;
4903 }
Ted Kremenek02087932010-07-16 02:11:22 +00004904
Ted Kremenekab278de2010-01-28 23:39:18 +00004905 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004906 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004907 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004908 // Account for cases where the string literal is truncated in a declaration.
4909 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4910 assert(T && "String literal not of constant array type!");
4911 size_t TypeSize = T->getSize().getZExtValue();
4912 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004913 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004914
4915 // Emit a warning if the string literal is truncated and does not contain an
4916 // embedded null character.
4917 if (TypeSize <= StrRef.size() &&
4918 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4919 CheckFormatHandler::EmitFormatDiagnostic(
4920 *this, inFunctionCall, Args[format_idx],
4921 PDiag(diag::warn_printf_format_string_not_null_terminated),
4922 FExpr->getLocStart(),
4923 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4924 return;
4925 }
4926
Ted Kremenekab278de2010-01-28 23:39:18 +00004927 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004928 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004929 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004930 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004931 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4932 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004933 return;
4934 }
Ted Kremenek02087932010-07-16 02:11:22 +00004935
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004936 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004937 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004938 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004939 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004940 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004941 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004942
Hans Wennborg23926bd2011-12-15 10:25:47 +00004943 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004944 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004945 Context.getTargetInfo(),
4946 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004947 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004948 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004949 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004950 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004951 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004952
Hans Wennborg23926bd2011-12-15 10:25:47 +00004953 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004954 getLangOpts(),
4955 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004956 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004957 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004958}
4959
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004960bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4961 // Str - The format string. NOTE: this is NOT null-terminated!
4962 StringRef StrRef = FExpr->getString();
4963 const char *Str = StrRef.data();
4964 // Account for cases where the string literal is truncated in a declaration.
4965 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4966 assert(T && "String literal not of constant array type!");
4967 size_t TypeSize = T->getSize().getZExtValue();
4968 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4969 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4970 getLangOpts(),
4971 Context.getTargetInfo());
4972}
4973
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004974//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4975
4976// Returns the related absolute value function that is larger, of 0 if one
4977// does not exist.
4978static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4979 switch (AbsFunction) {
4980 default:
4981 return 0;
4982
4983 case Builtin::BI__builtin_abs:
4984 return Builtin::BI__builtin_labs;
4985 case Builtin::BI__builtin_labs:
4986 return Builtin::BI__builtin_llabs;
4987 case Builtin::BI__builtin_llabs:
4988 return 0;
4989
4990 case Builtin::BI__builtin_fabsf:
4991 return Builtin::BI__builtin_fabs;
4992 case Builtin::BI__builtin_fabs:
4993 return Builtin::BI__builtin_fabsl;
4994 case Builtin::BI__builtin_fabsl:
4995 return 0;
4996
4997 case Builtin::BI__builtin_cabsf:
4998 return Builtin::BI__builtin_cabs;
4999 case Builtin::BI__builtin_cabs:
5000 return Builtin::BI__builtin_cabsl;
5001 case Builtin::BI__builtin_cabsl:
5002 return 0;
5003
5004 case Builtin::BIabs:
5005 return Builtin::BIlabs;
5006 case Builtin::BIlabs:
5007 return Builtin::BIllabs;
5008 case Builtin::BIllabs:
5009 return 0;
5010
5011 case Builtin::BIfabsf:
5012 return Builtin::BIfabs;
5013 case Builtin::BIfabs:
5014 return Builtin::BIfabsl;
5015 case Builtin::BIfabsl:
5016 return 0;
5017
5018 case Builtin::BIcabsf:
5019 return Builtin::BIcabs;
5020 case Builtin::BIcabs:
5021 return Builtin::BIcabsl;
5022 case Builtin::BIcabsl:
5023 return 0;
5024 }
5025}
5026
5027// Returns the argument type of the absolute value function.
5028static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5029 unsigned AbsType) {
5030 if (AbsType == 0)
5031 return QualType();
5032
5033 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5034 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5035 if (Error != ASTContext::GE_None)
5036 return QualType();
5037
5038 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5039 if (!FT)
5040 return QualType();
5041
5042 if (FT->getNumParams() != 1)
5043 return QualType();
5044
5045 return FT->getParamType(0);
5046}
5047
5048// Returns the best absolute value function, or zero, based on type and
5049// current absolute value function.
5050static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5051 unsigned AbsFunctionKind) {
5052 unsigned BestKind = 0;
5053 uint64_t ArgSize = Context.getTypeSize(ArgType);
5054 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5055 Kind = getLargerAbsoluteValueFunction(Kind)) {
5056 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5057 if (Context.getTypeSize(ParamType) >= ArgSize) {
5058 if (BestKind == 0)
5059 BestKind = Kind;
5060 else if (Context.hasSameType(ParamType, ArgType)) {
5061 BestKind = Kind;
5062 break;
5063 }
5064 }
5065 }
5066 return BestKind;
5067}
5068
5069enum AbsoluteValueKind {
5070 AVK_Integer,
5071 AVK_Floating,
5072 AVK_Complex
5073};
5074
5075static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5076 if (T->isIntegralOrEnumerationType())
5077 return AVK_Integer;
5078 if (T->isRealFloatingType())
5079 return AVK_Floating;
5080 if (T->isAnyComplexType())
5081 return AVK_Complex;
5082
5083 llvm_unreachable("Type not integer, floating, or complex");
5084}
5085
5086// Changes the absolute value function to a different type. Preserves whether
5087// the function is a builtin.
5088static unsigned changeAbsFunction(unsigned AbsKind,
5089 AbsoluteValueKind ValueKind) {
5090 switch (ValueKind) {
5091 case AVK_Integer:
5092 switch (AbsKind) {
5093 default:
5094 return 0;
5095 case Builtin::BI__builtin_fabsf:
5096 case Builtin::BI__builtin_fabs:
5097 case Builtin::BI__builtin_fabsl:
5098 case Builtin::BI__builtin_cabsf:
5099 case Builtin::BI__builtin_cabs:
5100 case Builtin::BI__builtin_cabsl:
5101 return Builtin::BI__builtin_abs;
5102 case Builtin::BIfabsf:
5103 case Builtin::BIfabs:
5104 case Builtin::BIfabsl:
5105 case Builtin::BIcabsf:
5106 case Builtin::BIcabs:
5107 case Builtin::BIcabsl:
5108 return Builtin::BIabs;
5109 }
5110 case AVK_Floating:
5111 switch (AbsKind) {
5112 default:
5113 return 0;
5114 case Builtin::BI__builtin_abs:
5115 case Builtin::BI__builtin_labs:
5116 case Builtin::BI__builtin_llabs:
5117 case Builtin::BI__builtin_cabsf:
5118 case Builtin::BI__builtin_cabs:
5119 case Builtin::BI__builtin_cabsl:
5120 return Builtin::BI__builtin_fabsf;
5121 case Builtin::BIabs:
5122 case Builtin::BIlabs:
5123 case Builtin::BIllabs:
5124 case Builtin::BIcabsf:
5125 case Builtin::BIcabs:
5126 case Builtin::BIcabsl:
5127 return Builtin::BIfabsf;
5128 }
5129 case AVK_Complex:
5130 switch (AbsKind) {
5131 default:
5132 return 0;
5133 case Builtin::BI__builtin_abs:
5134 case Builtin::BI__builtin_labs:
5135 case Builtin::BI__builtin_llabs:
5136 case Builtin::BI__builtin_fabsf:
5137 case Builtin::BI__builtin_fabs:
5138 case Builtin::BI__builtin_fabsl:
5139 return Builtin::BI__builtin_cabsf;
5140 case Builtin::BIabs:
5141 case Builtin::BIlabs:
5142 case Builtin::BIllabs:
5143 case Builtin::BIfabsf:
5144 case Builtin::BIfabs:
5145 case Builtin::BIfabsl:
5146 return Builtin::BIcabsf;
5147 }
5148 }
5149 llvm_unreachable("Unable to convert function");
5150}
5151
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005152static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005153 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5154 if (!FnInfo)
5155 return 0;
5156
5157 switch (FDecl->getBuiltinID()) {
5158 default:
5159 return 0;
5160 case Builtin::BI__builtin_abs:
5161 case Builtin::BI__builtin_fabs:
5162 case Builtin::BI__builtin_fabsf:
5163 case Builtin::BI__builtin_fabsl:
5164 case Builtin::BI__builtin_labs:
5165 case Builtin::BI__builtin_llabs:
5166 case Builtin::BI__builtin_cabs:
5167 case Builtin::BI__builtin_cabsf:
5168 case Builtin::BI__builtin_cabsl:
5169 case Builtin::BIabs:
5170 case Builtin::BIlabs:
5171 case Builtin::BIllabs:
5172 case Builtin::BIfabs:
5173 case Builtin::BIfabsf:
5174 case Builtin::BIfabsl:
5175 case Builtin::BIcabs:
5176 case Builtin::BIcabsf:
5177 case Builtin::BIcabsl:
5178 return FDecl->getBuiltinID();
5179 }
5180 llvm_unreachable("Unknown Builtin type");
5181}
5182
5183// If the replacement is valid, emit a note with replacement function.
5184// Additionally, suggest including the proper header if not already included.
5185static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005186 unsigned AbsKind, QualType ArgType) {
5187 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005188 const char *HeaderName = nullptr;
5189 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005190 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5191 FunctionName = "std::abs";
5192 if (ArgType->isIntegralOrEnumerationType()) {
5193 HeaderName = "cstdlib";
5194 } else if (ArgType->isRealFloatingType()) {
5195 HeaderName = "cmath";
5196 } else {
5197 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005198 }
Richard Trieubeffb832014-04-15 23:47:53 +00005199
5200 // Lookup all std::abs
5201 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005202 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005203 R.suppressDiagnostics();
5204 S.LookupQualifiedName(R, Std);
5205
5206 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005207 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005208 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5209 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5210 } else {
5211 FDecl = dyn_cast<FunctionDecl>(I);
5212 }
5213 if (!FDecl)
5214 continue;
5215
5216 // Found std::abs(), check that they are the right ones.
5217 if (FDecl->getNumParams() != 1)
5218 continue;
5219
5220 // Check that the parameter type can handle the argument.
5221 QualType ParamType = FDecl->getParamDecl(0)->getType();
5222 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5223 S.Context.getTypeSize(ArgType) <=
5224 S.Context.getTypeSize(ParamType)) {
5225 // Found a function, don't need the header hint.
5226 EmitHeaderHint = false;
5227 break;
5228 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005229 }
Richard Trieubeffb832014-04-15 23:47:53 +00005230 }
5231 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005232 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005233 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5234
5235 if (HeaderName) {
5236 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5237 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5238 R.suppressDiagnostics();
5239 S.LookupName(R, S.getCurScope());
5240
5241 if (R.isSingleResult()) {
5242 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5243 if (FD && FD->getBuiltinID() == AbsKind) {
5244 EmitHeaderHint = false;
5245 } else {
5246 return;
5247 }
5248 } else if (!R.empty()) {
5249 return;
5250 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005251 }
5252 }
5253
5254 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005255 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005256
Richard Trieubeffb832014-04-15 23:47:53 +00005257 if (!HeaderName)
5258 return;
5259
5260 if (!EmitHeaderHint)
5261 return;
5262
Alp Toker5d96e0a2014-07-11 20:53:51 +00005263 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5264 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005265}
5266
5267static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5268 if (!FDecl)
5269 return false;
5270
5271 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5272 return false;
5273
5274 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5275
5276 while (ND && ND->isInlineNamespace()) {
5277 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005278 }
Richard Trieubeffb832014-04-15 23:47:53 +00005279
5280 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5281 return false;
5282
5283 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5284 return false;
5285
5286 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005287}
5288
5289// Warn when using the wrong abs() function.
5290void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5291 const FunctionDecl *FDecl,
5292 IdentifierInfo *FnInfo) {
5293 if (Call->getNumArgs() != 1)
5294 return;
5295
5296 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005297 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5298 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005299 return;
5300
5301 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5302 QualType ParamType = Call->getArg(0)->getType();
5303
Alp Toker5d96e0a2014-07-11 20:53:51 +00005304 // Unsigned types cannot be negative. Suggest removing the absolute value
5305 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005306 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005307 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005308 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005309 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5310 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005311 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005312 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5313 return;
5314 }
5315
David Majnemer7f77eb92015-11-15 03:04:34 +00005316 // Taking the absolute value of a pointer is very suspicious, they probably
5317 // wanted to index into an array, dereference a pointer, call a function, etc.
5318 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5319 unsigned DiagType = 0;
5320 if (ArgType->isFunctionType())
5321 DiagType = 1;
5322 else if (ArgType->isArrayType())
5323 DiagType = 2;
5324
5325 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5326 return;
5327 }
5328
Richard Trieubeffb832014-04-15 23:47:53 +00005329 // std::abs has overloads which prevent most of the absolute value problems
5330 // from occurring.
5331 if (IsStdAbs)
5332 return;
5333
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005334 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5335 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5336
5337 // The argument and parameter are the same kind. Check if they are the right
5338 // size.
5339 if (ArgValueKind == ParamValueKind) {
5340 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5341 return;
5342
5343 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5344 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5345 << FDecl << ArgType << ParamType;
5346
5347 if (NewAbsKind == 0)
5348 return;
5349
5350 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005351 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005352 return;
5353 }
5354
5355 // ArgValueKind != ParamValueKind
5356 // The wrong type of absolute value function was used. Attempt to find the
5357 // proper one.
5358 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5359 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5360 if (NewAbsKind == 0)
5361 return;
5362
5363 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5364 << FDecl << ParamValueKind << ArgValueKind;
5365
5366 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005367 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005368 return;
5369}
5370
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005371//===--- CHECK: Standard memory functions ---------------------------------===//
5372
Nico Weber0e6daef2013-12-26 23:38:39 +00005373/// \brief Takes the expression passed to the size_t parameter of functions
5374/// such as memcmp, strncat, etc and warns if it's a comparison.
5375///
5376/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5377static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5378 IdentifierInfo *FnName,
5379 SourceLocation FnLoc,
5380 SourceLocation RParenLoc) {
5381 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5382 if (!Size)
5383 return false;
5384
5385 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5386 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5387 return false;
5388
Nico Weber0e6daef2013-12-26 23:38:39 +00005389 SourceRange SizeRange = Size->getSourceRange();
5390 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5391 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005392 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005393 << FnName << FixItHint::CreateInsertion(
5394 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005395 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005396 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005397 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005398 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5399 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005400
5401 return true;
5402}
5403
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005404/// \brief Determine whether the given type is or contains a dynamic class type
5405/// (e.g., whether it has a vtable).
5406static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5407 bool &IsContained) {
5408 // Look through array types while ignoring qualifiers.
5409 const Type *Ty = T->getBaseElementTypeUnsafe();
5410 IsContained = false;
5411
5412 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5413 RD = RD ? RD->getDefinition() : nullptr;
5414 if (!RD)
5415 return nullptr;
5416
5417 if (RD->isDynamicClass())
5418 return RD;
5419
5420 // Check all the fields. If any bases were dynamic, the class is dynamic.
5421 // It's impossible for a class to transitively contain itself by value, so
5422 // infinite recursion is impossible.
5423 for (auto *FD : RD->fields()) {
5424 bool SubContained;
5425 if (const CXXRecordDecl *ContainedRD =
5426 getContainedDynamicClass(FD->getType(), SubContained)) {
5427 IsContained = true;
5428 return ContainedRD;
5429 }
5430 }
5431
5432 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005433}
5434
Chandler Carruth889ed862011-06-21 23:04:20 +00005435/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005436/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005437static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005438 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005439 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5440 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5441 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005442
Craig Topperc3ec1492014-05-26 06:22:03 +00005443 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005444}
5445
Chandler Carruth889ed862011-06-21 23:04:20 +00005446/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005447static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005448 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5449 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5450 if (SizeOf->getKind() == clang::UETT_SizeOf)
5451 return SizeOf->getTypeOfArgument();
5452
5453 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005454}
5455
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005456/// \brief Check for dangerous or invalid arguments to memset().
5457///
Chandler Carruthac687262011-06-03 06:23:57 +00005458/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005459/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5460/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005461///
5462/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005463void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005464 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005465 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005466 assert(BId != 0);
5467
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005468 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005469 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005470 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005471 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005472 return;
5473
Anna Zaks22122702012-01-17 00:37:07 +00005474 unsigned LastArg = (BId == Builtin::BImemset ||
5475 BId == Builtin::BIstrndup ? 1 : 2);
5476 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005477 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005478
Nico Weber0e6daef2013-12-26 23:38:39 +00005479 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5480 Call->getLocStart(), Call->getRParenLoc()))
5481 return;
5482
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005483 // We have special checking when the length is a sizeof expression.
5484 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5485 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5486 llvm::FoldingSetNodeID SizeOfArgID;
5487
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005488 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5489 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005490 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005491
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005492 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005493 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005494 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005495 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005496
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005497 // Never warn about void type pointers. This can be used to suppress
5498 // false positives.
5499 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005500 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005501
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005502 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5503 // actually comparing the expressions for equality. Because computing the
5504 // expression IDs can be expensive, we only do this if the diagnostic is
5505 // enabled.
5506 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005507 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5508 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005509 // We only compute IDs for expressions if the warning is enabled, and
5510 // cache the sizeof arg's ID.
5511 if (SizeOfArgID == llvm::FoldingSetNodeID())
5512 SizeOfArg->Profile(SizeOfArgID, Context, true);
5513 llvm::FoldingSetNodeID DestID;
5514 Dest->Profile(DestID, Context, true);
5515 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005516 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5517 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005518 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005519 StringRef ReadableName = FnName->getName();
5520
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005521 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005522 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005523 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005524 if (!PointeeTy->isIncompleteType() &&
5525 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005526 ActionIdx = 2; // If the pointee's size is sizeof(char),
5527 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005528
5529 // If the function is defined as a builtin macro, do not show macro
5530 // expansion.
5531 SourceLocation SL = SizeOfArg->getExprLoc();
5532 SourceRange DSR = Dest->getSourceRange();
5533 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005534 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005535
5536 if (SM.isMacroArgExpansion(SL)) {
5537 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5538 SL = SM.getSpellingLoc(SL);
5539 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5540 SM.getSpellingLoc(DSR.getEnd()));
5541 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5542 SM.getSpellingLoc(SSR.getEnd()));
5543 }
5544
Anna Zaksd08d9152012-05-30 23:14:52 +00005545 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005546 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005547 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005548 << PointeeTy
5549 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005550 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005551 << SSR);
5552 DiagRuntimeBehavior(SL, SizeOfArg,
5553 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5554 << ActionIdx
5555 << SSR);
5556
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005557 break;
5558 }
5559 }
5560
5561 // Also check for cases where the sizeof argument is the exact same
5562 // type as the memory argument, and where it points to a user-defined
5563 // record type.
5564 if (SizeOfArgTy != QualType()) {
5565 if (PointeeTy->isRecordType() &&
5566 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5567 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5568 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5569 << FnName << SizeOfArgTy << ArgIdx
5570 << PointeeTy << Dest->getSourceRange()
5571 << LenExpr->getSourceRange());
5572 break;
5573 }
Nico Weberc5e73862011-06-14 16:14:58 +00005574 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005575 } else if (DestTy->isArrayType()) {
5576 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005577 }
Nico Weberc5e73862011-06-14 16:14:58 +00005578
Nico Weberc44b35e2015-03-21 17:37:46 +00005579 if (PointeeTy == QualType())
5580 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005581
Nico Weberc44b35e2015-03-21 17:37:46 +00005582 // Always complain about dynamic classes.
5583 bool IsContained;
5584 if (const CXXRecordDecl *ContainedRD =
5585 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005586
Nico Weberc44b35e2015-03-21 17:37:46 +00005587 unsigned OperationType = 0;
5588 // "overwritten" if we're warning about the destination for any call
5589 // but memcmp; otherwise a verb appropriate to the call.
5590 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5591 if (BId == Builtin::BImemcpy)
5592 OperationType = 1;
5593 else if(BId == Builtin::BImemmove)
5594 OperationType = 2;
5595 else if (BId == Builtin::BImemcmp)
5596 OperationType = 3;
5597 }
5598
John McCall31168b02011-06-15 23:02:42 +00005599 DiagRuntimeBehavior(
5600 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005601 PDiag(diag::warn_dyn_class_memaccess)
5602 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5603 << FnName << IsContained << ContainedRD << OperationType
5604 << Call->getCallee()->getSourceRange());
5605 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5606 BId != Builtin::BImemset)
5607 DiagRuntimeBehavior(
5608 Dest->getExprLoc(), Dest,
5609 PDiag(diag::warn_arc_object_memaccess)
5610 << ArgIdx << FnName << PointeeTy
5611 << Call->getCallee()->getSourceRange());
5612 else
5613 continue;
5614
5615 DiagRuntimeBehavior(
5616 Dest->getExprLoc(), Dest,
5617 PDiag(diag::note_bad_memaccess_silence)
5618 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5619 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005620 }
Nico Weberc44b35e2015-03-21 17:37:46 +00005621
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005622}
5623
Ted Kremenek6865f772011-08-18 20:55:45 +00005624// A little helper routine: ignore addition and subtraction of integer literals.
5625// This intentionally does not ignore all integer constant expressions because
5626// we don't want to remove sizeof().
5627static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5628 Ex = Ex->IgnoreParenCasts();
5629
5630 for (;;) {
5631 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5632 if (!BO || !BO->isAdditiveOp())
5633 break;
5634
5635 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5636 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5637
5638 if (isa<IntegerLiteral>(RHS))
5639 Ex = LHS;
5640 else if (isa<IntegerLiteral>(LHS))
5641 Ex = RHS;
5642 else
5643 break;
5644 }
5645
5646 return Ex;
5647}
5648
Anna Zaks13b08572012-08-08 21:42:23 +00005649static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5650 ASTContext &Context) {
5651 // Only handle constant-sized or VLAs, but not flexible members.
5652 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5653 // Only issue the FIXIT for arrays of size > 1.
5654 if (CAT->getSize().getSExtValue() <= 1)
5655 return false;
5656 } else if (!Ty->isVariableArrayType()) {
5657 return false;
5658 }
5659 return true;
5660}
5661
Ted Kremenek6865f772011-08-18 20:55:45 +00005662// Warn if the user has made the 'size' argument to strlcpy or strlcat
5663// be the size of the source, instead of the destination.
5664void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5665 IdentifierInfo *FnName) {
5666
5667 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005668 unsigned NumArgs = Call->getNumArgs();
5669 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005670 return;
5671
5672 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5673 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005674 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005675
5676 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5677 Call->getLocStart(), Call->getRParenLoc()))
5678 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005679
5680 // Look for 'strlcpy(dst, x, sizeof(x))'
5681 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5682 CompareWithSrc = Ex;
5683 else {
5684 // Look for 'strlcpy(dst, x, strlen(x))'
5685 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005686 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5687 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005688 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5689 }
5690 }
5691
5692 if (!CompareWithSrc)
5693 return;
5694
5695 // Determine if the argument to sizeof/strlen is equal to the source
5696 // argument. In principle there's all kinds of things you could do
5697 // here, for instance creating an == expression and evaluating it with
5698 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5699 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5700 if (!SrcArgDRE)
5701 return;
5702
5703 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5704 if (!CompareWithSrcDRE ||
5705 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5706 return;
5707
5708 const Expr *OriginalSizeArg = Call->getArg(2);
5709 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5710 << OriginalSizeArg->getSourceRange() << FnName;
5711
5712 // Output a FIXIT hint if the destination is an array (rather than a
5713 // pointer to an array). This could be enhanced to handle some
5714 // pointers if we know the actual size, like if DstArg is 'array+2'
5715 // we could say 'sizeof(array)-2'.
5716 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005717 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005718 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005719
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005720 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005721 llvm::raw_svector_ostream OS(sizeString);
5722 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005723 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005724 OS << ")";
5725
5726 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5727 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5728 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005729}
5730
Anna Zaks314cd092012-02-01 19:08:57 +00005731/// Check if two expressions refer to the same declaration.
5732static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5733 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5734 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5735 return D1->getDecl() == D2->getDecl();
5736 return false;
5737}
5738
5739static const Expr *getStrlenExprArg(const Expr *E) {
5740 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5741 const FunctionDecl *FD = CE->getDirectCallee();
5742 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005743 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005744 return CE->getArg(0)->IgnoreParenCasts();
5745 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005746 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005747}
5748
5749// Warn on anti-patterns as the 'size' argument to strncat.
5750// The correct size argument should look like following:
5751// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5752void Sema::CheckStrncatArguments(const CallExpr *CE,
5753 IdentifierInfo *FnName) {
5754 // Don't crash if the user has the wrong number of arguments.
5755 if (CE->getNumArgs() < 3)
5756 return;
5757 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5758 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5759 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5760
Nico Weber0e6daef2013-12-26 23:38:39 +00005761 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5762 CE->getRParenLoc()))
5763 return;
5764
Anna Zaks314cd092012-02-01 19:08:57 +00005765 // Identify common expressions, which are wrongly used as the size argument
5766 // to strncat and may lead to buffer overflows.
5767 unsigned PatternType = 0;
5768 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5769 // - sizeof(dst)
5770 if (referToTheSameDecl(SizeOfArg, DstArg))
5771 PatternType = 1;
5772 // - sizeof(src)
5773 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5774 PatternType = 2;
5775 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5776 if (BE->getOpcode() == BO_Sub) {
5777 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5778 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5779 // - sizeof(dst) - strlen(dst)
5780 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5781 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5782 PatternType = 1;
5783 // - sizeof(src) - (anything)
5784 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5785 PatternType = 2;
5786 }
5787 }
5788
5789 if (PatternType == 0)
5790 return;
5791
Anna Zaks5069aa32012-02-03 01:27:37 +00005792 // Generate the diagnostic.
5793 SourceLocation SL = LenArg->getLocStart();
5794 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005795 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005796
5797 // If the function is defined as a builtin macro, do not show macro expansion.
5798 if (SM.isMacroArgExpansion(SL)) {
5799 SL = SM.getSpellingLoc(SL);
5800 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5801 SM.getSpellingLoc(SR.getEnd()));
5802 }
5803
Anna Zaks13b08572012-08-08 21:42:23 +00005804 // Check if the destination is an array (rather than a pointer to an array).
5805 QualType DstTy = DstArg->getType();
5806 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5807 Context);
5808 if (!isKnownSizeArray) {
5809 if (PatternType == 1)
5810 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5811 else
5812 Diag(SL, diag::warn_strncat_src_size) << SR;
5813 return;
5814 }
5815
Anna Zaks314cd092012-02-01 19:08:57 +00005816 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005817 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005818 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005819 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005820
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005821 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005822 llvm::raw_svector_ostream OS(sizeString);
5823 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005824 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005825 OS << ") - ";
5826 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005827 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005828 OS << ") - 1";
5829
Anna Zaks5069aa32012-02-03 01:27:37 +00005830 Diag(SL, diag::note_strncat_wrong_size)
5831 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005832}
5833
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005834//===--- CHECK: Return Address of Stack Variable --------------------------===//
5835
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005836static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5837 Decl *ParentDecl);
5838static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5839 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005840
5841/// CheckReturnStackAddr - Check if a return statement returns the address
5842/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005843static void
5844CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5845 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005846
Craig Topperc3ec1492014-05-26 06:22:03 +00005847 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005848 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005849
5850 // Perform checking for returned stack addresses, local blocks,
5851 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005852 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005853 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005854 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005855 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005856 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005857 }
5858
Craig Topperc3ec1492014-05-26 06:22:03 +00005859 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005860 return; // Nothing suspicious was found.
5861
5862 SourceLocation diagLoc;
5863 SourceRange diagRange;
5864 if (refVars.empty()) {
5865 diagLoc = stackE->getLocStart();
5866 diagRange = stackE->getSourceRange();
5867 } else {
5868 // We followed through a reference variable. 'stackE' contains the
5869 // problematic expression but we will warn at the return statement pointing
5870 // at the reference variable. We will later display the "trail" of
5871 // reference variables using notes.
5872 diagLoc = refVars[0]->getLocStart();
5873 diagRange = refVars[0]->getSourceRange();
5874 }
5875
5876 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Craig Topperda7b27f2015-11-17 05:40:09 +00005877 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005878 << DR->getDecl()->getDeclName() << diagRange;
5879 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005880 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005881 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005882 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005883 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00005884 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
5885 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005886 }
5887
5888 // Display the "trail" of reference variables that we followed until we
5889 // found the problematic expression using notes.
5890 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5891 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5892 // If this var binds to another reference var, show the range of the next
5893 // var, otherwise the var binds to the problematic expression, in which case
5894 // show the range of the expression.
5895 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5896 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005897 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5898 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005899 }
5900}
5901
5902/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5903/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005904/// to a location on the stack, a local block, an address of a label, or a
5905/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005906/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005907/// encounter a subexpression that (1) clearly does not lead to one of the
5908/// above problematic expressions (2) is something we cannot determine leads to
5909/// a problematic expression based on such local checking.
5910///
5911/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5912/// the expression that they point to. Such variables are added to the
5913/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005914///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005915/// EvalAddr processes expressions that are pointers that are used as
5916/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005917/// At the base case of the recursion is a check for the above problematic
5918/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005919///
5920/// This implementation handles:
5921///
5922/// * pointer-to-pointer casts
5923/// * implicit conversions from array references to pointers
5924/// * taking the address of fields
5925/// * arbitrary interplay between "&" and "*" operators
5926/// * pointer arithmetic from an address of a stack variable
5927/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005928static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5929 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005930 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005931 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005932
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005933 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005934 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005935 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005936 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005937 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005938
Peter Collingbourne91147592011-04-15 00:35:48 +00005939 E = E->IgnoreParens();
5940
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005941 // Our "symbolic interpreter" is just a dispatch off the currently
5942 // viewed AST node. We then recursively traverse the AST by calling
5943 // EvalAddr and EvalVal appropriately.
5944 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005945 case Stmt::DeclRefExprClass: {
5946 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5947
Richard Smith40f08eb2014-01-30 22:05:38 +00005948 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005949 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005950 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005951
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005952 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5953 // If this is a reference variable, follow through to the expression that
5954 // it points to.
5955 if (V->hasLocalStorage() &&
5956 V->getType()->isReferenceType() && V->hasInit()) {
5957 // Add the reference variable to the "trail".
5958 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005959 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005960 }
5961
Craig Topperc3ec1492014-05-26 06:22:03 +00005962 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005963 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005964
Chris Lattner934edb22007-12-28 05:31:15 +00005965 case Stmt::UnaryOperatorClass: {
5966 // The only unary operator that make sense to handle here
5967 // is AddrOf. All others don't make sense as pointers.
5968 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005969
John McCalle3027922010-08-25 11:45:40 +00005970 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005971 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005972 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005973 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005974 }
Mike Stump11289f42009-09-09 15:08:12 +00005975
Chris Lattner934edb22007-12-28 05:31:15 +00005976 case Stmt::BinaryOperatorClass: {
5977 // Handle pointer arithmetic. All other binary operators are not valid
5978 // in this context.
5979 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005980 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005981
John McCalle3027922010-08-25 11:45:40 +00005982 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005983 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005984
Chris Lattner934edb22007-12-28 05:31:15 +00005985 Expr *Base = B->getLHS();
5986
5987 // Determine which argument is the real pointer base. It could be
5988 // the RHS argument instead of the LHS.
5989 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005990
Chris Lattner934edb22007-12-28 05:31:15 +00005991 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005992 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005993 }
Steve Naroff2752a172008-09-10 19:17:48 +00005994
Chris Lattner934edb22007-12-28 05:31:15 +00005995 // For conditional operators we need to see if either the LHS or RHS are
5996 // valid DeclRefExpr*s. If one of them is valid, we return it.
5997 case Stmt::ConditionalOperatorClass: {
5998 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005999
Chris Lattner934edb22007-12-28 05:31:15 +00006000 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006001 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
6002 if (Expr *LHSExpr = C->getLHS()) {
6003 // In C++, we can have a throw-expression, which has 'void' type.
6004 if (!LHSExpr->getType()->isVoidType())
6005 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006006 return LHS;
6007 }
Chris Lattner934edb22007-12-28 05:31:15 +00006008
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006009 // In C++, we can have a throw-expression, which has 'void' type.
6010 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006011 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006012
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006013 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006014 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006015
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006016 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006017 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006018 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006019 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006020
6021 case Stmt::AddrLabelExprClass:
6022 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006023
John McCall28fc7092011-11-10 05:35:25 +00006024 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006025 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6026 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006027
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006028 // For casts, we need to handle conversions from arrays to
6029 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006030 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006031 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006032 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006033 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006034 case Stmt::CXXStaticCastExprClass:
6035 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006036 case Stmt::CXXConstCastExprClass:
6037 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00006038 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
6039 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006040 case CK_LValueToRValue:
6041 case CK_NoOp:
6042 case CK_BaseToDerived:
6043 case CK_DerivedToBase:
6044 case CK_UncheckedDerivedToBase:
6045 case CK_Dynamic:
6046 case CK_CPointerToObjCPointerCast:
6047 case CK_BlockPointerToObjCPointerCast:
6048 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006049 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006050
6051 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006052 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006053
Richard Trieudadefde2014-07-02 04:39:38 +00006054 case CK_BitCast:
6055 if (SubExpr->getType()->isAnyPointerType() ||
6056 SubExpr->getType()->isBlockPointerType() ||
6057 SubExpr->getType()->isObjCQualifiedIdType())
6058 return EvalAddr(SubExpr, refVars, ParentDecl);
6059 else
6060 return nullptr;
6061
Eli Friedman8195ad72012-02-23 23:04:32 +00006062 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006063 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006064 }
Chris Lattner934edb22007-12-28 05:31:15 +00006065 }
Mike Stump11289f42009-09-09 15:08:12 +00006066
Douglas Gregorfe314812011-06-21 17:03:29 +00006067 case Stmt::MaterializeTemporaryExprClass:
6068 if (Expr *Result = EvalAddr(
6069 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006070 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006071 return Result;
6072
6073 return E;
6074
Chris Lattner934edb22007-12-28 05:31:15 +00006075 // Everything else: we simply don't reason about them.
6076 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006077 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006078 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006079}
Mike Stump11289f42009-09-09 15:08:12 +00006080
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006081
6082/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6083/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006084static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
6085 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00006086do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006087 // We should only be called for evaluating non-pointer expressions, or
6088 // expressions with a pointer type that are not used as references but instead
6089 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006090
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006091 // Our "symbolic interpreter" is just a dispatch off the currently
6092 // viewed AST node. We then recursively traverse the AST by calling
6093 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006094
6095 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006096 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00006097 case Stmt::ImplicitCastExprClass: {
6098 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00006099 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00006100 E = IE->getSubExpr();
6101 continue;
6102 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006103 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00006104 }
6105
John McCall28fc7092011-11-10 05:35:25 +00006106 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006107 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006108
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006109 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006110 // When we hit a DeclRefExpr we are looking at code that refers to a
6111 // variable's name. If it's not a reference variable we check if it has
6112 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006113 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006114
Richard Smith40f08eb2014-01-30 22:05:38 +00006115 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006116 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006117 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006118
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006119 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6120 // Check if it refers to itself, e.g. "int& i = i;".
6121 if (V == ParentDecl)
6122 return DR;
6123
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006124 if (V->hasLocalStorage()) {
6125 if (!V->getType()->isReferenceType())
6126 return DR;
6127
6128 // Reference variable, follow through to the expression that
6129 // it points to.
6130 if (V->hasInit()) {
6131 // Add the reference variable to the "trail".
6132 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006133 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006134 }
6135 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006136 }
Mike Stump11289f42009-09-09 15:08:12 +00006137
Craig Topperc3ec1492014-05-26 06:22:03 +00006138 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006139 }
Mike Stump11289f42009-09-09 15:08:12 +00006140
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006141 case Stmt::UnaryOperatorClass: {
6142 // The only unary operator that make sense to handle here
6143 // is Deref. All others don't resolve to a "name." This includes
6144 // handling all sorts of rvalues passed to a unary operator.
6145 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006146
John McCalle3027922010-08-25 11:45:40 +00006147 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006148 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006149
Craig Topperc3ec1492014-05-26 06:22:03 +00006150 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006151 }
Mike Stump11289f42009-09-09 15:08:12 +00006152
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006153 case Stmt::ArraySubscriptExprClass: {
6154 // Array subscripts are potential references to data on the stack. We
6155 // retrieve the DeclRefExpr* for the array variable if it indeed
6156 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006157 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006158 }
Mike Stump11289f42009-09-09 15:08:12 +00006159
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006160 case Stmt::OMPArraySectionExprClass: {
6161 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6162 ParentDecl);
6163 }
6164
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006165 case Stmt::ConditionalOperatorClass: {
6166 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006167 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006168 ConditionalOperator *C = cast<ConditionalOperator>(E);
6169
Anders Carlsson801c5c72007-11-30 19:04:31 +00006170 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006171 if (Expr *LHSExpr = C->getLHS()) {
6172 // In C++, we can have a throw-expression, which has 'void' type.
6173 if (!LHSExpr->getType()->isVoidType())
6174 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6175 return LHS;
6176 }
6177
6178 // In C++, we can have a throw-expression, which has 'void' type.
6179 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006180 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00006181
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006182 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006183 }
Mike Stump11289f42009-09-09 15:08:12 +00006184
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006185 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00006186 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006187 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006188
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006189 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006190 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00006191 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006192
6193 // Check whether the member type is itself a reference, in which case
6194 // we're not going to refer to the member, but to what the member refers to.
6195 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006196 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006197
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006198 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006199 }
Mike Stump11289f42009-09-09 15:08:12 +00006200
Douglas Gregorfe314812011-06-21 17:03:29 +00006201 case Stmt::MaterializeTemporaryExprClass:
6202 if (Expr *Result = EvalVal(
6203 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006204 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006205 return Result;
6206
6207 return E;
6208
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006209 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006210 // Check that we don't return or take the address of a reference to a
6211 // temporary. This is only useful in C++.
6212 if (!E->isTypeDependent() && E->isRValue())
6213 return E;
6214
6215 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00006216 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006217 }
Ted Kremenekb7861562010-08-04 20:01:07 +00006218} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006219}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006220
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006221void
6222Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6223 SourceLocation ReturnLoc,
6224 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006225 const AttrVec *Attrs,
6226 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006227 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6228
6229 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006230 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6231 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006232 CheckNonNullExpr(*this, RetValExp))
6233 Diag(ReturnLoc, diag::warn_null_ret)
6234 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006235
6236 // C++11 [basic.stc.dynamic.allocation]p4:
6237 // If an allocation function declared with a non-throwing
6238 // exception-specification fails to allocate storage, it shall return
6239 // a null pointer. Any other allocation function that fails to allocate
6240 // storage shall indicate failure only by throwing an exception [...]
6241 if (FD) {
6242 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6243 if (Op == OO_New || Op == OO_Array_New) {
6244 const FunctionProtoType *Proto
6245 = FD->getType()->castAs<FunctionProtoType>();
6246 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6247 CheckNonNullExpr(*this, RetValExp))
6248 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6249 << FD << getLangOpts().CPlusPlus11;
6250 }
6251 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006252}
6253
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006254//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6255
6256/// Check for comparisons of floating point operands using != and ==.
6257/// Issue a warning if these are no self-comparisons, as they are not likely
6258/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006259void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006260 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6261 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006262
6263 // Special case: check for x == x (which is OK).
6264 // Do not emit warnings for such cases.
6265 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6266 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6267 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006268 return;
Mike Stump11289f42009-09-09 15:08:12 +00006269
6270
Ted Kremenekeda40e22007-11-29 00:59:04 +00006271 // Special case: check for comparisons against literals that can be exactly
6272 // represented by APFloat. In such cases, do not emit a warning. This
6273 // is a heuristic: often comparison against such literals are used to
6274 // detect if a value in a variable has not changed. This clearly can
6275 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006276 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6277 if (FLL->isExact())
6278 return;
6279 } else
6280 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6281 if (FLR->isExact())
6282 return;
Mike Stump11289f42009-09-09 15:08:12 +00006283
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006284 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006285 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006286 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006287 return;
Mike Stump11289f42009-09-09 15:08:12 +00006288
David Blaikie1f4ff152012-07-16 20:47:22 +00006289 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006290 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006291 return;
Mike Stump11289f42009-09-09 15:08:12 +00006292
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006293 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006294 Diag(Loc, diag::warn_floatingpoint_eq)
6295 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006296}
John McCallca01b222010-01-04 23:21:16 +00006297
John McCall70aa5392010-01-06 05:24:50 +00006298//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6299//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006300
John McCall70aa5392010-01-06 05:24:50 +00006301namespace {
John McCallca01b222010-01-04 23:21:16 +00006302
John McCall70aa5392010-01-06 05:24:50 +00006303/// Structure recording the 'active' range of an integer-valued
6304/// expression.
6305struct IntRange {
6306 /// The number of bits active in the int.
6307 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006308
John McCall70aa5392010-01-06 05:24:50 +00006309 /// True if the int is known not to have negative values.
6310 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006311
John McCall70aa5392010-01-06 05:24:50 +00006312 IntRange(unsigned Width, bool NonNegative)
6313 : Width(Width), NonNegative(NonNegative)
6314 {}
John McCallca01b222010-01-04 23:21:16 +00006315
John McCall817d4af2010-11-10 23:38:19 +00006316 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006317 static IntRange forBoolType() {
6318 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006319 }
6320
John McCall817d4af2010-11-10 23:38:19 +00006321 /// Returns the range of an opaque value of the given integral type.
6322 static IntRange forValueOfType(ASTContext &C, QualType T) {
6323 return forValueOfCanonicalType(C,
6324 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006325 }
6326
John McCall817d4af2010-11-10 23:38:19 +00006327 /// Returns the range of an opaque value of a canonical integral type.
6328 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006329 assert(T->isCanonicalUnqualified());
6330
6331 if (const VectorType *VT = dyn_cast<VectorType>(T))
6332 T = VT->getElementType().getTypePtr();
6333 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6334 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006335 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6336 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006337
David Majnemer6a426652013-06-07 22:07:20 +00006338 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006339 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006340 EnumDecl *Enum = ET->getDecl();
6341 if (!Enum->isCompleteDefinition())
6342 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006343
David Majnemer6a426652013-06-07 22:07:20 +00006344 unsigned NumPositive = Enum->getNumPositiveBits();
6345 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006346
David Majnemer6a426652013-06-07 22:07:20 +00006347 if (NumNegative == 0)
6348 return IntRange(NumPositive, true/*NonNegative*/);
6349 else
6350 return IntRange(std::max(NumPositive + 1, NumNegative),
6351 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006352 }
John McCall70aa5392010-01-06 05:24:50 +00006353
6354 const BuiltinType *BT = cast<BuiltinType>(T);
6355 assert(BT->isInteger());
6356
6357 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6358 }
6359
John McCall817d4af2010-11-10 23:38:19 +00006360 /// Returns the "target" range of a canonical integral type, i.e.
6361 /// the range of values expressible in the type.
6362 ///
6363 /// This matches forValueOfCanonicalType except that enums have the
6364 /// full range of their type, not the range of their enumerators.
6365 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6366 assert(T->isCanonicalUnqualified());
6367
6368 if (const VectorType *VT = dyn_cast<VectorType>(T))
6369 T = VT->getElementType().getTypePtr();
6370 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6371 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006372 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6373 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006374 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006375 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006376
6377 const BuiltinType *BT = cast<BuiltinType>(T);
6378 assert(BT->isInteger());
6379
6380 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6381 }
6382
6383 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006384 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006385 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006386 L.NonNegative && R.NonNegative);
6387 }
6388
John McCall817d4af2010-11-10 23:38:19 +00006389 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006390 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006391 return IntRange(std::min(L.Width, R.Width),
6392 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006393 }
6394};
6395
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006396static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
6397 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006398 if (value.isSigned() && value.isNegative())
6399 return IntRange(value.getMinSignedBits(), false);
6400
6401 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006402 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006403
6404 // isNonNegative() just checks the sign bit without considering
6405 // signedness.
6406 return IntRange(value.getActiveBits(), true);
6407}
6408
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006409static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6410 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006411 if (result.isInt())
6412 return GetValueRange(C, result.getInt(), MaxWidth);
6413
6414 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006415 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6416 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6417 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6418 R = IntRange::join(R, El);
6419 }
John McCall70aa5392010-01-06 05:24:50 +00006420 return R;
6421 }
6422
6423 if (result.isComplexInt()) {
6424 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6425 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6426 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006427 }
6428
6429 // This can happen with lossless casts to intptr_t of "based" lvalues.
6430 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006431 // FIXME: The only reason we need to pass the type in here is to get
6432 // the sign right on this one case. It would be nice if APValue
6433 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006434 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006435 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006436}
John McCall70aa5392010-01-06 05:24:50 +00006437
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006438static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006439 QualType Ty = E->getType();
6440 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6441 Ty = AtomicRHS->getValueType();
6442 return Ty;
6443}
6444
John McCall70aa5392010-01-06 05:24:50 +00006445/// Pseudo-evaluate the given integer expression, estimating the
6446/// range of values it might take.
6447///
6448/// \param MaxWidth - the width to which the value will be truncated
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006449static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006450 E = E->IgnoreParens();
6451
6452 // Try a full evaluation first.
6453 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006454 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006455 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006456
6457 // I think we only want to look through implicit casts here; if the
6458 // user has an explicit widening cast, we should treat the value as
6459 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006460 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006461 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006462 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6463
Eli Friedmane6d33952013-07-08 20:20:06 +00006464 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006465
George Burgess IVdf1ed002016-01-13 01:52:39 +00006466 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6467 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00006468
John McCall70aa5392010-01-06 05:24:50 +00006469 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006470 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006471 return OutputTypeRange;
6472
6473 IntRange SubRange
6474 = GetExprRange(C, CE->getSubExpr(),
6475 std::min(MaxWidth, OutputTypeRange.Width));
6476
6477 // Bail out if the subexpr's range is as wide as the cast type.
6478 if (SubRange.Width >= OutputTypeRange.Width)
6479 return OutputTypeRange;
6480
6481 // Otherwise, we take the smaller width, and we're non-negative if
6482 // either the output type or the subexpr is.
6483 return IntRange(SubRange.Width,
6484 SubRange.NonNegative || OutputTypeRange.NonNegative);
6485 }
6486
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006487 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006488 // If we can fold the condition, just take that operand.
6489 bool CondResult;
6490 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6491 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6492 : CO->getFalseExpr(),
6493 MaxWidth);
6494
6495 // Otherwise, conservatively merge.
6496 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6497 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6498 return IntRange::join(L, R);
6499 }
6500
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006501 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006502 switch (BO->getOpcode()) {
6503
6504 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006505 case BO_LAnd:
6506 case BO_LOr:
6507 case BO_LT:
6508 case BO_GT:
6509 case BO_LE:
6510 case BO_GE:
6511 case BO_EQ:
6512 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006513 return IntRange::forBoolType();
6514
John McCallc3688382011-07-13 06:35:24 +00006515 // The type of the assignments is the type of the LHS, so the RHS
6516 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006517 case BO_MulAssign:
6518 case BO_DivAssign:
6519 case BO_RemAssign:
6520 case BO_AddAssign:
6521 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006522 case BO_XorAssign:
6523 case BO_OrAssign:
6524 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006525 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006526
John McCallc3688382011-07-13 06:35:24 +00006527 // Simple assignments just pass through the RHS, which will have
6528 // been coerced to the LHS type.
6529 case BO_Assign:
6530 // TODO: bitfields?
6531 return GetExprRange(C, BO->getRHS(), MaxWidth);
6532
John McCall70aa5392010-01-06 05:24:50 +00006533 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006534 case BO_PtrMemD:
6535 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006536 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006537
John McCall2ce81ad2010-01-06 22:07:33 +00006538 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006539 case BO_And:
6540 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006541 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6542 GetExprRange(C, BO->getRHS(), MaxWidth));
6543
John McCall70aa5392010-01-06 05:24:50 +00006544 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006545 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006546 // ...except that we want to treat '1 << (blah)' as logically
6547 // positive. It's an important idiom.
6548 if (IntegerLiteral *I
6549 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6550 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006551 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006552 return IntRange(R.Width, /*NonNegative*/ true);
6553 }
6554 }
6555 // fallthrough
6556
John McCalle3027922010-08-25 11:45:40 +00006557 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006558 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006559
John McCall2ce81ad2010-01-06 22:07:33 +00006560 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006561 case BO_Shr:
6562 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006563 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6564
6565 // If the shift amount is a positive constant, drop the width by
6566 // that much.
6567 llvm::APSInt shift;
6568 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6569 shift.isNonNegative()) {
6570 unsigned zext = shift.getZExtValue();
6571 if (zext >= L.Width)
6572 L.Width = (L.NonNegative ? 0 : 1);
6573 else
6574 L.Width -= zext;
6575 }
6576
6577 return L;
6578 }
6579
6580 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006581 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006582 return GetExprRange(C, BO->getRHS(), MaxWidth);
6583
John McCall2ce81ad2010-01-06 22:07:33 +00006584 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006585 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006586 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006587 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006588 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006589
John McCall51431812011-07-14 22:39:48 +00006590 // The width of a division result is mostly determined by the size
6591 // of the LHS.
6592 case BO_Div: {
6593 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006594 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006595 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6596
6597 // If the divisor is constant, use that.
6598 llvm::APSInt divisor;
6599 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6600 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6601 if (log2 >= L.Width)
6602 L.Width = (L.NonNegative ? 0 : 1);
6603 else
6604 L.Width = std::min(L.Width - log2, MaxWidth);
6605 return L;
6606 }
6607
6608 // Otherwise, just use the LHS's width.
6609 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6610 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6611 }
6612
6613 // The result of a remainder can't be larger than the result of
6614 // either side.
6615 case BO_Rem: {
6616 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006617 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006618 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6619 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6620
6621 IntRange meet = IntRange::meet(L, R);
6622 meet.Width = std::min(meet.Width, MaxWidth);
6623 return meet;
6624 }
6625
6626 // The default behavior is okay for these.
6627 case BO_Mul:
6628 case BO_Add:
6629 case BO_Xor:
6630 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006631 break;
6632 }
6633
John McCall51431812011-07-14 22:39:48 +00006634 // The default case is to treat the operation as if it were closed
6635 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006636 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6637 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6638 return IntRange::join(L, R);
6639 }
6640
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006641 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006642 switch (UO->getOpcode()) {
6643 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006644 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006645 return IntRange::forBoolType();
6646
6647 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006648 case UO_Deref:
6649 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006650 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006651
6652 default:
6653 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6654 }
6655 }
6656
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006657 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006658 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6659
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006660 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006661 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006662 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006663
Eli Friedmane6d33952013-07-08 20:20:06 +00006664 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006665}
John McCall263a48b2010-01-04 23:31:57 +00006666
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006667static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006668 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006669}
6670
John McCall263a48b2010-01-04 23:31:57 +00006671/// Checks whether the given value, which currently has the given
6672/// source semantics, has the same value when coerced through the
6673/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006674static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6675 const llvm::fltSemantics &Src,
6676 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006677 llvm::APFloat truncated = value;
6678
6679 bool ignored;
6680 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6681 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6682
6683 return truncated.bitwiseIsEqual(value);
6684}
6685
6686/// Checks whether the given value, which currently has the given
6687/// source semantics, has the same value when coerced through the
6688/// target semantics.
6689///
6690/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006691static bool IsSameFloatAfterCast(const APValue &value,
6692 const llvm::fltSemantics &Src,
6693 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006694 if (value.isFloat())
6695 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6696
6697 if (value.isVector()) {
6698 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6699 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6700 return false;
6701 return true;
6702 }
6703
6704 assert(value.isComplexFloat());
6705 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6706 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6707}
6708
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006709static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006710
Ted Kremenek6274be42010-09-23 21:43:44 +00006711static bool IsZero(Sema &S, Expr *E) {
6712 // Suppress cases where we are comparing against an enum constant.
6713 if (const DeclRefExpr *DR =
6714 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6715 if (isa<EnumConstantDecl>(DR->getDecl()))
6716 return false;
6717
6718 // Suppress cases where the '0' value is expanded from a macro.
6719 if (E->getLocStart().isMacroID())
6720 return false;
6721
John McCallcc7e5bf2010-05-06 08:58:33 +00006722 llvm::APSInt Value;
6723 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6724}
6725
John McCall2551c1b2010-10-06 00:25:24 +00006726static bool HasEnumType(Expr *E) {
6727 // Strip off implicit integral promotions.
6728 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006729 if (ICE->getCastKind() != CK_IntegralCast &&
6730 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006731 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006732 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006733 }
6734
6735 return E->getType()->isEnumeralType();
6736}
6737
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006738static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006739 // Disable warning in template instantiations.
6740 if (!S.ActiveTemplateInstantiations.empty())
6741 return;
6742
John McCalle3027922010-08-25 11:45:40 +00006743 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006744 if (E->isValueDependent())
6745 return;
6746
John McCalle3027922010-08-25 11:45:40 +00006747 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006748 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006749 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006750 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006751 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006752 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006753 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006754 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006755 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006756 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006757 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006758 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006759 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006760 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006761 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006762 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6763 }
6764}
6765
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006766static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006767 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006768 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006769 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006770 // Disable warning in template instantiations.
6771 if (!S.ActiveTemplateInstantiations.empty())
6772 return;
6773
Richard Trieu0f097742014-04-04 04:13:47 +00006774 // TODO: Investigate using GetExprRange() to get tighter bounds
6775 // on the bit ranges.
6776 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006777 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006778 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006779 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6780 unsigned OtherWidth = OtherRange.Width;
6781
6782 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6783
Richard Trieu560910c2012-11-14 22:50:24 +00006784 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006785 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006786 return;
6787
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006788 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006789 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006790
Richard Trieu0f097742014-04-04 04:13:47 +00006791 // Used for diagnostic printout.
6792 enum {
6793 LiteralConstant = 0,
6794 CXXBoolLiteralTrue,
6795 CXXBoolLiteralFalse
6796 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006797
Richard Trieu0f097742014-04-04 04:13:47 +00006798 if (!OtherIsBooleanType) {
6799 QualType ConstantT = Constant->getType();
6800 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006801
Richard Trieu0f097742014-04-04 04:13:47 +00006802 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6803 return;
6804 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6805 "comparison with non-integer type");
6806
6807 bool ConstantSigned = ConstantT->isSignedIntegerType();
6808 bool CommonSigned = CommonT->isSignedIntegerType();
6809
6810 bool EqualityOnly = false;
6811
6812 if (CommonSigned) {
6813 // The common type is signed, therefore no signed to unsigned conversion.
6814 if (!OtherRange.NonNegative) {
6815 // Check that the constant is representable in type OtherT.
6816 if (ConstantSigned) {
6817 if (OtherWidth >= Value.getMinSignedBits())
6818 return;
6819 } else { // !ConstantSigned
6820 if (OtherWidth >= Value.getActiveBits() + 1)
6821 return;
6822 }
6823 } else { // !OtherSigned
6824 // Check that the constant is representable in type OtherT.
6825 // Negative values are out of range.
6826 if (ConstantSigned) {
6827 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6828 return;
6829 } else { // !ConstantSigned
6830 if (OtherWidth >= Value.getActiveBits())
6831 return;
6832 }
Richard Trieu560910c2012-11-14 22:50:24 +00006833 }
Richard Trieu0f097742014-04-04 04:13:47 +00006834 } else { // !CommonSigned
6835 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006836 if (OtherWidth >= Value.getActiveBits())
6837 return;
Craig Toppercf360162014-06-18 05:13:11 +00006838 } else { // OtherSigned
6839 assert(!ConstantSigned &&
6840 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006841 // Check to see if the constant is representable in OtherT.
6842 if (OtherWidth > Value.getActiveBits())
6843 return;
6844 // Check to see if the constant is equivalent to a negative value
6845 // cast to CommonT.
6846 if (S.Context.getIntWidth(ConstantT) ==
6847 S.Context.getIntWidth(CommonT) &&
6848 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6849 return;
6850 // The constant value rests between values that OtherT can represent
6851 // after conversion. Relational comparison still works, but equality
6852 // comparisons will be tautological.
6853 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006854 }
6855 }
Richard Trieu0f097742014-04-04 04:13:47 +00006856
6857 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6858
6859 if (op == BO_EQ || op == BO_NE) {
6860 IsTrue = op == BO_NE;
6861 } else if (EqualityOnly) {
6862 return;
6863 } else if (RhsConstant) {
6864 if (op == BO_GT || op == BO_GE)
6865 IsTrue = !PositiveConstant;
6866 else // op == BO_LT || op == BO_LE
6867 IsTrue = PositiveConstant;
6868 } else {
6869 if (op == BO_LT || op == BO_LE)
6870 IsTrue = !PositiveConstant;
6871 else // op == BO_GT || op == BO_GE
6872 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006873 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006874 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006875 // Other isKnownToHaveBooleanValue
6876 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6877 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6878 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6879
6880 static const struct LinkedConditions {
6881 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6882 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6883 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6884 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6885 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6886 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6887
6888 } TruthTable = {
6889 // Constant on LHS. | Constant on RHS. |
6890 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6891 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6892 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6893 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6894 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6895 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6896 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6897 };
6898
6899 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6900
6901 enum ConstantValue ConstVal = Zero;
6902 if (Value.isUnsigned() || Value.isNonNegative()) {
6903 if (Value == 0) {
6904 LiteralOrBoolConstant =
6905 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6906 ConstVal = Zero;
6907 } else if (Value == 1) {
6908 LiteralOrBoolConstant =
6909 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6910 ConstVal = One;
6911 } else {
6912 LiteralOrBoolConstant = LiteralConstant;
6913 ConstVal = GT_One;
6914 }
6915 } else {
6916 ConstVal = LT_Zero;
6917 }
6918
6919 CompareBoolWithConstantResult CmpRes;
6920
6921 switch (op) {
6922 case BO_LT:
6923 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6924 break;
6925 case BO_GT:
6926 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6927 break;
6928 case BO_LE:
6929 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6930 break;
6931 case BO_GE:
6932 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6933 break;
6934 case BO_EQ:
6935 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6936 break;
6937 case BO_NE:
6938 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6939 break;
6940 default:
6941 CmpRes = Unkwn;
6942 break;
6943 }
6944
6945 if (CmpRes == AFals) {
6946 IsTrue = false;
6947 } else if (CmpRes == ATrue) {
6948 IsTrue = true;
6949 } else {
6950 return;
6951 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006952 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006953
6954 // If this is a comparison to an enum constant, include that
6955 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006956 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006957 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6958 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6959
6960 SmallString<64> PrettySourceValue;
6961 llvm::raw_svector_ostream OS(PrettySourceValue);
6962 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006963 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006964 else
6965 OS << Value;
6966
Richard Trieu0f097742014-04-04 04:13:47 +00006967 S.DiagRuntimeBehavior(
6968 E->getOperatorLoc(), E,
6969 S.PDiag(diag::warn_out_of_range_compare)
6970 << OS.str() << LiteralOrBoolConstant
6971 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6972 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006973}
6974
John McCallcc7e5bf2010-05-06 08:58:33 +00006975/// Analyze the operands of the given comparison. Implements the
6976/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006977static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006978 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6979 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006980}
John McCall263a48b2010-01-04 23:31:57 +00006981
John McCallca01b222010-01-04 23:21:16 +00006982/// \brief Implements -Wsign-compare.
6983///
Richard Trieu82402a02011-09-15 21:56:47 +00006984/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006985static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006986 // The type the comparison is being performed in.
6987 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006988
6989 // Only analyze comparison operators where both sides have been converted to
6990 // the same type.
6991 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6992 return AnalyzeImpConvsInComparison(S, E);
6993
6994 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006995 if (E->isValueDependent())
6996 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006997
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006998 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6999 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007000
7001 bool IsComparisonConstant = false;
7002
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007003 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007004 // of 'true' or 'false'.
7005 if (T->isIntegralType(S.Context)) {
7006 llvm::APSInt RHSValue;
7007 bool IsRHSIntegralLiteral =
7008 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7009 llvm::APSInt LHSValue;
7010 bool IsLHSIntegralLiteral =
7011 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7012 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7013 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7014 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7015 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7016 else
7017 IsComparisonConstant =
7018 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007019 } else if (!T->hasUnsignedIntegerRepresentation())
7020 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007021
John McCallcc7e5bf2010-05-06 08:58:33 +00007022 // We don't do anything special if this isn't an unsigned integral
7023 // comparison: we're only interested in integral comparisons, and
7024 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007025 //
7026 // We also don't care about value-dependent expressions or expressions
7027 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007028 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007029 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007030
John McCallcc7e5bf2010-05-06 08:58:33 +00007031 // Check to see if one of the (unmodified) operands is of different
7032 // signedness.
7033 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007034 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7035 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007036 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007037 signedOperand = LHS;
7038 unsignedOperand = RHS;
7039 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7040 signedOperand = RHS;
7041 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007042 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007043 CheckTrivialUnsignedComparison(S, E);
7044 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007045 }
7046
John McCallcc7e5bf2010-05-06 08:58:33 +00007047 // Otherwise, calculate the effective range of the signed operand.
7048 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007049
John McCallcc7e5bf2010-05-06 08:58:33 +00007050 // Go ahead and analyze implicit conversions in the operands. Note
7051 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007052 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7053 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007054
John McCallcc7e5bf2010-05-06 08:58:33 +00007055 // If the signed range is non-negative, -Wsign-compare won't fire,
7056 // but we should still check for comparisons which are always true
7057 // or false.
7058 if (signedRange.NonNegative)
7059 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007060
7061 // For (in)equality comparisons, if the unsigned operand is a
7062 // constant which cannot collide with a overflowed signed operand,
7063 // then reinterpreting the signed operand as unsigned will not
7064 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007065 if (E->isEqualityOp()) {
7066 unsigned comparisonWidth = S.Context.getIntWidth(T);
7067 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007068
John McCallcc7e5bf2010-05-06 08:58:33 +00007069 // We should never be unable to prove that the unsigned operand is
7070 // non-negative.
7071 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7072
7073 if (unsignedRange.Width < comparisonWidth)
7074 return;
7075 }
7076
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007077 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7078 S.PDiag(diag::warn_mixed_sign_comparison)
7079 << LHS->getType() << RHS->getType()
7080 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007081}
7082
John McCall1f425642010-11-11 03:21:53 +00007083/// Analyzes an attempt to assign the given value to a bitfield.
7084///
7085/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00007086static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7087 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007088 assert(Bitfield->isBitField());
7089 if (Bitfield->isInvalidDecl())
7090 return false;
7091
John McCalldeebbcf2010-11-11 05:33:51 +00007092 // White-list bool bitfields.
7093 if (Bitfield->getType()->isBooleanType())
7094 return false;
7095
Douglas Gregor789adec2011-02-04 13:09:01 +00007096 // Ignore value- or type-dependent expressions.
7097 if (Bitfield->getBitWidth()->isValueDependent() ||
7098 Bitfield->getBitWidth()->isTypeDependent() ||
7099 Init->isValueDependent() ||
7100 Init->isTypeDependent())
7101 return false;
7102
John McCall1f425642010-11-11 03:21:53 +00007103 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7104
Richard Smith5fab0c92011-12-28 19:48:30 +00007105 llvm::APSInt Value;
7106 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007107 return false;
7108
John McCall1f425642010-11-11 03:21:53 +00007109 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007110 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007111
7112 if (OriginalWidth <= FieldWidth)
7113 return false;
7114
Eli Friedmanc267a322012-01-26 23:11:39 +00007115 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007116 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007117 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007118
Eli Friedmanc267a322012-01-26 23:11:39 +00007119 // Check whether the stored value is equal to the original value.
7120 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007121 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007122 return false;
7123
Eli Friedmanc267a322012-01-26 23:11:39 +00007124 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007125 // therefore don't strictly fit into a signed bitfield of width 1.
7126 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007127 return false;
7128
John McCall1f425642010-11-11 03:21:53 +00007129 std::string PrettyValue = Value.toString(10);
7130 std::string PrettyTrunc = TruncatedValue.toString(10);
7131
7132 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7133 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7134 << Init->getSourceRange();
7135
7136 return true;
7137}
7138
John McCalld2a53122010-11-09 23:24:47 +00007139/// Analyze the given simple or compound assignment for warning-worthy
7140/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00007141static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007142 // Just recurse on the LHS.
7143 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7144
7145 // We want to recurse on the RHS as normal unless we're assigning to
7146 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007147 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007148 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007149 E->getOperatorLoc())) {
7150 // Recurse, ignoring any implicit conversions on the RHS.
7151 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7152 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007153 }
7154 }
7155
7156 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7157}
7158
John McCall263a48b2010-01-04 23:31:57 +00007159/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00007160static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00007161 SourceLocation CContext, unsigned diag,
7162 bool pruneControlFlow = false) {
7163 if (pruneControlFlow) {
7164 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7165 S.PDiag(diag)
7166 << SourceType << T << E->getSourceRange()
7167 << SourceRange(CContext));
7168 return;
7169 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007170 S.Diag(E->getExprLoc(), diag)
7171 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7172}
7173
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007174/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00007175static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00007176 SourceLocation CContext, unsigned diag,
7177 bool pruneControlFlow = false) {
7178 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007179}
7180
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007181/// Diagnose an implicit cast from a literal expression. Does not warn when the
7182/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00007183void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
7184 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007185 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00007186 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007187 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007188 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7189 T->hasUnsignedIntegerRepresentation());
7190 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00007191 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007192 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00007193 return;
7194
Eli Friedman07185912013-08-29 23:44:43 +00007195 // FIXME: Force the precision of the source value down so we don't print
7196 // digits which are usually useless (we don't really care here if we
7197 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7198 // would automatically print the shortest representation, but it's a bit
7199 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007200 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007201 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7202 precision = (precision * 59 + 195) / 196;
7203 Value.toString(PrettySourceValue, precision);
7204
David Blaikie9b88cc02012-05-15 17:18:27 +00007205 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00007206 if (T->isSpecificBuiltinType(BuiltinType::Bool))
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007207 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007208 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007209 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007210
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007211 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00007212 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
7213 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00007214}
7215
John McCall18a2c2c2010-11-09 22:22:12 +00007216std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7217 if (!Range.Width) return "0";
7218
7219 llvm::APSInt ValueInRange = Value;
7220 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007221 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007222 return ValueInRange.toString(10);
7223}
7224
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007225static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
7226 if (!isa<ImplicitCastExpr>(Ex))
7227 return false;
7228
7229 Expr *InnerE = Ex->IgnoreParenImpCasts();
7230 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7231 const Type *Source =
7232 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7233 if (Target->isDependentType())
7234 return false;
7235
7236 const BuiltinType *FloatCandidateBT =
7237 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7238 const Type *BoolCandidateType = ToBool ? Target : Source;
7239
7240 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7241 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7242}
7243
7244void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7245 SourceLocation CC) {
7246 unsigned NumArgs = TheCall->getNumArgs();
7247 for (unsigned i = 0; i < NumArgs; ++i) {
7248 Expr *CurrA = TheCall->getArg(i);
7249 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7250 continue;
7251
7252 bool IsSwapped = ((i > 0) &&
7253 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7254 IsSwapped |= ((i < (NumArgs - 1)) &&
7255 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7256 if (IsSwapped) {
7257 // Warn on this floating-point to bool conversion.
7258 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7259 CurrA->getType(), CC,
7260 diag::warn_impcast_floating_point_to_bool);
7261 }
7262 }
7263}
7264
Richard Trieu5b993502014-10-15 03:42:06 +00007265static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
7266 SourceLocation CC) {
7267 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7268 E->getExprLoc()))
7269 return;
7270
Richard Trieu09d6b802016-01-08 23:35:06 +00007271 // Don't warn on functions which have return type nullptr_t.
7272 if (isa<CallExpr>(E))
7273 return;
7274
Richard Trieu5b993502014-10-15 03:42:06 +00007275 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7276 const Expr::NullPointerConstantKind NullKind =
7277 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7278 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7279 return;
7280
7281 // Return if target type is a safe conversion.
7282 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7283 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7284 return;
7285
7286 SourceLocation Loc = E->getSourceRange().getBegin();
7287
7288 // __null is usually wrapped in a macro. Go up a macro if that is the case.
7289 if (NullKind == Expr::NPCK_GNUNull) {
Richard Trieufc014f22016-01-09 01:10:17 +00007290 if (Loc.isMacroID()) {
Richard Trieu3a5c9582016-01-26 02:51:55 +00007291 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7292 Loc, S.SourceMgr, S.getLangOpts());
Richard Trieufc014f22016-01-09 01:10:17 +00007293 if (MacroName == "NULL")
7294 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
7295 }
Richard Trieu5b993502014-10-15 03:42:06 +00007296 }
7297
7298 // Only warn if the null and context location are in the same macro expansion.
7299 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7300 return;
7301
7302 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7303 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7304 << FixItHint::CreateReplacement(Loc,
7305 S.getFixItZeroLiteralForType(T, Loc));
7306}
7307
Douglas Gregor5054cb02015-07-07 03:58:22 +00007308static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7309 ObjCArrayLiteral *ArrayLiteral);
7310static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7311 ObjCDictionaryLiteral *DictionaryLiteral);
7312
7313/// Check a single element within a collection literal against the
7314/// target element type.
7315static void checkObjCCollectionLiteralElement(Sema &S,
7316 QualType TargetElementType,
7317 Expr *Element,
7318 unsigned ElementKind) {
7319 // Skip a bitcast to 'id' or qualified 'id'.
7320 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7321 if (ICE->getCastKind() == CK_BitCast &&
7322 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7323 Element = ICE->getSubExpr();
7324 }
7325
7326 QualType ElementType = Element->getType();
7327 ExprResult ElementResult(Element);
7328 if (ElementType->getAs<ObjCObjectPointerType>() &&
7329 S.CheckSingleAssignmentConstraints(TargetElementType,
7330 ElementResult,
7331 false, false)
7332 != Sema::Compatible) {
7333 S.Diag(Element->getLocStart(),
7334 diag::warn_objc_collection_literal_element)
7335 << ElementType << ElementKind << TargetElementType
7336 << Element->getSourceRange();
7337 }
7338
7339 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7340 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7341 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7342 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7343}
7344
7345/// Check an Objective-C array literal being converted to the given
7346/// target type.
7347static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7348 ObjCArrayLiteral *ArrayLiteral) {
7349 if (!S.NSArrayDecl)
7350 return;
7351
7352 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7353 if (!TargetObjCPtr)
7354 return;
7355
7356 if (TargetObjCPtr->isUnspecialized() ||
7357 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7358 != S.NSArrayDecl->getCanonicalDecl())
7359 return;
7360
7361 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7362 if (TypeArgs.size() != 1)
7363 return;
7364
7365 QualType TargetElementType = TypeArgs[0];
7366 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7367 checkObjCCollectionLiteralElement(S, TargetElementType,
7368 ArrayLiteral->getElement(I),
7369 0);
7370 }
7371}
7372
7373/// Check an Objective-C dictionary literal being converted to the given
7374/// target type.
7375static void checkObjCDictionaryLiteral(
7376 Sema &S, QualType TargetType,
7377 ObjCDictionaryLiteral *DictionaryLiteral) {
7378 if (!S.NSDictionaryDecl)
7379 return;
7380
7381 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7382 if (!TargetObjCPtr)
7383 return;
7384
7385 if (TargetObjCPtr->isUnspecialized() ||
7386 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7387 != S.NSDictionaryDecl->getCanonicalDecl())
7388 return;
7389
7390 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7391 if (TypeArgs.size() != 2)
7392 return;
7393
7394 QualType TargetKeyType = TypeArgs[0];
7395 QualType TargetObjectType = TypeArgs[1];
7396 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7397 auto Element = DictionaryLiteral->getKeyValueElement(I);
7398 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7399 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7400 }
7401}
7402
Richard Trieufc404c72016-02-05 23:02:38 +00007403// Helper function to filter out cases for constant width constant conversion.
7404// Don't warn on char array initialization or for non-decimal values.
7405static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7406 SourceLocation CC) {
7407 // If initializing from a constant, and the constant starts with '0',
7408 // then it is a binary, octal, or hexadecimal. Allow these constants
7409 // to fill all the bits, even if there is a sign change.
7410 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7411 const char FirstLiteralCharacter =
7412 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7413 if (FirstLiteralCharacter == '0')
7414 return false;
7415 }
7416
7417 // If the CC location points to a '{', and the type is char, then assume
7418 // assume it is an array initialization.
7419 if (CC.isValid() && T->isCharType()) {
7420 const char FirstContextCharacter =
7421 S.getSourceManager().getCharacterData(CC)[0];
7422 if (FirstContextCharacter == '{')
7423 return false;
7424 }
7425
7426 return true;
7427}
7428
John McCallcc7e5bf2010-05-06 08:58:33 +00007429void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007430 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007431 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007432
John McCallcc7e5bf2010-05-06 08:58:33 +00007433 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7434 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7435 if (Source == Target) return;
7436 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007437
Chandler Carruthc22845a2011-07-26 05:40:03 +00007438 // If the conversion context location is invalid don't complain. We also
7439 // don't want to emit a warning if the issue occurs from the expansion of
7440 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7441 // delay this check as long as possible. Once we detect we are in that
7442 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007443 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007444 return;
7445
Richard Trieu021baa32011-09-23 20:10:00 +00007446 // Diagnose implicit casts to bool.
7447 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7448 if (isa<StringLiteral>(E))
7449 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007450 // and expressions, for instance, assert(0 && "error here"), are
7451 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007452 return DiagnoseImpCast(S, E, T, CC,
7453 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007454 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7455 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7456 // This covers the literal expressions that evaluate to Objective-C
7457 // objects.
7458 return DiagnoseImpCast(S, E, T, CC,
7459 diag::warn_impcast_objective_c_literal_to_bool);
7460 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007461 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7462 // Warn on pointer to bool conversion that is always true.
7463 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7464 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007465 }
Richard Trieu021baa32011-09-23 20:10:00 +00007466 }
John McCall263a48b2010-01-04 23:31:57 +00007467
Douglas Gregor5054cb02015-07-07 03:58:22 +00007468 // Check implicit casts from Objective-C collection literals to specialized
7469 // collection types, e.g., NSArray<NSString *> *.
7470 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7471 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7472 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7473 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7474
John McCall263a48b2010-01-04 23:31:57 +00007475 // Strip vector types.
7476 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007477 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007478 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007479 return;
John McCallacf0ee52010-10-08 02:01:28 +00007480 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007481 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007482
7483 // If the vector cast is cast between two vectors of the same size, it is
7484 // a bitcast, not a conversion.
7485 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7486 return;
John McCall263a48b2010-01-04 23:31:57 +00007487
7488 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7489 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7490 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007491 if (auto VecTy = dyn_cast<VectorType>(Target))
7492 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007493
7494 // Strip complex types.
7495 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007496 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007497 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007498 return;
7499
John McCallacf0ee52010-10-08 02:01:28 +00007500 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007501 }
John McCall263a48b2010-01-04 23:31:57 +00007502
7503 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7504 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7505 }
7506
7507 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7508 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7509
7510 // If the source is floating point...
7511 if (SourceBT && SourceBT->isFloatingPoint()) {
7512 // ...and the target is floating point...
7513 if (TargetBT && TargetBT->isFloatingPoint()) {
7514 // ...then warn if we're dropping FP rank.
7515
7516 // Builtin FP kinds are ordered by increasing FP rank.
7517 if (SourceBT->getKind() > TargetBT->getKind()) {
7518 // Don't warn about float constants that are precisely
7519 // representable in the target type.
7520 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007521 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007522 // Value might be a float, a float vector, or a float complex.
7523 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007524 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7525 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007526 return;
7527 }
7528
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007529 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007530 return;
7531
John McCallacf0ee52010-10-08 02:01:28 +00007532 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007533
7534 }
7535 // ... or possibly if we're increasing rank, too
7536 else if (TargetBT->getKind() > SourceBT->getKind()) {
7537 if (S.SourceMgr.isInSystemMacro(CC))
7538 return;
7539
7540 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007541 }
7542 return;
7543 }
7544
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007545 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007546 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007547 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007548 return;
7549
Chandler Carruth22c7a792011-02-17 11:05:49 +00007550 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007551 // We also want to warn on, e.g., "int i = -1.234"
7552 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7553 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7554 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7555
Chandler Carruth016ef402011-04-10 08:36:24 +00007556 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7557 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007558 } else {
7559 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7560 }
7561 }
John McCall263a48b2010-01-04 23:31:57 +00007562
Richard Smith54894fd2015-12-30 01:06:52 +00007563 // Detect the case where a call result is converted from floating-point to
7564 // to bool, and the final argument to the call is converted from bool, to
7565 // discover this typo:
7566 //
7567 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
7568 //
7569 // FIXME: This is an incredibly special case; is there some more general
7570 // way to detect this class of misplaced-parentheses bug?
7571 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007572 // Check last argument of function call to see if it is an
7573 // implicit cast from a type matching the type the result
7574 // is being cast to.
7575 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00007576 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007577 Expr *LastA = CEx->getArg(NumArgs - 1);
7578 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00007579 if (isa<ImplicitCastExpr>(LastA) &&
7580 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007581 // Warn on this floating-point to bool conversion
7582 DiagnoseImpCast(S, E, T, CC,
7583 diag::warn_impcast_floating_point_to_bool);
7584 }
7585 }
7586 }
John McCall263a48b2010-01-04 23:31:57 +00007587 return;
7588 }
7589
Richard Trieu5b993502014-10-15 03:42:06 +00007590 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007591
David Blaikie9366d2b2012-06-19 21:19:06 +00007592 if (!Source->isIntegerType() || !Target->isIntegerType())
7593 return;
7594
David Blaikie7555b6a2012-05-15 16:56:36 +00007595 // TODO: remove this early return once the false positives for constant->bool
7596 // in templates, macros, etc, are reduced or removed.
7597 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7598 return;
7599
John McCallcc7e5bf2010-05-06 08:58:33 +00007600 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007601 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007602
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007603 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007604 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007605 // TODO: this should happen for bitfield stores, too.
7606 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00007607 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007608 if (S.SourceMgr.isInSystemMacro(CC))
7609 return;
7610
John McCall18a2c2c2010-11-09 22:22:12 +00007611 std::string PrettySourceValue = Value.toString(10);
7612 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007613
Ted Kremenek33ba9952011-10-22 02:37:33 +00007614 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7615 S.PDiag(diag::warn_impcast_integer_precision_constant)
7616 << PrettySourceValue << PrettyTargetValue
7617 << E->getType() << T << E->getSourceRange()
7618 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007619 return;
7620 }
7621
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007622 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7623 if (S.SourceMgr.isInSystemMacro(CC))
7624 return;
7625
David Blaikie9455da02012-04-12 22:40:54 +00007626 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007627 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7628 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007629 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007630 }
7631
Richard Trieudcb55572016-01-29 23:51:16 +00007632 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
7633 SourceRange.NonNegative && Source->isSignedIntegerType()) {
7634 // Warn when doing a signed to signed conversion, warn if the positive
7635 // source value is exactly the width of the target type, which will
7636 // cause a negative value to be stored.
7637
7638 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00007639 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
7640 !S.SourceMgr.isInSystemMacro(CC)) {
7641 if (isSameWidthConstantConversion(S, E, T, CC)) {
7642 std::string PrettySourceValue = Value.toString(10);
7643 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00007644
Richard Trieufc404c72016-02-05 23:02:38 +00007645 S.DiagRuntimeBehavior(
7646 E->getExprLoc(), E,
7647 S.PDiag(diag::warn_impcast_integer_precision_constant)
7648 << PrettySourceValue << PrettyTargetValue << E->getType() << T
7649 << E->getSourceRange() << clang::SourceRange(CC));
7650 return;
Richard Trieudcb55572016-01-29 23:51:16 +00007651 }
7652 }
Richard Trieufc404c72016-02-05 23:02:38 +00007653
Richard Trieudcb55572016-01-29 23:51:16 +00007654 // Fall through for non-constants to give a sign conversion warning.
7655 }
7656
John McCallcc7e5bf2010-05-06 08:58:33 +00007657 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7658 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7659 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007660
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007661 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007662 return;
7663
John McCallcc7e5bf2010-05-06 08:58:33 +00007664 unsigned DiagID = diag::warn_impcast_integer_sign;
7665
7666 // Traditionally, gcc has warned about this under -Wsign-compare.
7667 // We also want to warn about it in -Wconversion.
7668 // So if -Wconversion is off, use a completely identical diagnostic
7669 // in the sign-compare group.
7670 // The conditional-checking code will
7671 if (ICContext) {
7672 DiagID = diag::warn_impcast_integer_sign_conditional;
7673 *ICContext = true;
7674 }
7675
John McCallacf0ee52010-10-08 02:01:28 +00007676 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007677 }
7678
Douglas Gregora78f1932011-02-22 02:45:07 +00007679 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007680 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7681 // type, to give us better diagnostics.
7682 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007683 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007684 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7685 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7686 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7687 SourceType = S.Context.getTypeDeclType(Enum);
7688 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7689 }
7690 }
7691
Douglas Gregora78f1932011-02-22 02:45:07 +00007692 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7693 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007694 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7695 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007696 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007697 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007698 return;
7699
Douglas Gregor364f7db2011-03-12 00:14:31 +00007700 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007701 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007702 }
Douglas Gregora78f1932011-02-22 02:45:07 +00007703
John McCall263a48b2010-01-04 23:31:57 +00007704 return;
7705}
7706
David Blaikie18e9ac72012-05-15 21:57:38 +00007707void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7708 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007709
7710void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007711 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007712 E = E->IgnoreParenImpCasts();
7713
7714 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007715 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007716
John McCallacf0ee52010-10-08 02:01:28 +00007717 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007718 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007719 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007720 return;
7721}
7722
David Blaikie18e9ac72012-05-15 21:57:38 +00007723void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7724 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007725 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007726
7727 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007728 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7729 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007730
7731 // If -Wconversion would have warned about either of the candidates
7732 // for a signedness conversion to the context type...
7733 if (!Suspicious) return;
7734
7735 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007736 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007737 return;
7738
John McCallcc7e5bf2010-05-06 08:58:33 +00007739 // ...then check whether it would have warned about either of the
7740 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007741 if (E->getType() == T) return;
7742
7743 Suspicious = false;
7744 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7745 E->getType(), CC, &Suspicious);
7746 if (!Suspicious)
7747 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007748 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007749}
7750
Richard Trieu65724892014-11-15 06:37:39 +00007751/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7752/// Input argument E is a logical expression.
7753static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
7754 if (S.getLangOpts().Bool)
7755 return;
7756 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7757}
7758
John McCallcc7e5bf2010-05-06 08:58:33 +00007759/// AnalyzeImplicitConversions - Find and report any interesting
7760/// implicit conversions in the given expression. There are a couple
7761/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007762void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007763 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007764 Expr *E = OrigE->IgnoreParenImpCasts();
7765
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007766 if (E->isTypeDependent() || E->isValueDependent())
7767 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007768
John McCallcc7e5bf2010-05-06 08:58:33 +00007769 // For conditional operators, we analyze the arguments as if they
7770 // were being fed directly into the output.
7771 if (isa<ConditionalOperator>(E)) {
7772 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007773 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007774 return;
7775 }
7776
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007777 // Check implicit argument conversions for function calls.
7778 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7779 CheckImplicitArgumentConversions(S, Call, CC);
7780
John McCallcc7e5bf2010-05-06 08:58:33 +00007781 // Go ahead and check any implicit conversions we might have skipped.
7782 // The non-canonical typecheck is just an optimization;
7783 // CheckImplicitConversion will filter out dead implicit conversions.
7784 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007785 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007786
7787 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00007788
7789 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
7790 // The bound subexpressions in a PseudoObjectExpr are not reachable
7791 // as transitive children.
7792 // FIXME: Use a more uniform representation for this.
7793 for (auto *SE : POE->semantics())
7794 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
7795 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007796 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00007797
John McCallcc7e5bf2010-05-06 08:58:33 +00007798 // Skip past explicit casts.
7799 if (isa<ExplicitCastExpr>(E)) {
7800 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007801 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007802 }
7803
John McCalld2a53122010-11-09 23:24:47 +00007804 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7805 // Do a somewhat different check with comparison operators.
7806 if (BO->isComparisonOp())
7807 return AnalyzeComparison(S, BO);
7808
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007809 // And with simple assignments.
7810 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007811 return AnalyzeAssignment(S, BO);
7812 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007813
7814 // These break the otherwise-useful invariant below. Fortunately,
7815 // we don't really need to recurse into them, because any internal
7816 // expressions should have been analyzed already when they were
7817 // built into statements.
7818 if (isa<StmtExpr>(E)) return;
7819
7820 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007821 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007822
7823 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007824 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007825 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007826 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007827 for (Stmt *SubStmt : E->children()) {
7828 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007829 if (!ChildExpr)
7830 continue;
7831
Richard Trieu955231d2014-01-25 01:10:35 +00007832 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007833 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007834 // Ignore checking string literals that are in logical and operators.
7835 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007836 continue;
7837 AnalyzeImplicitConversions(S, ChildExpr, CC);
7838 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007839
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007840 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007841 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7842 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007843 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007844
7845 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7846 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007847 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007848 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007849
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007850 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7851 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007852 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007853}
7854
7855} // end anonymous namespace
7856
Richard Trieuc1888e02014-06-28 23:25:37 +00007857// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7858// Returns true when emitting a warning about taking the address of a reference.
7859static bool CheckForReference(Sema &SemaRef, const Expr *E,
7860 PartialDiagnostic PD) {
7861 E = E->IgnoreParenImpCasts();
7862
7863 const FunctionDecl *FD = nullptr;
7864
7865 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7866 if (!DRE->getDecl()->getType()->isReferenceType())
7867 return false;
7868 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7869 if (!M->getMemberDecl()->getType()->isReferenceType())
7870 return false;
7871 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007872 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007873 return false;
7874 FD = Call->getDirectCallee();
7875 } else {
7876 return false;
7877 }
7878
7879 SemaRef.Diag(E->getExprLoc(), PD);
7880
7881 // If possible, point to location of function.
7882 if (FD) {
7883 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7884 }
7885
7886 return true;
7887}
7888
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007889// Returns true if the SourceLocation is expanded from any macro body.
7890// Returns false if the SourceLocation is invalid, is from not in a macro
7891// expansion, or is from expanded from a top-level macro argument.
7892static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7893 if (Loc.isInvalid())
7894 return false;
7895
7896 while (Loc.isMacroID()) {
7897 if (SM.isMacroBodyExpansion(Loc))
7898 return true;
7899 Loc = SM.getImmediateMacroCallerLoc(Loc);
7900 }
7901
7902 return false;
7903}
7904
Richard Trieu3bb8b562014-02-26 02:36:06 +00007905/// \brief Diagnose pointers that are always non-null.
7906/// \param E the expression containing the pointer
7907/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7908/// compared to a null pointer
7909/// \param IsEqual True when the comparison is equal to a null pointer
7910/// \param Range Extra SourceRange to highlight in the diagnostic
7911void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7912 Expr::NullPointerConstantKind NullKind,
7913 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007914 if (!E)
7915 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007916
7917 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007918 if (E->getExprLoc().isMacroID()) {
7919 const SourceManager &SM = getSourceManager();
7920 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7921 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007922 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007923 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007924 E = E->IgnoreImpCasts();
7925
7926 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7927
Richard Trieuf7432752014-06-06 21:39:26 +00007928 if (isa<CXXThisExpr>(E)) {
7929 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7930 : diag::warn_this_bool_conversion;
7931 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7932 return;
7933 }
7934
Richard Trieu3bb8b562014-02-26 02:36:06 +00007935 bool IsAddressOf = false;
7936
7937 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7938 if (UO->getOpcode() != UO_AddrOf)
7939 return;
7940 IsAddressOf = true;
7941 E = UO->getSubExpr();
7942 }
7943
Richard Trieuc1888e02014-06-28 23:25:37 +00007944 if (IsAddressOf) {
7945 unsigned DiagID = IsCompare
7946 ? diag::warn_address_of_reference_null_compare
7947 : diag::warn_address_of_reference_bool_conversion;
7948 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7949 << IsEqual;
7950 if (CheckForReference(*this, E, PD)) {
7951 return;
7952 }
7953 }
7954
George Burgess IV850269a2015-12-08 22:02:00 +00007955 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
7956 std::string Str;
7957 llvm::raw_string_ostream S(Str);
7958 E->printPretty(S, nullptr, getPrintingPolicy());
7959 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
7960 : diag::warn_cast_nonnull_to_bool;
7961 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
7962 << E->getSourceRange() << Range << IsEqual;
7963 };
7964
7965 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
7966 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
7967 if (auto *Callee = Call->getDirectCallee()) {
7968 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
7969 ComplainAboutNonnullParamOrCall(false);
7970 return;
7971 }
7972 }
7973 }
7974
Richard Trieu3bb8b562014-02-26 02:36:06 +00007975 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007976 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007977 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7978 D = R->getDecl();
7979 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7980 D = M->getMemberDecl();
7981 }
7982
7983 // Weak Decls can be null.
7984 if (!D || D->isWeak())
7985 return;
George Burgess IV850269a2015-12-08 22:02:00 +00007986
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007987 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00007988 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
7989 if (getCurFunction() &&
7990 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
7991 if (PV->hasAttr<NonNullAttr>()) {
7992 ComplainAboutNonnullParamOrCall(true);
7993 return;
7994 }
7995
7996 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7997 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
7998 assert(ParamIter != FD->param_end());
7999 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8000
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008001 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8002 if (!NonNull->args_size()) {
George Burgess IV850269a2015-12-08 22:02:00 +00008003 ComplainAboutNonnullParamOrCall(true);
8004 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008005 }
George Burgess IV850269a2015-12-08 22:02:00 +00008006
8007 for (unsigned ArgNo : NonNull->args()) {
8008 if (ArgNo == ParamNo) {
8009 ComplainAboutNonnullParamOrCall(true);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008010 return;
8011 }
George Burgess IV850269a2015-12-08 22:02:00 +00008012 }
8013 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008014 }
8015 }
George Burgess IV850269a2015-12-08 22:02:00 +00008016 }
8017
Richard Trieu3bb8b562014-02-26 02:36:06 +00008018 QualType T = D->getType();
8019 const bool IsArray = T->isArrayType();
8020 const bool IsFunction = T->isFunctionType();
8021
Richard Trieuc1888e02014-06-28 23:25:37 +00008022 // Address of function is used to silence the function warning.
8023 if (IsAddressOf && IsFunction) {
8024 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008025 }
8026
8027 // Found nothing.
8028 if (!IsAddressOf && !IsFunction && !IsArray)
8029 return;
8030
8031 // Pretty print the expression for the diagnostic.
8032 std::string Str;
8033 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008034 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008035
8036 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8037 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008038 enum {
8039 AddressOf,
8040 FunctionPointer,
8041 ArrayPointer
8042 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008043 if (IsAddressOf)
8044 DiagType = AddressOf;
8045 else if (IsFunction)
8046 DiagType = FunctionPointer;
8047 else if (IsArray)
8048 DiagType = ArrayPointer;
8049 else
8050 llvm_unreachable("Could not determine diagnostic.");
8051 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8052 << Range << IsEqual;
8053
8054 if (!IsFunction)
8055 return;
8056
8057 // Suggest '&' to silence the function warning.
8058 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8059 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8060
8061 // Check to see if '()' fixit should be emitted.
8062 QualType ReturnType;
8063 UnresolvedSet<4> NonTemplateOverloads;
8064 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8065 if (ReturnType.isNull())
8066 return;
8067
8068 if (IsCompare) {
8069 // There are two cases here. If there is null constant, the only suggest
8070 // for a pointer return type. If the null is 0, then suggest if the return
8071 // type is a pointer or an integer type.
8072 if (!ReturnType->isPointerType()) {
8073 if (NullKind == Expr::NPCK_ZeroExpression ||
8074 NullKind == Expr::NPCK_ZeroLiteral) {
8075 if (!ReturnType->isIntegerType())
8076 return;
8077 } else {
8078 return;
8079 }
8080 }
8081 } else { // !IsCompare
8082 // For function to bool, only suggest if the function pointer has bool
8083 // return type.
8084 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8085 return;
8086 }
8087 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008088 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008089}
8090
8091
John McCallcc7e5bf2010-05-06 08:58:33 +00008092/// Diagnoses "dangerous" implicit conversions within the given
8093/// expression (which is a full expression). Implements -Wconversion
8094/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008095///
8096/// \param CC the "context" location of the implicit conversion, i.e.
8097/// the most location of the syntactic entity requiring the implicit
8098/// conversion
8099void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008100 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008101 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008102 return;
8103
8104 // Don't diagnose for value- or type-dependent expressions.
8105 if (E->isTypeDependent() || E->isValueDependent())
8106 return;
8107
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008108 // Check for array bounds violations in cases where the check isn't triggered
8109 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8110 // ArraySubscriptExpr is on the RHS of a variable initialization.
8111 CheckArrayAccess(E);
8112
John McCallacf0ee52010-10-08 02:01:28 +00008113 // This is not the right CC for (e.g.) a variable initialization.
8114 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008115}
8116
Richard Trieu65724892014-11-15 06:37:39 +00008117/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8118/// Input argument E is a logical expression.
8119void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8120 ::CheckBoolLikeConversion(*this, E, CC);
8121}
8122
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008123/// Diagnose when expression is an integer constant expression and its evaluation
8124/// results in integer overflow
8125void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00008126 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
8127 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Akira Hatanakaf5c13612016-01-11 17:22:01 +00008128 else if (auto InitList = dyn_cast<InitListExpr>(E))
8129 for (Expr *E : InitList->inits())
8130 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
8131 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008132}
8133
Richard Smithc406cb72013-01-17 01:17:56 +00008134namespace {
8135/// \brief Visitor for expressions which looks for unsequenced operations on the
8136/// same object.
8137class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008138 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8139
Richard Smithc406cb72013-01-17 01:17:56 +00008140 /// \brief A tree of sequenced regions within an expression. Two regions are
8141 /// unsequenced if one is an ancestor or a descendent of the other. When we
8142 /// finish processing an expression with sequencing, such as a comma
8143 /// expression, we fold its tree nodes into its parent, since they are
8144 /// unsequenced with respect to nodes we will visit later.
8145 class SequenceTree {
8146 struct Value {
8147 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8148 unsigned Parent : 31;
8149 bool Merged : 1;
8150 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008151 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008152
8153 public:
8154 /// \brief A region within an expression which may be sequenced with respect
8155 /// to some other region.
8156 class Seq {
8157 explicit Seq(unsigned N) : Index(N) {}
8158 unsigned Index;
8159 friend class SequenceTree;
8160 public:
8161 Seq() : Index(0) {}
8162 };
8163
8164 SequenceTree() { Values.push_back(Value(0)); }
8165 Seq root() const { return Seq(0); }
8166
8167 /// \brief Create a new sequence of operations, which is an unsequenced
8168 /// subset of \p Parent. This sequence of operations is sequenced with
8169 /// respect to other children of \p Parent.
8170 Seq allocate(Seq Parent) {
8171 Values.push_back(Value(Parent.Index));
8172 return Seq(Values.size() - 1);
8173 }
8174
8175 /// \brief Merge a sequence of operations into its parent.
8176 void merge(Seq S) {
8177 Values[S.Index].Merged = true;
8178 }
8179
8180 /// \brief Determine whether two operations are unsequenced. This operation
8181 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8182 /// should have been merged into its parent as appropriate.
8183 bool isUnsequenced(Seq Cur, Seq Old) {
8184 unsigned C = representative(Cur.Index);
8185 unsigned Target = representative(Old.Index);
8186 while (C >= Target) {
8187 if (C == Target)
8188 return true;
8189 C = Values[C].Parent;
8190 }
8191 return false;
8192 }
8193
8194 private:
8195 /// \brief Pick a representative for a sequence.
8196 unsigned representative(unsigned K) {
8197 if (Values[K].Merged)
8198 // Perform path compression as we go.
8199 return Values[K].Parent = representative(Values[K].Parent);
8200 return K;
8201 }
8202 };
8203
8204 /// An object for which we can track unsequenced uses.
8205 typedef NamedDecl *Object;
8206
8207 /// Different flavors of object usage which we track. We only track the
8208 /// least-sequenced usage of each kind.
8209 enum UsageKind {
8210 /// A read of an object. Multiple unsequenced reads are OK.
8211 UK_Use,
8212 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008213 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008214 UK_ModAsValue,
8215 /// A modification of an object which is not sequenced before the value
8216 /// computation of the expression, such as n++.
8217 UK_ModAsSideEffect,
8218
8219 UK_Count = UK_ModAsSideEffect + 1
8220 };
8221
8222 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008223 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008224 Expr *Use;
8225 SequenceTree::Seq Seq;
8226 };
8227
8228 struct UsageInfo {
8229 UsageInfo() : Diagnosed(false) {}
8230 Usage Uses[UK_Count];
8231 /// Have we issued a diagnostic for this variable already?
8232 bool Diagnosed;
8233 };
8234 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8235
8236 Sema &SemaRef;
8237 /// Sequenced regions within the expression.
8238 SequenceTree Tree;
8239 /// Declaration modifications and references which we have seen.
8240 UsageInfoMap UsageMap;
8241 /// The region we are currently within.
8242 SequenceTree::Seq Region;
8243 /// Filled in with declarations which were modified as a side-effect
8244 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008245 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008246 /// Expressions to check later. We defer checking these to reduce
8247 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008248 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008249
8250 /// RAII object wrapping the visitation of a sequenced subexpression of an
8251 /// expression. At the end of this process, the side-effects of the evaluation
8252 /// become sequenced with respect to the value computation of the result, so
8253 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8254 /// UK_ModAsValue.
8255 struct SequencedSubexpression {
8256 SequencedSubexpression(SequenceChecker &Self)
8257 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8258 Self.ModAsSideEffect = &ModAsSideEffect;
8259 }
8260 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00008261 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8262 MI != ME; ++MI) {
8263 UsageInfo &U = Self.UsageMap[MI->first];
8264 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8265 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8266 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00008267 }
8268 Self.ModAsSideEffect = OldModAsSideEffect;
8269 }
8270
8271 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008272 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8273 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008274 };
8275
Richard Smith40238f02013-06-20 22:21:56 +00008276 /// RAII object wrapping the visitation of a subexpression which we might
8277 /// choose to evaluate as a constant. If any subexpression is evaluated and
8278 /// found to be non-constant, this allows us to suppress the evaluation of
8279 /// the outer expression.
8280 class EvaluationTracker {
8281 public:
8282 EvaluationTracker(SequenceChecker &Self)
8283 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8284 Self.EvalTracker = this;
8285 }
8286 ~EvaluationTracker() {
8287 Self.EvalTracker = Prev;
8288 if (Prev)
8289 Prev->EvalOK &= EvalOK;
8290 }
8291
8292 bool evaluate(const Expr *E, bool &Result) {
8293 if (!EvalOK || E->isValueDependent())
8294 return false;
8295 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8296 return EvalOK;
8297 }
8298
8299 private:
8300 SequenceChecker &Self;
8301 EvaluationTracker *Prev;
8302 bool EvalOK;
8303 } *EvalTracker;
8304
Richard Smithc406cb72013-01-17 01:17:56 +00008305 /// \brief Find the object which is produced by the specified expression,
8306 /// if any.
8307 Object getObject(Expr *E, bool Mod) const {
8308 E = E->IgnoreParenCasts();
8309 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8310 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8311 return getObject(UO->getSubExpr(), Mod);
8312 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8313 if (BO->getOpcode() == BO_Comma)
8314 return getObject(BO->getRHS(), Mod);
8315 if (Mod && BO->isAssignmentOp())
8316 return getObject(BO->getLHS(), Mod);
8317 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8318 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8319 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8320 return ME->getMemberDecl();
8321 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8322 // FIXME: If this is a reference, map through to its value.
8323 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008324 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008325 }
8326
8327 /// \brief Note that an object was modified or used by an expression.
8328 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8329 Usage &U = UI.Uses[UK];
8330 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8331 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8332 ModAsSideEffect->push_back(std::make_pair(O, U));
8333 U.Use = Ref;
8334 U.Seq = Region;
8335 }
8336 }
8337 /// \brief Check whether a modification or use conflicts with a prior usage.
8338 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8339 bool IsModMod) {
8340 if (UI.Diagnosed)
8341 return;
8342
8343 const Usage &U = UI.Uses[OtherKind];
8344 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8345 return;
8346
8347 Expr *Mod = U.Use;
8348 Expr *ModOrUse = Ref;
8349 if (OtherKind == UK_Use)
8350 std::swap(Mod, ModOrUse);
8351
8352 SemaRef.Diag(Mod->getExprLoc(),
8353 IsModMod ? diag::warn_unsequenced_mod_mod
8354 : diag::warn_unsequenced_mod_use)
8355 << O << SourceRange(ModOrUse->getExprLoc());
8356 UI.Diagnosed = true;
8357 }
8358
8359 void notePreUse(Object O, Expr *Use) {
8360 UsageInfo &U = UsageMap[O];
8361 // Uses conflict with other modifications.
8362 checkUsage(O, U, Use, UK_ModAsValue, false);
8363 }
8364 void notePostUse(Object O, Expr *Use) {
8365 UsageInfo &U = UsageMap[O];
8366 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8367 addUsage(U, O, Use, UK_Use);
8368 }
8369
8370 void notePreMod(Object O, Expr *Mod) {
8371 UsageInfo &U = UsageMap[O];
8372 // Modifications conflict with other modifications and with uses.
8373 checkUsage(O, U, Mod, UK_ModAsValue, true);
8374 checkUsage(O, U, Mod, UK_Use, false);
8375 }
8376 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8377 UsageInfo &U = UsageMap[O];
8378 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8379 addUsage(U, O, Use, UK);
8380 }
8381
8382public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008383 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008384 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8385 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008386 Visit(E);
8387 }
8388
8389 void VisitStmt(Stmt *S) {
8390 // Skip all statements which aren't expressions for now.
8391 }
8392
8393 void VisitExpr(Expr *E) {
8394 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008395 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008396 }
8397
8398 void VisitCastExpr(CastExpr *E) {
8399 Object O = Object();
8400 if (E->getCastKind() == CK_LValueToRValue)
8401 O = getObject(E->getSubExpr(), false);
8402
8403 if (O)
8404 notePreUse(O, E);
8405 VisitExpr(E);
8406 if (O)
8407 notePostUse(O, E);
8408 }
8409
8410 void VisitBinComma(BinaryOperator *BO) {
8411 // C++11 [expr.comma]p1:
8412 // Every value computation and side effect associated with the left
8413 // expression is sequenced before every value computation and side
8414 // effect associated with the right expression.
8415 SequenceTree::Seq LHS = Tree.allocate(Region);
8416 SequenceTree::Seq RHS = Tree.allocate(Region);
8417 SequenceTree::Seq OldRegion = Region;
8418
8419 {
8420 SequencedSubexpression SeqLHS(*this);
8421 Region = LHS;
8422 Visit(BO->getLHS());
8423 }
8424
8425 Region = RHS;
8426 Visit(BO->getRHS());
8427
8428 Region = OldRegion;
8429
8430 // Forget that LHS and RHS are sequenced. They are both unsequenced
8431 // with respect to other stuff.
8432 Tree.merge(LHS);
8433 Tree.merge(RHS);
8434 }
8435
8436 void VisitBinAssign(BinaryOperator *BO) {
8437 // The modification is sequenced after the value computation of the LHS
8438 // and RHS, so check it before inspecting the operands and update the
8439 // map afterwards.
8440 Object O = getObject(BO->getLHS(), true);
8441 if (!O)
8442 return VisitExpr(BO);
8443
8444 notePreMod(O, BO);
8445
8446 // C++11 [expr.ass]p7:
8447 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8448 // only once.
8449 //
8450 // Therefore, for a compound assignment operator, O is considered used
8451 // everywhere except within the evaluation of E1 itself.
8452 if (isa<CompoundAssignOperator>(BO))
8453 notePreUse(O, BO);
8454
8455 Visit(BO->getLHS());
8456
8457 if (isa<CompoundAssignOperator>(BO))
8458 notePostUse(O, BO);
8459
8460 Visit(BO->getRHS());
8461
Richard Smith83e37bee2013-06-26 23:16:51 +00008462 // C++11 [expr.ass]p1:
8463 // the assignment is sequenced [...] before the value computation of the
8464 // assignment expression.
8465 // C11 6.5.16/3 has no such rule.
8466 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8467 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008468 }
8469 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8470 VisitBinAssign(CAO);
8471 }
8472
8473 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8474 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8475 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8476 Object O = getObject(UO->getSubExpr(), true);
8477 if (!O)
8478 return VisitExpr(UO);
8479
8480 notePreMod(O, UO);
8481 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008482 // C++11 [expr.pre.incr]p1:
8483 // the expression ++x is equivalent to x+=1
8484 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8485 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008486 }
8487
8488 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8489 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8490 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8491 Object O = getObject(UO->getSubExpr(), true);
8492 if (!O)
8493 return VisitExpr(UO);
8494
8495 notePreMod(O, UO);
8496 Visit(UO->getSubExpr());
8497 notePostMod(O, UO, UK_ModAsSideEffect);
8498 }
8499
8500 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8501 void VisitBinLOr(BinaryOperator *BO) {
8502 // The side-effects of the LHS of an '&&' are sequenced before the
8503 // value computation of the RHS, and hence before the value computation
8504 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8505 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008506 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008507 {
8508 SequencedSubexpression Sequenced(*this);
8509 Visit(BO->getLHS());
8510 }
8511
8512 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008513 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008514 if (!Result)
8515 Visit(BO->getRHS());
8516 } else {
8517 // Check for unsequenced operations in the RHS, treating it as an
8518 // entirely separate evaluation.
8519 //
8520 // FIXME: If there are operations in the RHS which are unsequenced
8521 // with respect to operations outside the RHS, and those operations
8522 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008523 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008524 }
Richard Smithc406cb72013-01-17 01:17:56 +00008525 }
8526 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008527 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008528 {
8529 SequencedSubexpression Sequenced(*this);
8530 Visit(BO->getLHS());
8531 }
8532
8533 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008534 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008535 if (Result)
8536 Visit(BO->getRHS());
8537 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008538 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008539 }
Richard Smithc406cb72013-01-17 01:17:56 +00008540 }
8541
8542 // Only visit the condition, unless we can be sure which subexpression will
8543 // be chosen.
8544 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008545 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008546 {
8547 SequencedSubexpression Sequenced(*this);
8548 Visit(CO->getCond());
8549 }
Richard Smithc406cb72013-01-17 01:17:56 +00008550
8551 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008552 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008553 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008554 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008555 WorkList.push_back(CO->getTrueExpr());
8556 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008557 }
Richard Smithc406cb72013-01-17 01:17:56 +00008558 }
8559
Richard Smithe3dbfe02013-06-30 10:40:20 +00008560 void VisitCallExpr(CallExpr *CE) {
8561 // C++11 [intro.execution]p15:
8562 // When calling a function [...], every value computation and side effect
8563 // associated with any argument expression, or with the postfix expression
8564 // designating the called function, is sequenced before execution of every
8565 // expression or statement in the body of the function [and thus before
8566 // the value computation of its result].
8567 SequencedSubexpression Sequenced(*this);
8568 Base::VisitCallExpr(CE);
8569
8570 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8571 }
8572
Richard Smithc406cb72013-01-17 01:17:56 +00008573 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008574 // This is a call, so all subexpressions are sequenced before the result.
8575 SequencedSubexpression Sequenced(*this);
8576
Richard Smithc406cb72013-01-17 01:17:56 +00008577 if (!CCE->isListInitialization())
8578 return VisitExpr(CCE);
8579
8580 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008581 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008582 SequenceTree::Seq Parent = Region;
8583 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8584 E = CCE->arg_end();
8585 I != E; ++I) {
8586 Region = Tree.allocate(Parent);
8587 Elts.push_back(Region);
8588 Visit(*I);
8589 }
8590
8591 // Forget that the initializers are sequenced.
8592 Region = Parent;
8593 for (unsigned I = 0; I < Elts.size(); ++I)
8594 Tree.merge(Elts[I]);
8595 }
8596
8597 void VisitInitListExpr(InitListExpr *ILE) {
8598 if (!SemaRef.getLangOpts().CPlusPlus11)
8599 return VisitExpr(ILE);
8600
8601 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008602 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008603 SequenceTree::Seq Parent = Region;
8604 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8605 Expr *E = ILE->getInit(I);
8606 if (!E) continue;
8607 Region = Tree.allocate(Parent);
8608 Elts.push_back(Region);
8609 Visit(E);
8610 }
8611
8612 // Forget that the initializers are sequenced.
8613 Region = Parent;
8614 for (unsigned I = 0; I < Elts.size(); ++I)
8615 Tree.merge(Elts[I]);
8616 }
8617};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008618}
Richard Smithc406cb72013-01-17 01:17:56 +00008619
8620void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008621 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008622 WorkList.push_back(E);
8623 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008624 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008625 SequenceChecker(*this, Item, WorkList);
8626 }
Richard Smithc406cb72013-01-17 01:17:56 +00008627}
8628
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008629void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8630 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008631 CheckImplicitConversions(E, CheckLoc);
8632 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008633 if (!IsConstexpr && !E->isValueDependent())
8634 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008635}
8636
John McCall1f425642010-11-11 03:21:53 +00008637void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8638 FieldDecl *BitField,
8639 Expr *Init) {
8640 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8641}
8642
David Majnemer61a5bbf2015-04-07 22:08:51 +00008643static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8644 SourceLocation Loc) {
8645 if (!PType->isVariablyModifiedType())
8646 return;
8647 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8648 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8649 return;
8650 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008651 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8652 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8653 return;
8654 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008655 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8656 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8657 return;
8658 }
8659
8660 const ArrayType *AT = S.Context.getAsArrayType(PType);
8661 if (!AT)
8662 return;
8663
8664 if (AT->getSizeModifier() != ArrayType::Star) {
8665 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8666 return;
8667 }
8668
8669 S.Diag(Loc, diag::err_array_star_in_function_definition);
8670}
8671
Mike Stump0c2ec772010-01-21 03:59:47 +00008672/// CheckParmsForFunctionDef - Check that the parameters of the given
8673/// function are appropriate for the definition of a function. This
8674/// takes care of any checks that cannot be performed on the
8675/// declaration itself, e.g., that the types of each of the function
8676/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008677bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8678 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008679 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008680 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008681 for (; P != PEnd; ++P) {
8682 ParmVarDecl *Param = *P;
8683
Mike Stump0c2ec772010-01-21 03:59:47 +00008684 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8685 // function declarator that is part of a function definition of
8686 // that function shall not have incomplete type.
8687 //
8688 // This is also C++ [dcl.fct]p6.
8689 if (!Param->isInvalidDecl() &&
8690 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008691 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008692 Param->setInvalidDecl();
8693 HasInvalidParm = true;
8694 }
8695
8696 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8697 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008698 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008699 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008700 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008701 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008702 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008703
8704 // C99 6.7.5.3p12:
8705 // If the function declarator is not part of a definition of that
8706 // function, parameters may have incomplete type and may use the [*]
8707 // notation in their sequences of declarator specifiers to specify
8708 // variable length array types.
8709 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008710 // FIXME: This diagnostic should point the '[*]' if source-location
8711 // information is added for it.
8712 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008713
8714 // MSVC destroys objects passed by value in the callee. Therefore a
8715 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008716 // object's destructor. However, we don't perform any direct access check
8717 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008718 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8719 .getCXXABI()
8720 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008721 if (!Param->isInvalidDecl()) {
8722 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8723 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8724 if (!ClassDecl->isInvalidDecl() &&
8725 !ClassDecl->hasIrrelevantDestructor() &&
8726 !ClassDecl->isDependentContext()) {
8727 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8728 MarkFunctionReferenced(Param->getLocation(), Destructor);
8729 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8730 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008731 }
8732 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008733 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008734
8735 // Parameters with the pass_object_size attribute only need to be marked
8736 // constant at function definitions. Because we lack information about
8737 // whether we're on a declaration or definition when we're instantiating the
8738 // attribute, we need to check for constness here.
8739 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
8740 if (!Param->getType().isConstQualified())
8741 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
8742 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00008743 }
8744
8745 return HasInvalidParm;
8746}
John McCall2b5c1b22010-08-12 21:44:57 +00008747
8748/// CheckCastAlign - Implements -Wcast-align, which warns when a
8749/// pointer cast increases the alignment requirements.
8750void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8751 // This is actually a lot of work to potentially be doing on every
8752 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008753 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008754 return;
8755
8756 // Ignore dependent types.
8757 if (T->isDependentType() || Op->getType()->isDependentType())
8758 return;
8759
8760 // Require that the destination be a pointer type.
8761 const PointerType *DestPtr = T->getAs<PointerType>();
8762 if (!DestPtr) return;
8763
8764 // If the destination has alignment 1, we're done.
8765 QualType DestPointee = DestPtr->getPointeeType();
8766 if (DestPointee->isIncompleteType()) return;
8767 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8768 if (DestAlign.isOne()) return;
8769
8770 // Require that the source be a pointer type.
8771 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8772 if (!SrcPtr) return;
8773 QualType SrcPointee = SrcPtr->getPointeeType();
8774
8775 // Whitelist casts from cv void*. We already implicitly
8776 // whitelisted casts to cv void*, since they have alignment 1.
8777 // Also whitelist casts involving incomplete types, which implicitly
8778 // includes 'void'.
8779 if (SrcPointee->isIncompleteType()) return;
8780
8781 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8782 if (SrcAlign >= DestAlign) return;
8783
8784 Diag(TRange.getBegin(), diag::warn_cast_align)
8785 << Op->getType() << T
8786 << static_cast<unsigned>(SrcAlign.getQuantity())
8787 << static_cast<unsigned>(DestAlign.getQuantity())
8788 << TRange << Op->getSourceRange();
8789}
8790
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008791static const Type* getElementType(const Expr *BaseExpr) {
8792 const Type* EltType = BaseExpr->getType().getTypePtr();
8793 if (EltType->isAnyPointerType())
8794 return EltType->getPointeeType().getTypePtr();
8795 else if (EltType->isArrayType())
8796 return EltType->getBaseElementTypeUnsafe();
8797 return EltType;
8798}
8799
Chandler Carruth28389f02011-08-05 09:10:50 +00008800/// \brief Check whether this array fits the idiom of a size-one tail padded
8801/// array member of a struct.
8802///
8803/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8804/// commonly used to emulate flexible arrays in C89 code.
8805static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8806 const NamedDecl *ND) {
8807 if (Size != 1 || !ND) return false;
8808
8809 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8810 if (!FD) return false;
8811
8812 // Don't consider sizes resulting from macro expansions or template argument
8813 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008814
8815 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008816 while (TInfo) {
8817 TypeLoc TL = TInfo->getTypeLoc();
8818 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008819 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8820 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008821 TInfo = TDL->getTypeSourceInfo();
8822 continue;
8823 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008824 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8825 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008826 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8827 return false;
8828 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008829 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008830 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008831
8832 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008833 if (!RD) return false;
8834 if (RD->isUnion()) return false;
8835 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8836 if (!CRD->isStandardLayout()) return false;
8837 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008838
Benjamin Kramer8c543672011-08-06 03:04:42 +00008839 // See if this is the last field decl in the record.
8840 const Decl *D = FD;
8841 while ((D = D->getNextDeclInContext()))
8842 if (isa<FieldDecl>(D))
8843 return false;
8844 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008845}
8846
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008847void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008848 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00008849 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008850 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008851 if (IndexExpr->isValueDependent())
8852 return;
8853
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00008854 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008855 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008856 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008857 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008858 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00008859 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00008860
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008861 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00008862 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00008863 return;
Richard Smith13f67182011-12-16 19:31:14 +00008864 if (IndexNegated)
8865 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00008866
Craig Topperc3ec1492014-05-26 06:22:03 +00008867 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00008868 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8869 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00008870 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00008871 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00008872
Ted Kremeneke4b316c2011-02-23 23:06:04 +00008873 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008874 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008875 if (!size.isStrictlyPositive())
8876 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008877
8878 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008879 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008880 // Make sure we're comparing apples to apples when comparing index to size
8881 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8882 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008883 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008884 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008885 if (ptrarith_typesize != array_typesize) {
8886 // There's a cast to a different size type involved
8887 uint64_t ratio = array_typesize / ptrarith_typesize;
8888 // TODO: Be smarter about handling cases where array_typesize is not a
8889 // multiple of ptrarith_typesize
8890 if (ptrarith_typesize * ratio == array_typesize)
8891 size *= llvm::APInt(size.getBitWidth(), ratio);
8892 }
8893 }
8894
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008895 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008896 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008897 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008898 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008899
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008900 // For array subscripting the index must be less than size, but for pointer
8901 // arithmetic also allow the index (offset) to be equal to size since
8902 // computing the next address after the end of the array is legal and
8903 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008904 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008905 return;
8906
8907 // Also don't warn for arrays of size 1 which are members of some
8908 // structure. These are often used to approximate flexible arrays in C89
8909 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008910 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008911 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008912
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008913 // Suppress the warning if the subscript expression (as identified by the
8914 // ']' location) and the index expression are both from macro expansions
8915 // within a system header.
8916 if (ASE) {
8917 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8918 ASE->getRBracketLoc());
8919 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8920 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8921 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008922 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008923 return;
8924 }
8925 }
8926
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008927 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008928 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008929 DiagID = diag::warn_array_index_exceeds_bounds;
8930
8931 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8932 PDiag(DiagID) << index.toString(10, true)
8933 << size.toString(10, true)
8934 << (unsigned)size.getLimitedValue(~0U)
8935 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008936 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008937 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008938 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008939 DiagID = diag::warn_ptr_arith_precedes_bounds;
8940 if (index.isNegative()) index = -index;
8941 }
8942
8943 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8944 PDiag(DiagID) << index.toString(10, true)
8945 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008946 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008947
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008948 if (!ND) {
8949 // Try harder to find a NamedDecl to point at in the note.
8950 while (const ArraySubscriptExpr *ASE =
8951 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8952 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8953 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8954 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8955 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8956 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8957 }
8958
Chandler Carruth1af88f12011-02-17 21:10:52 +00008959 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008960 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8961 PDiag(diag::note_array_index_out_of_bounds)
8962 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008963}
8964
Ted Kremenekdf26df72011-03-01 18:41:00 +00008965void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008966 int AllowOnePastEnd = 0;
8967 while (expr) {
8968 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008969 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008970 case Stmt::ArraySubscriptExprClass: {
8971 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008972 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008973 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00008974 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008975 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008976 case Stmt::OMPArraySectionExprClass: {
8977 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
8978 if (ASE->getLowerBound())
8979 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
8980 /*ASE=*/nullptr, AllowOnePastEnd > 0);
8981 return;
8982 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008983 case Stmt::UnaryOperatorClass: {
8984 // Only unwrap the * and & unary operators
8985 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8986 expr = UO->getSubExpr();
8987 switch (UO->getOpcode()) {
8988 case UO_AddrOf:
8989 AllowOnePastEnd++;
8990 break;
8991 case UO_Deref:
8992 AllowOnePastEnd--;
8993 break;
8994 default:
8995 return;
8996 }
8997 break;
8998 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008999 case Stmt::ConditionalOperatorClass: {
9000 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9001 if (const Expr *lhs = cond->getLHS())
9002 CheckArrayAccess(lhs);
9003 if (const Expr *rhs = cond->getRHS())
9004 CheckArrayAccess(rhs);
9005 return;
9006 }
9007 default:
9008 return;
9009 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009010 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009011}
John McCall31168b02011-06-15 23:02:42 +00009012
9013//===--- CHECK: Objective-C retain cycles ----------------------------------//
9014
9015namespace {
9016 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009017 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009018 VarDecl *Variable;
9019 SourceRange Range;
9020 SourceLocation Loc;
9021 bool Indirect;
9022
9023 void setLocsFrom(Expr *e) {
9024 Loc = e->getExprLoc();
9025 Range = e->getSourceRange();
9026 }
9027 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009028}
John McCall31168b02011-06-15 23:02:42 +00009029
9030/// Consider whether capturing the given variable can possibly lead to
9031/// a retain cycle.
9032static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009033 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009034 // lifetime. In MRR, it's captured strongly if the variable is
9035 // __block and has an appropriate type.
9036 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9037 return false;
9038
9039 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009040 if (ref)
9041 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009042 return true;
9043}
9044
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009045static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009046 while (true) {
9047 e = e->IgnoreParens();
9048 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9049 switch (cast->getCastKind()) {
9050 case CK_BitCast:
9051 case CK_LValueBitCast:
9052 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009053 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009054 e = cast->getSubExpr();
9055 continue;
9056
John McCall31168b02011-06-15 23:02:42 +00009057 default:
9058 return false;
9059 }
9060 }
9061
9062 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9063 ObjCIvarDecl *ivar = ref->getDecl();
9064 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9065 return false;
9066
9067 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009068 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009069 return false;
9070
9071 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9072 owner.Indirect = true;
9073 return true;
9074 }
9075
9076 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9077 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9078 if (!var) return false;
9079 return considerVariable(var, ref, owner);
9080 }
9081
John McCall31168b02011-06-15 23:02:42 +00009082 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9083 if (member->isArrow()) return false;
9084
9085 // Don't count this as an indirect ownership.
9086 e = member->getBase();
9087 continue;
9088 }
9089
John McCallfe96e0b2011-11-06 09:01:30 +00009090 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9091 // Only pay attention to pseudo-objects on property references.
9092 ObjCPropertyRefExpr *pre
9093 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9094 ->IgnoreParens());
9095 if (!pre) return false;
9096 if (pre->isImplicitProperty()) return false;
9097 ObjCPropertyDecl *property = pre->getExplicitProperty();
9098 if (!property->isRetaining() &&
9099 !(property->getPropertyIvarDecl() &&
9100 property->getPropertyIvarDecl()->getType()
9101 .getObjCLifetime() == Qualifiers::OCL_Strong))
9102 return false;
9103
9104 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009105 if (pre->isSuperReceiver()) {
9106 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9107 if (!owner.Variable)
9108 return false;
9109 owner.Loc = pre->getLocation();
9110 owner.Range = pre->getSourceRange();
9111 return true;
9112 }
John McCallfe96e0b2011-11-06 09:01:30 +00009113 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9114 ->getSourceExpr());
9115 continue;
9116 }
9117
John McCall31168b02011-06-15 23:02:42 +00009118 // Array ivars?
9119
9120 return false;
9121 }
9122}
9123
9124namespace {
9125 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9126 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9127 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009128 Context(Context), Variable(variable), Capturer(nullptr),
9129 VarWillBeReased(false) {}
9130 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009131 VarDecl *Variable;
9132 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009133 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009134
9135 void VisitDeclRefExpr(DeclRefExpr *ref) {
9136 if (ref->getDecl() == Variable && !Capturer)
9137 Capturer = ref;
9138 }
9139
John McCall31168b02011-06-15 23:02:42 +00009140 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9141 if (Capturer) return;
9142 Visit(ref->getBase());
9143 if (Capturer && ref->isFreeIvar())
9144 Capturer = ref;
9145 }
9146
9147 void VisitBlockExpr(BlockExpr *block) {
9148 // Look inside nested blocks
9149 if (block->getBlockDecl()->capturesVariable(Variable))
9150 Visit(block->getBlockDecl()->getBody());
9151 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009152
9153 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9154 if (Capturer) return;
9155 if (OVE->getSourceExpr())
9156 Visit(OVE->getSourceExpr());
9157 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009158 void VisitBinaryOperator(BinaryOperator *BinOp) {
9159 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9160 return;
9161 Expr *LHS = BinOp->getLHS();
9162 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9163 if (DRE->getDecl() != Variable)
9164 return;
9165 if (Expr *RHS = BinOp->getRHS()) {
9166 RHS = RHS->IgnoreParenCasts();
9167 llvm::APSInt Value;
9168 VarWillBeReased =
9169 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9170 }
9171 }
9172 }
John McCall31168b02011-06-15 23:02:42 +00009173 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009174}
John McCall31168b02011-06-15 23:02:42 +00009175
9176/// Check whether the given argument is a block which captures a
9177/// variable.
9178static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9179 assert(owner.Variable && owner.Loc.isValid());
9180
9181 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009182
9183 // Look through [^{...} copy] and Block_copy(^{...}).
9184 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9185 Selector Cmd = ME->getSelector();
9186 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9187 e = ME->getInstanceReceiver();
9188 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009189 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009190 e = e->IgnoreParenCasts();
9191 }
9192 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9193 if (CE->getNumArgs() == 1) {
9194 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009195 if (Fn) {
9196 const IdentifierInfo *FnI = Fn->getIdentifier();
9197 if (FnI && FnI->isStr("_Block_copy")) {
9198 e = CE->getArg(0)->IgnoreParenCasts();
9199 }
9200 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009201 }
9202 }
9203
John McCall31168b02011-06-15 23:02:42 +00009204 BlockExpr *block = dyn_cast<BlockExpr>(e);
9205 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009206 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009207
9208 FindCaptureVisitor visitor(S.Context, owner.Variable);
9209 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009210 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009211}
9212
9213static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9214 RetainCycleOwner &owner) {
9215 assert(capturer);
9216 assert(owner.Variable && owner.Loc.isValid());
9217
9218 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9219 << owner.Variable << capturer->getSourceRange();
9220 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9221 << owner.Indirect << owner.Range;
9222}
9223
9224/// Check for a keyword selector that starts with the word 'add' or
9225/// 'set'.
9226static bool isSetterLikeSelector(Selector sel) {
9227 if (sel.isUnarySelector()) return false;
9228
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009229 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009230 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009231 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009232 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009233 else if (str.startswith("add")) {
9234 // Specially whitelist 'addOperationWithBlock:'.
9235 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9236 return false;
9237 str = str.substr(3);
9238 }
John McCall31168b02011-06-15 23:02:42 +00009239 else
9240 return false;
9241
9242 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009243 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009244}
9245
Benjamin Kramer3a743452015-03-09 15:03:32 +00009246static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9247 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009248 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9249 Message->getReceiverInterface(),
9250 NSAPI::ClassId_NSMutableArray);
9251 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009252 return None;
9253 }
9254
9255 Selector Sel = Message->getSelector();
9256
9257 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9258 S.NSAPIObj->getNSArrayMethodKind(Sel);
9259 if (!MKOpt) {
9260 return None;
9261 }
9262
9263 NSAPI::NSArrayMethodKind MK = *MKOpt;
9264
9265 switch (MK) {
9266 case NSAPI::NSMutableArr_addObject:
9267 case NSAPI::NSMutableArr_insertObjectAtIndex:
9268 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9269 return 0;
9270 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9271 return 1;
9272
9273 default:
9274 return None;
9275 }
9276
9277 return None;
9278}
9279
9280static
9281Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9282 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009283 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9284 Message->getReceiverInterface(),
9285 NSAPI::ClassId_NSMutableDictionary);
9286 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009287 return None;
9288 }
9289
9290 Selector Sel = Message->getSelector();
9291
9292 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9293 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9294 if (!MKOpt) {
9295 return None;
9296 }
9297
9298 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9299
9300 switch (MK) {
9301 case NSAPI::NSMutableDict_setObjectForKey:
9302 case NSAPI::NSMutableDict_setValueForKey:
9303 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9304 return 0;
9305
9306 default:
9307 return None;
9308 }
9309
9310 return None;
9311}
9312
9313static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009314 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9315 Message->getReceiverInterface(),
9316 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009317
Alex Denisov5dfac812015-08-06 04:51:14 +00009318 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9319 Message->getReceiverInterface(),
9320 NSAPI::ClassId_NSMutableOrderedSet);
9321 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009322 return None;
9323 }
9324
9325 Selector Sel = Message->getSelector();
9326
9327 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9328 if (!MKOpt) {
9329 return None;
9330 }
9331
9332 NSAPI::NSSetMethodKind MK = *MKOpt;
9333
9334 switch (MK) {
9335 case NSAPI::NSMutableSet_addObject:
9336 case NSAPI::NSOrderedSet_setObjectAtIndex:
9337 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9338 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9339 return 0;
9340 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9341 return 1;
9342 }
9343
9344 return None;
9345}
9346
9347void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9348 if (!Message->isInstanceMessage()) {
9349 return;
9350 }
9351
9352 Optional<int> ArgOpt;
9353
9354 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9355 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9356 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9357 return;
9358 }
9359
9360 int ArgIndex = *ArgOpt;
9361
Alex Denisove1d882c2015-03-04 17:55:52 +00009362 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9363 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9364 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9365 }
9366
Alex Denisov5dfac812015-08-06 04:51:14 +00009367 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009368 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009369 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009370 Diag(Message->getSourceRange().getBegin(),
9371 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009372 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009373 }
9374 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009375 } else {
9376 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9377
9378 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9379 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9380 }
9381
9382 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9383 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9384 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9385 ValueDecl *Decl = ReceiverRE->getDecl();
9386 Diag(Message->getSourceRange().getBegin(),
9387 diag::warn_objc_circular_container)
9388 << Decl->getName() << Decl->getName();
9389 if (!ArgRE->isObjCSelfExpr()) {
9390 Diag(Decl->getLocation(),
9391 diag::note_objc_circular_container_declared_here)
9392 << Decl->getName();
9393 }
9394 }
9395 }
9396 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9397 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9398 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9399 ObjCIvarDecl *Decl = IvarRE->getDecl();
9400 Diag(Message->getSourceRange().getBegin(),
9401 diag::warn_objc_circular_container)
9402 << Decl->getName() << Decl->getName();
9403 Diag(Decl->getLocation(),
9404 diag::note_objc_circular_container_declared_here)
9405 << Decl->getName();
9406 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009407 }
9408 }
9409 }
9410
9411}
9412
John McCall31168b02011-06-15 23:02:42 +00009413/// Check a message send to see if it's likely to cause a retain cycle.
9414void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9415 // Only check instance methods whose selector looks like a setter.
9416 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9417 return;
9418
9419 // Try to find a variable that the receiver is strongly owned by.
9420 RetainCycleOwner owner;
9421 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009422 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009423 return;
9424 } else {
9425 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9426 owner.Variable = getCurMethodDecl()->getSelfDecl();
9427 owner.Loc = msg->getSuperLoc();
9428 owner.Range = msg->getSuperLoc();
9429 }
9430
9431 // Check whether the receiver is captured by any of the arguments.
9432 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9433 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9434 return diagnoseRetainCycle(*this, capturer, owner);
9435}
9436
9437/// Check a property assign to see if it's likely to cause a retain cycle.
9438void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9439 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009440 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009441 return;
9442
9443 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9444 diagnoseRetainCycle(*this, capturer, owner);
9445}
9446
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009447void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9448 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009449 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009450 return;
9451
9452 // Because we don't have an expression for the variable, we have to set the
9453 // location explicitly here.
9454 Owner.Loc = Var->getLocation();
9455 Owner.Range = Var->getSourceRange();
9456
9457 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9458 diagnoseRetainCycle(*this, Capturer, Owner);
9459}
9460
Ted Kremenek9304da92012-12-21 08:04:28 +00009461static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9462 Expr *RHS, bool isProperty) {
9463 // Check if RHS is an Objective-C object literal, which also can get
9464 // immediately zapped in a weak reference. Note that we explicitly
9465 // allow ObjCStringLiterals, since those are designed to never really die.
9466 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009467
Ted Kremenek64873352012-12-21 22:46:35 +00009468 // This enum needs to match with the 'select' in
9469 // warn_objc_arc_literal_assign (off-by-1).
9470 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9471 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9472 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009473
9474 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009475 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009476 << (isProperty ? 0 : 1)
9477 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009478
9479 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009480}
9481
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009482static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9483 Qualifiers::ObjCLifetime LT,
9484 Expr *RHS, bool isProperty) {
9485 // Strip off any implicit cast added to get to the one ARC-specific.
9486 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9487 if (cast->getCastKind() == CK_ARCConsumeObject) {
9488 S.Diag(Loc, diag::warn_arc_retained_assign)
9489 << (LT == Qualifiers::OCL_ExplicitNone)
9490 << (isProperty ? 0 : 1)
9491 << RHS->getSourceRange();
9492 return true;
9493 }
9494 RHS = cast->getSubExpr();
9495 }
9496
9497 if (LT == Qualifiers::OCL_Weak &&
9498 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9499 return true;
9500
9501 return false;
9502}
9503
Ted Kremenekb36234d2012-12-21 08:04:20 +00009504bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9505 QualType LHS, Expr *RHS) {
9506 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9507
9508 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9509 return false;
9510
9511 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9512 return true;
9513
9514 return false;
9515}
9516
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009517void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9518 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009519 QualType LHSType;
9520 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009521 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009522 ObjCPropertyRefExpr *PRE
9523 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9524 if (PRE && !PRE->isImplicitProperty()) {
9525 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9526 if (PD)
9527 LHSType = PD->getType();
9528 }
9529
9530 if (LHSType.isNull())
9531 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009532
9533 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9534
9535 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009536 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009537 getCurFunction()->markSafeWeakUse(LHS);
9538 }
9539
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009540 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9541 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009542
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009543 // FIXME. Check for other life times.
9544 if (LT != Qualifiers::OCL_None)
9545 return;
9546
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009547 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009548 if (PRE->isImplicitProperty())
9549 return;
9550 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9551 if (!PD)
9552 return;
9553
Bill Wendling44426052012-12-20 19:22:21 +00009554 unsigned Attributes = PD->getPropertyAttributes();
9555 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009556 // when 'assign' attribute was not explicitly specified
9557 // by user, ignore it and rely on property type itself
9558 // for lifetime info.
9559 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9560 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9561 LHSType->isObjCRetainableType())
9562 return;
9563
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009564 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009565 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009566 Diag(Loc, diag::warn_arc_retained_property_assign)
9567 << RHS->getSourceRange();
9568 return;
9569 }
9570 RHS = cast->getSubExpr();
9571 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009572 }
Bill Wendling44426052012-12-20 19:22:21 +00009573 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009574 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9575 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009576 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009577 }
9578}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009579
9580//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9581
9582namespace {
9583bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9584 SourceLocation StmtLoc,
9585 const NullStmt *Body) {
9586 // Do not warn if the body is a macro that expands to nothing, e.g:
9587 //
9588 // #define CALL(x)
9589 // if (condition)
9590 // CALL(0);
9591 //
9592 if (Body->hasLeadingEmptyMacro())
9593 return false;
9594
9595 // Get line numbers of statement and body.
9596 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009597 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009598 &StmtLineInvalid);
9599 if (StmtLineInvalid)
9600 return false;
9601
9602 bool BodyLineInvalid;
9603 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9604 &BodyLineInvalid);
9605 if (BodyLineInvalid)
9606 return false;
9607
9608 // Warn if null statement and body are on the same line.
9609 if (StmtLine != BodyLine)
9610 return false;
9611
9612 return true;
9613}
9614} // Unnamed namespace
9615
9616void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9617 const Stmt *Body,
9618 unsigned DiagID) {
9619 // Since this is a syntactic check, don't emit diagnostic for template
9620 // instantiations, this just adds noise.
9621 if (CurrentInstantiationScope)
9622 return;
9623
9624 // The body should be a null statement.
9625 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9626 if (!NBody)
9627 return;
9628
9629 // Do the usual checks.
9630 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9631 return;
9632
9633 Diag(NBody->getSemiLoc(), DiagID);
9634 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9635}
9636
9637void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9638 const Stmt *PossibleBody) {
9639 assert(!CurrentInstantiationScope); // Ensured by caller
9640
9641 SourceLocation StmtLoc;
9642 const Stmt *Body;
9643 unsigned DiagID;
9644 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9645 StmtLoc = FS->getRParenLoc();
9646 Body = FS->getBody();
9647 DiagID = diag::warn_empty_for_body;
9648 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9649 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9650 Body = WS->getBody();
9651 DiagID = diag::warn_empty_while_body;
9652 } else
9653 return; // Neither `for' nor `while'.
9654
9655 // The body should be a null statement.
9656 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9657 if (!NBody)
9658 return;
9659
9660 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009661 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009662 return;
9663
9664 // Do the usual checks.
9665 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9666 return;
9667
9668 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9669 // noise level low, emit diagnostics only if for/while is followed by a
9670 // CompoundStmt, e.g.:
9671 // for (int i = 0; i < n; i++);
9672 // {
9673 // a(i);
9674 // }
9675 // or if for/while is followed by a statement with more indentation
9676 // than for/while itself:
9677 // for (int i = 0; i < n; i++);
9678 // a(i);
9679 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9680 if (!ProbableTypo) {
9681 bool BodyColInvalid;
9682 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9683 PossibleBody->getLocStart(),
9684 &BodyColInvalid);
9685 if (BodyColInvalid)
9686 return;
9687
9688 bool StmtColInvalid;
9689 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9690 S->getLocStart(),
9691 &StmtColInvalid);
9692 if (StmtColInvalid)
9693 return;
9694
9695 if (BodyCol > StmtCol)
9696 ProbableTypo = true;
9697 }
9698
9699 if (ProbableTypo) {
9700 Diag(NBody->getSemiLoc(), DiagID);
9701 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9702 }
9703}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009704
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009705//===--- CHECK: Warn on self move with std::move. -------------------------===//
9706
9707/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9708void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9709 SourceLocation OpLoc) {
9710
9711 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9712 return;
9713
9714 if (!ActiveTemplateInstantiations.empty())
9715 return;
9716
9717 // Strip parens and casts away.
9718 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9719 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9720
9721 // Check for a call expression
9722 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9723 if (!CE || CE->getNumArgs() != 1)
9724 return;
9725
9726 // Check for a call to std::move
9727 const FunctionDecl *FD = CE->getDirectCallee();
9728 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9729 !FD->getIdentifier()->isStr("move"))
9730 return;
9731
9732 // Get argument from std::move
9733 RHSExpr = CE->getArg(0);
9734
9735 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9736 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9737
9738 // Two DeclRefExpr's, check that the decls are the same.
9739 if (LHSDeclRef && RHSDeclRef) {
9740 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9741 return;
9742 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9743 RHSDeclRef->getDecl()->getCanonicalDecl())
9744 return;
9745
9746 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9747 << LHSExpr->getSourceRange()
9748 << RHSExpr->getSourceRange();
9749 return;
9750 }
9751
9752 // Member variables require a different approach to check for self moves.
9753 // MemberExpr's are the same if every nested MemberExpr refers to the same
9754 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9755 // the base Expr's are CXXThisExpr's.
9756 const Expr *LHSBase = LHSExpr;
9757 const Expr *RHSBase = RHSExpr;
9758 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9759 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9760 if (!LHSME || !RHSME)
9761 return;
9762
9763 while (LHSME && RHSME) {
9764 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9765 RHSME->getMemberDecl()->getCanonicalDecl())
9766 return;
9767
9768 LHSBase = LHSME->getBase();
9769 RHSBase = RHSME->getBase();
9770 LHSME = dyn_cast<MemberExpr>(LHSBase);
9771 RHSME = dyn_cast<MemberExpr>(RHSBase);
9772 }
9773
9774 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9775 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9776 if (LHSDeclRef && RHSDeclRef) {
9777 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9778 return;
9779 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9780 RHSDeclRef->getDecl()->getCanonicalDecl())
9781 return;
9782
9783 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9784 << LHSExpr->getSourceRange()
9785 << RHSExpr->getSourceRange();
9786 return;
9787 }
9788
9789 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9790 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9791 << LHSExpr->getSourceRange()
9792 << RHSExpr->getSourceRange();
9793}
9794
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009795//===--- Layout compatibility ----------------------------------------------//
9796
9797namespace {
9798
9799bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9800
9801/// \brief Check if two enumeration types are layout-compatible.
9802bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9803 // C++11 [dcl.enum] p8:
9804 // Two enumeration types are layout-compatible if they have the same
9805 // underlying type.
9806 return ED1->isComplete() && ED2->isComplete() &&
9807 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9808}
9809
9810/// \brief Check if two fields are layout-compatible.
9811bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9812 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9813 return false;
9814
9815 if (Field1->isBitField() != Field2->isBitField())
9816 return false;
9817
9818 if (Field1->isBitField()) {
9819 // Make sure that the bit-fields are the same length.
9820 unsigned Bits1 = Field1->getBitWidthValue(C);
9821 unsigned Bits2 = Field2->getBitWidthValue(C);
9822
9823 if (Bits1 != Bits2)
9824 return false;
9825 }
9826
9827 return true;
9828}
9829
9830/// \brief Check if two standard-layout structs are layout-compatible.
9831/// (C++11 [class.mem] p17)
9832bool isLayoutCompatibleStruct(ASTContext &C,
9833 RecordDecl *RD1,
9834 RecordDecl *RD2) {
9835 // If both records are C++ classes, check that base classes match.
9836 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9837 // If one of records is a CXXRecordDecl we are in C++ mode,
9838 // thus the other one is a CXXRecordDecl, too.
9839 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9840 // Check number of base classes.
9841 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9842 return false;
9843
9844 // Check the base classes.
9845 for (CXXRecordDecl::base_class_const_iterator
9846 Base1 = D1CXX->bases_begin(),
9847 BaseEnd1 = D1CXX->bases_end(),
9848 Base2 = D2CXX->bases_begin();
9849 Base1 != BaseEnd1;
9850 ++Base1, ++Base2) {
9851 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9852 return false;
9853 }
9854 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9855 // If only RD2 is a C++ class, it should have zero base classes.
9856 if (D2CXX->getNumBases() > 0)
9857 return false;
9858 }
9859
9860 // Check the fields.
9861 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9862 Field2End = RD2->field_end(),
9863 Field1 = RD1->field_begin(),
9864 Field1End = RD1->field_end();
9865 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9866 if (!isLayoutCompatible(C, *Field1, *Field2))
9867 return false;
9868 }
9869 if (Field1 != Field1End || Field2 != Field2End)
9870 return false;
9871
9872 return true;
9873}
9874
9875/// \brief Check if two standard-layout unions are layout-compatible.
9876/// (C++11 [class.mem] p18)
9877bool isLayoutCompatibleUnion(ASTContext &C,
9878 RecordDecl *RD1,
9879 RecordDecl *RD2) {
9880 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009881 for (auto *Field2 : RD2->fields())
9882 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009883
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009884 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009885 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9886 I = UnmatchedFields.begin(),
9887 E = UnmatchedFields.end();
9888
9889 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009890 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009891 bool Result = UnmatchedFields.erase(*I);
9892 (void) Result;
9893 assert(Result);
9894 break;
9895 }
9896 }
9897 if (I == E)
9898 return false;
9899 }
9900
9901 return UnmatchedFields.empty();
9902}
9903
9904bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9905 if (RD1->isUnion() != RD2->isUnion())
9906 return false;
9907
9908 if (RD1->isUnion())
9909 return isLayoutCompatibleUnion(C, RD1, RD2);
9910 else
9911 return isLayoutCompatibleStruct(C, RD1, RD2);
9912}
9913
9914/// \brief Check if two types are layout-compatible in C++11 sense.
9915bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9916 if (T1.isNull() || T2.isNull())
9917 return false;
9918
9919 // C++11 [basic.types] p11:
9920 // If two types T1 and T2 are the same type, then T1 and T2 are
9921 // layout-compatible types.
9922 if (C.hasSameType(T1, T2))
9923 return true;
9924
9925 T1 = T1.getCanonicalType().getUnqualifiedType();
9926 T2 = T2.getCanonicalType().getUnqualifiedType();
9927
9928 const Type::TypeClass TC1 = T1->getTypeClass();
9929 const Type::TypeClass TC2 = T2->getTypeClass();
9930
9931 if (TC1 != TC2)
9932 return false;
9933
9934 if (TC1 == Type::Enum) {
9935 return isLayoutCompatible(C,
9936 cast<EnumType>(T1)->getDecl(),
9937 cast<EnumType>(T2)->getDecl());
9938 } else if (TC1 == Type::Record) {
9939 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9940 return false;
9941
9942 return isLayoutCompatible(C,
9943 cast<RecordType>(T1)->getDecl(),
9944 cast<RecordType>(T2)->getDecl());
9945 }
9946
9947 return false;
9948}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009949}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009950
9951//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9952
9953namespace {
9954/// \brief Given a type tag expression find the type tag itself.
9955///
9956/// \param TypeExpr Type tag expression, as it appears in user's code.
9957///
9958/// \param VD Declaration of an identifier that appears in a type tag.
9959///
9960/// \param MagicValue Type tag magic value.
9961bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9962 const ValueDecl **VD, uint64_t *MagicValue) {
9963 while(true) {
9964 if (!TypeExpr)
9965 return false;
9966
9967 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9968
9969 switch (TypeExpr->getStmtClass()) {
9970 case Stmt::UnaryOperatorClass: {
9971 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9972 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9973 TypeExpr = UO->getSubExpr();
9974 continue;
9975 }
9976 return false;
9977 }
9978
9979 case Stmt::DeclRefExprClass: {
9980 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9981 *VD = DRE->getDecl();
9982 return true;
9983 }
9984
9985 case Stmt::IntegerLiteralClass: {
9986 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9987 llvm::APInt MagicValueAPInt = IL->getValue();
9988 if (MagicValueAPInt.getActiveBits() <= 64) {
9989 *MagicValue = MagicValueAPInt.getZExtValue();
9990 return true;
9991 } else
9992 return false;
9993 }
9994
9995 case Stmt::BinaryConditionalOperatorClass:
9996 case Stmt::ConditionalOperatorClass: {
9997 const AbstractConditionalOperator *ACO =
9998 cast<AbstractConditionalOperator>(TypeExpr);
9999 bool Result;
10000 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10001 if (Result)
10002 TypeExpr = ACO->getTrueExpr();
10003 else
10004 TypeExpr = ACO->getFalseExpr();
10005 continue;
10006 }
10007 return false;
10008 }
10009
10010 case Stmt::BinaryOperatorClass: {
10011 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10012 if (BO->getOpcode() == BO_Comma) {
10013 TypeExpr = BO->getRHS();
10014 continue;
10015 }
10016 return false;
10017 }
10018
10019 default:
10020 return false;
10021 }
10022 }
10023}
10024
10025/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10026///
10027/// \param TypeExpr Expression that specifies a type tag.
10028///
10029/// \param MagicValues Registered magic values.
10030///
10031/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10032/// kind.
10033///
10034/// \param TypeInfo Information about the corresponding C type.
10035///
10036/// \returns true if the corresponding C type was found.
10037bool GetMatchingCType(
10038 const IdentifierInfo *ArgumentKind,
10039 const Expr *TypeExpr, const ASTContext &Ctx,
10040 const llvm::DenseMap<Sema::TypeTagMagicValue,
10041 Sema::TypeTagData> *MagicValues,
10042 bool &FoundWrongKind,
10043 Sema::TypeTagData &TypeInfo) {
10044 FoundWrongKind = false;
10045
10046 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010047 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010048
10049 uint64_t MagicValue;
10050
10051 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10052 return false;
10053
10054 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010055 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010056 if (I->getArgumentKind() != ArgumentKind) {
10057 FoundWrongKind = true;
10058 return false;
10059 }
10060 TypeInfo.Type = I->getMatchingCType();
10061 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10062 TypeInfo.MustBeNull = I->getMustBeNull();
10063 return true;
10064 }
10065 return false;
10066 }
10067
10068 if (!MagicValues)
10069 return false;
10070
10071 llvm::DenseMap<Sema::TypeTagMagicValue,
10072 Sema::TypeTagData>::const_iterator I =
10073 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10074 if (I == MagicValues->end())
10075 return false;
10076
10077 TypeInfo = I->second;
10078 return true;
10079}
10080} // unnamed namespace
10081
10082void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10083 uint64_t MagicValue, QualType Type,
10084 bool LayoutCompatible,
10085 bool MustBeNull) {
10086 if (!TypeTagForDatatypeMagicValues)
10087 TypeTagForDatatypeMagicValues.reset(
10088 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10089
10090 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10091 (*TypeTagForDatatypeMagicValues)[Magic] =
10092 TypeTagData(Type, LayoutCompatible, MustBeNull);
10093}
10094
10095namespace {
10096bool IsSameCharType(QualType T1, QualType T2) {
10097 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10098 if (!BT1)
10099 return false;
10100
10101 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10102 if (!BT2)
10103 return false;
10104
10105 BuiltinType::Kind T1Kind = BT1->getKind();
10106 BuiltinType::Kind T2Kind = BT2->getKind();
10107
10108 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10109 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10110 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10111 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10112}
10113} // unnamed namespace
10114
10115void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10116 const Expr * const *ExprArgs) {
10117 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10118 bool IsPointerAttr = Attr->getIsPointer();
10119
10120 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10121 bool FoundWrongKind;
10122 TypeTagData TypeInfo;
10123 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10124 TypeTagForDatatypeMagicValues.get(),
10125 FoundWrongKind, TypeInfo)) {
10126 if (FoundWrongKind)
10127 Diag(TypeTagExpr->getExprLoc(),
10128 diag::warn_type_tag_for_datatype_wrong_kind)
10129 << TypeTagExpr->getSourceRange();
10130 return;
10131 }
10132
10133 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10134 if (IsPointerAttr) {
10135 // Skip implicit cast of pointer to `void *' (as a function argument).
10136 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010137 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010138 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010139 ArgumentExpr = ICE->getSubExpr();
10140 }
10141 QualType ArgumentType = ArgumentExpr->getType();
10142
10143 // Passing a `void*' pointer shouldn't trigger a warning.
10144 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10145 return;
10146
10147 if (TypeInfo.MustBeNull) {
10148 // Type tag with matching void type requires a null pointer.
10149 if (!ArgumentExpr->isNullPointerConstant(Context,
10150 Expr::NPC_ValueDependentIsNotNull)) {
10151 Diag(ArgumentExpr->getExprLoc(),
10152 diag::warn_type_safety_null_pointer_required)
10153 << ArgumentKind->getName()
10154 << ArgumentExpr->getSourceRange()
10155 << TypeTagExpr->getSourceRange();
10156 }
10157 return;
10158 }
10159
10160 QualType RequiredType = TypeInfo.Type;
10161 if (IsPointerAttr)
10162 RequiredType = Context.getPointerType(RequiredType);
10163
10164 bool mismatch = false;
10165 if (!TypeInfo.LayoutCompatible) {
10166 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10167
10168 // C++11 [basic.fundamental] p1:
10169 // Plain char, signed char, and unsigned char are three distinct types.
10170 //
10171 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10172 // char' depending on the current char signedness mode.
10173 if (mismatch)
10174 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10175 RequiredType->getPointeeType())) ||
10176 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10177 mismatch = false;
10178 } else
10179 if (IsPointerAttr)
10180 mismatch = !isLayoutCompatible(Context,
10181 ArgumentType->getPointeeType(),
10182 RequiredType->getPointeeType());
10183 else
10184 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10185
10186 if (mismatch)
10187 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010188 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010189 << TypeInfo.LayoutCompatible << RequiredType
10190 << ArgumentExpr->getSourceRange()
10191 << TypeTagExpr->getSourceRange();
10192}