blob: c38dda6464c442cc2a1b79f494372734768602cd [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000024#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000025#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000028#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000031#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000039#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000041#include <limits>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000042
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000044using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000045
Chris Lattnera26fb342009-02-18 17:49:48 +000046SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
47 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000048 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
49 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000050}
51
John McCallbebede42011-02-26 05:39:39 +000052/// Checks that a call expression's argument count is the desired number.
53/// This is useful when doing custom type-checking. Returns true on error.
54static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
55 unsigned argCount = call->getNumArgs();
56 if (argCount == desiredArgCount) return false;
57
58 if (argCount < desiredArgCount)
59 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
60 << 0 /*function call*/ << desiredArgCount << argCount
61 << call->getSourceRange();
62
63 // Highlight all the excess arguments.
64 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
65 call->getArg(argCount - 1)->getLocEnd());
66
67 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
68 << 0 /*function call*/ << desiredArgCount << argCount
69 << call->getArg(1)->getSourceRange();
70}
71
Julien Lerouge4a5b4442012-04-28 17:39:16 +000072/// Check that the first argument to __builtin_annotation is an integer
73/// and the second argument is a non-wide string literal.
74static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
75 if (checkArgCount(S, TheCall, 2))
76 return true;
77
78 // First argument should be an integer.
79 Expr *ValArg = TheCall->getArg(0);
80 QualType Ty = ValArg->getType();
81 if (!Ty->isIntegerType()) {
82 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
83 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000084 return true;
85 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000086
87 // Second argument should be a constant string.
88 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
89 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
90 if (!Literal || !Literal->isAscii()) {
91 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
92 << StrArg->getSourceRange();
93 return true;
94 }
95
96 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000097 return false;
98}
99
Richard Smith6cbd65d2013-07-11 02:27:57 +0000100/// Check that the argument to __builtin_addressof is a glvalue, and set the
101/// result type to the corresponding pointer type.
102static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
103 if (checkArgCount(S, TheCall, 1))
104 return true;
105
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000106 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000107 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
108 if (ResultType.isNull())
109 return true;
110
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000111 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000112 TheCall->setType(ResultType);
113 return false;
114}
115
John McCall03107a42015-10-29 20:48:01 +0000116static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
117 if (checkArgCount(S, TheCall, 3))
118 return true;
119
120 // First two arguments should be integers.
121 for (unsigned I = 0; I < 2; ++I) {
122 Expr *Arg = TheCall->getArg(I);
123 QualType Ty = Arg->getType();
124 if (!Ty->isIntegerType()) {
125 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
126 << Ty << Arg->getSourceRange();
127 return true;
128 }
129 }
130
131 // Third argument should be a pointer to a non-const integer.
132 // IRGen correctly handles volatile, restrict, and address spaces, and
133 // the other qualifiers aren't possible.
134 {
135 Expr *Arg = TheCall->getArg(2);
136 QualType Ty = Arg->getType();
137 const auto *PtrTy = Ty->getAs<PointerType>();
138 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
139 !PtrTy->getPointeeType().isConstQualified())) {
140 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
141 << Ty << Arg->getSourceRange();
142 return true;
143 }
144 }
145
146 return false;
147}
148
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000149static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
150 CallExpr *TheCall, unsigned SizeIdx,
151 unsigned DstSizeIdx) {
152 if (TheCall->getNumArgs() <= SizeIdx ||
153 TheCall->getNumArgs() <= DstSizeIdx)
154 return;
155
156 const Expr *SizeArg = TheCall->getArg(SizeIdx);
157 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
158
159 llvm::APSInt Size, DstSize;
160
161 // find out if both sizes are known at compile time
162 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
163 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
164 return;
165
166 if (Size.ule(DstSize))
167 return;
168
169 // confirmed overflow so generate the diagnostic.
170 IdentifierInfo *FnName = FDecl->getIdentifier();
171 SourceLocation SL = TheCall->getLocStart();
172 SourceRange SR = TheCall->getSourceRange();
173
174 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
175}
176
Peter Collingbournef7706832014-12-12 23:41:25 +0000177static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
178 if (checkArgCount(S, BuiltinCall, 2))
179 return true;
180
181 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
182 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
183 Expr *Call = BuiltinCall->getArg(0);
184 Expr *Chain = BuiltinCall->getArg(1);
185
186 if (Call->getStmtClass() != Stmt::CallExprClass) {
187 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
188 << Call->getSourceRange();
189 return true;
190 }
191
192 auto CE = cast<CallExpr>(Call);
193 if (CE->getCallee()->getType()->isBlockPointerType()) {
194 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
195 << Call->getSourceRange();
196 return true;
197 }
198
199 const Decl *TargetDecl = CE->getCalleeDecl();
200 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
201 if (FD->getBuiltinID()) {
202 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
203 << Call->getSourceRange();
204 return true;
205 }
206
207 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
208 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
209 << Call->getSourceRange();
210 return true;
211 }
212
213 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
214 if (ChainResult.isInvalid())
215 return true;
216 if (!ChainResult.get()->getType()->isPointerType()) {
217 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
218 << Chain->getSourceRange();
219 return true;
220 }
221
David Majnemerced8bdf2015-02-25 17:36:15 +0000222 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000223 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
224 QualType BuiltinTy = S.Context.getFunctionType(
225 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
226 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
227
228 Builtin =
229 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
230
231 BuiltinCall->setType(CE->getType());
232 BuiltinCall->setValueKind(CE->getValueKind());
233 BuiltinCall->setObjectKind(CE->getObjectKind());
234 BuiltinCall->setCallee(Builtin);
235 BuiltinCall->setArg(1, ChainResult.get());
236
237 return false;
238}
239
Reid Kleckner1d59f992015-01-22 01:36:17 +0000240static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
241 Scope::ScopeFlags NeededScopeFlags,
242 unsigned DiagID) {
243 // Scopes aren't available during instantiation. Fortunately, builtin
244 // functions cannot be template args so they cannot be formed through template
245 // instantiation. Therefore checking once during the parse is sufficient.
246 if (!SemaRef.ActiveTemplateInstantiations.empty())
247 return false;
248
249 Scope *S = SemaRef.getCurScope();
250 while (S && !S->isSEHExceptScope())
251 S = S->getParent();
252 if (!S || !(S->getFlags() & NeededScopeFlags)) {
253 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
254 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
255 << DRE->getDecl()->getIdentifier();
256 return true;
257 }
258
259 return false;
260}
261
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000262/// Returns readable name for a call.
263static StringRef getFunctionName(CallExpr *Call) {
264 return cast<FunctionDecl>(Call->getCalleeDecl())->getName();
265}
266
267/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000268static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
269 if (D->hasAttr<OpenCLAccessAttr>())
270 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000271 return nullptr;
272}
273
274/// Returns true if pipe element type is different from the pointer.
275static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
276 const Expr *Arg0 = Call->getArg(0);
277 // First argument type should always be pipe.
278 if (!Arg0->getType()->isPipeType()) {
279 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
280 << getFunctionName(Call) << Arg0->getSourceRange();
281 return true;
282 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000283 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000284 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
285 // Validates the access qualifier is compatible with the call.
286 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
287 // read_only and write_only, and assumed to be read_only if no qualifier is
288 // specified.
289 bool isValid = true;
290 bool ReadOnly = getFunctionName(Call).find("read") != StringRef::npos;
291 if (ReadOnly)
292 isValid = AccessQual == nullptr || AccessQual->isReadOnly();
293 else
294 isValid = AccessQual != nullptr && AccessQual->isWriteOnly();
295 if (!isValid) {
296 const char *AM = ReadOnly ? "read_only" : "write_only";
297 S.Diag(Arg0->getLocStart(),
298 diag::err_opencl_builtin_pipe_invalid_access_modifier)
299 << AM << Arg0->getSourceRange();
300 return true;
301 }
302
303 return false;
304}
305
306/// Returns true if pipe element type is different from the pointer.
307static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
308 const Expr *Arg0 = Call->getArg(0);
309 const Expr *ArgIdx = Call->getArg(Idx);
310 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
311 const Type *EltTy = PipeTy->getElementType().getTypePtr();
312 const PointerType *ArgTy =
313 dyn_cast<PointerType>(ArgIdx->getType().getTypePtr());
314 // The Idx argument should be a pointer and the type of the pointer and
315 // the type of pipe element should also be the same.
316 if (!ArgTy || EltTy != ArgTy->getPointeeType().getTypePtr()) {
317 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
318 << getFunctionName(Call)
319 << S.Context.getPointerType(PipeTy->getElementType())
320 << ArgIdx->getSourceRange();
321 return true;
322 }
323 return false;
324}
325
326// \brief Performs semantic analysis for the read/write_pipe call.
327// \param S Reference to the semantic analyzer.
328// \param Call A pointer to the builtin call.
329// \return True if a semantic error has been found, false otherwise.
330static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
331 // Two kinds of read/write pipe
332 // From OpenCL C Specification 6.13.16.2 the built-in read/write
333 // functions have following forms.
334 switch (Call->getNumArgs()) {
335 case 2: {
336 if (checkOpenCLPipeArg(S, Call))
337 return true;
338 // The call with 2 arguments should be
339 // read/write_pipe(pipe T, T*)
340 // check packet type T
341 if (checkOpenCLPipePacketType(S, Call, 1))
342 return true;
343 } break;
344
345 case 4: {
346 if (checkOpenCLPipeArg(S, Call))
347 return true;
348 // The call with 4 arguments should be
349 // read/write_pipe(pipe T, reserve_id_t, uint, T*)
350 // check reserve_id_t
351 if (!Call->getArg(1)->getType()->isReserveIDT()) {
352 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
353 << getFunctionName(Call) << S.Context.OCLReserveIDTy
354 << Call->getArg(1)->getSourceRange();
355 return true;
356 }
357
358 // check the index
359 const Expr *Arg2 = Call->getArg(2);
360 if (!Arg2->getType()->isIntegerType() &&
361 !Arg2->getType()->isUnsignedIntegerType()) {
362 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
363 << getFunctionName(Call) << S.Context.UnsignedIntTy
364 << Arg2->getSourceRange();
365 return true;
366 }
367
368 // check packet type T
369 if (checkOpenCLPipePacketType(S, Call, 3))
370 return true;
371 } break;
372 default:
373 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
374 << getFunctionName(Call) << Call->getSourceRange();
375 return true;
376 }
377
378 return false;
379}
380
381// \brief Performs a semantic analysis on the {work_group_/sub_group_
382// /_}reserve_{read/write}_pipe
383// \param S Reference to the semantic analyzer.
384// \param Call The call to the builtin function to be analyzed.
385// \return True if a semantic error was found, false otherwise.
386static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
387 if (checkArgCount(S, Call, 2))
388 return true;
389
390 if (checkOpenCLPipeArg(S, Call))
391 return true;
392
393 // check the reserve size
394 if (!Call->getArg(1)->getType()->isIntegerType() &&
395 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
396 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
397 << getFunctionName(Call) << S.Context.UnsignedIntTy
398 << Call->getArg(1)->getSourceRange();
399 return true;
400 }
401
402 return false;
403}
404
405// \brief Performs a semantic analysis on {work_group_/sub_group_
406// /_}commit_{read/write}_pipe
407// \param S Reference to the semantic analyzer.
408// \param Call The call to the builtin function to be analyzed.
409// \return True if a semantic error was found, false otherwise.
410static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
411 if (checkArgCount(S, Call, 2))
412 return true;
413
414 if (checkOpenCLPipeArg(S, Call))
415 return true;
416
417 // check reserve_id_t
418 if (!Call->getArg(1)->getType()->isReserveIDT()) {
419 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
420 << getFunctionName(Call) << S.Context.OCLReserveIDTy
421 << Call->getArg(1)->getSourceRange();
422 return true;
423 }
424
425 return false;
426}
427
428// \brief Performs a semantic analysis on the call to built-in Pipe
429// Query Functions.
430// \param S Reference to the semantic analyzer.
431// \param Call The call to the builtin function to be analyzed.
432// \return True if a semantic error was found, false otherwise.
433static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
434 if (checkArgCount(S, Call, 1))
435 return true;
436
437 if (!Call->getArg(0)->getType()->isPipeType()) {
438 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
439 << getFunctionName(Call) << Call->getArg(0)->getSourceRange();
440 return true;
441 }
442
443 return false;
444}
445
John McCalldadc5752010-08-24 06:29:42 +0000446ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000447Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
448 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000449 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000450
Chris Lattner3be167f2010-10-01 23:23:24 +0000451 // Find out if any arguments are required to be integer constant expressions.
452 unsigned ICEArguments = 0;
453 ASTContext::GetBuiltinTypeError Error;
454 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
455 if (Error != ASTContext::GE_None)
456 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
457
458 // If any arguments are required to be ICE's, check and diagnose.
459 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
460 // Skip arguments not required to be ICE's.
461 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
462
463 llvm::APSInt Result;
464 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
465 return true;
466 ICEArguments &= ~(1 << ArgNo);
467 }
468
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000469 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000470 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000471 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000472 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000473 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000474 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000475 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000476 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000477 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000478 if (SemaBuiltinVAStart(TheCall))
479 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000480 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000481 case Builtin::BI__va_start: {
482 switch (Context.getTargetInfo().getTriple().getArch()) {
483 case llvm::Triple::arm:
484 case llvm::Triple::thumb:
485 if (SemaBuiltinVAStartARM(TheCall))
486 return ExprError();
487 break;
488 default:
489 if (SemaBuiltinVAStart(TheCall))
490 return ExprError();
491 break;
492 }
493 break;
494 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000495 case Builtin::BI__builtin_isgreater:
496 case Builtin::BI__builtin_isgreaterequal:
497 case Builtin::BI__builtin_isless:
498 case Builtin::BI__builtin_islessequal:
499 case Builtin::BI__builtin_islessgreater:
500 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000501 if (SemaBuiltinUnorderedCompare(TheCall))
502 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000503 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000504 case Builtin::BI__builtin_fpclassify:
505 if (SemaBuiltinFPClassification(TheCall, 6))
506 return ExprError();
507 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000508 case Builtin::BI__builtin_isfinite:
509 case Builtin::BI__builtin_isinf:
510 case Builtin::BI__builtin_isinf_sign:
511 case Builtin::BI__builtin_isnan:
512 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000513 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000514 return ExprError();
515 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000516 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000517 return SemaBuiltinShuffleVector(TheCall);
518 // TheCall will be freed by the smart pointer here, but that's fine, since
519 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000520 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000521 if (SemaBuiltinPrefetch(TheCall))
522 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000523 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000524 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000525 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000526 if (SemaBuiltinAssume(TheCall))
527 return ExprError();
528 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000529 case Builtin::BI__builtin_assume_aligned:
530 if (SemaBuiltinAssumeAligned(TheCall))
531 return ExprError();
532 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000533 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000534 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000535 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000536 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000537 case Builtin::BI__builtin_longjmp:
538 if (SemaBuiltinLongjmp(TheCall))
539 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000540 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000541 case Builtin::BI__builtin_setjmp:
542 if (SemaBuiltinSetjmp(TheCall))
543 return ExprError();
544 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000545 case Builtin::BI_setjmp:
546 case Builtin::BI_setjmpex:
547 if (checkArgCount(*this, TheCall, 1))
548 return true;
549 break;
John McCallbebede42011-02-26 05:39:39 +0000550
551 case Builtin::BI__builtin_classify_type:
552 if (checkArgCount(*this, TheCall, 1)) return true;
553 TheCall->setType(Context.IntTy);
554 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000555 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000556 if (checkArgCount(*this, TheCall, 1)) return true;
557 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000558 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000559 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000560 case Builtin::BI__sync_fetch_and_add_1:
561 case Builtin::BI__sync_fetch_and_add_2:
562 case Builtin::BI__sync_fetch_and_add_4:
563 case Builtin::BI__sync_fetch_and_add_8:
564 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000565 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000566 case Builtin::BI__sync_fetch_and_sub_1:
567 case Builtin::BI__sync_fetch_and_sub_2:
568 case Builtin::BI__sync_fetch_and_sub_4:
569 case Builtin::BI__sync_fetch_and_sub_8:
570 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000571 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000572 case Builtin::BI__sync_fetch_and_or_1:
573 case Builtin::BI__sync_fetch_and_or_2:
574 case Builtin::BI__sync_fetch_and_or_4:
575 case Builtin::BI__sync_fetch_and_or_8:
576 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000577 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000578 case Builtin::BI__sync_fetch_and_and_1:
579 case Builtin::BI__sync_fetch_and_and_2:
580 case Builtin::BI__sync_fetch_and_and_4:
581 case Builtin::BI__sync_fetch_and_and_8:
582 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000583 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000584 case Builtin::BI__sync_fetch_and_xor_1:
585 case Builtin::BI__sync_fetch_and_xor_2:
586 case Builtin::BI__sync_fetch_and_xor_4:
587 case Builtin::BI__sync_fetch_and_xor_8:
588 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000589 case Builtin::BI__sync_fetch_and_nand:
590 case Builtin::BI__sync_fetch_and_nand_1:
591 case Builtin::BI__sync_fetch_and_nand_2:
592 case Builtin::BI__sync_fetch_and_nand_4:
593 case Builtin::BI__sync_fetch_and_nand_8:
594 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000595 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000596 case Builtin::BI__sync_add_and_fetch_1:
597 case Builtin::BI__sync_add_and_fetch_2:
598 case Builtin::BI__sync_add_and_fetch_4:
599 case Builtin::BI__sync_add_and_fetch_8:
600 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000601 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000602 case Builtin::BI__sync_sub_and_fetch_1:
603 case Builtin::BI__sync_sub_and_fetch_2:
604 case Builtin::BI__sync_sub_and_fetch_4:
605 case Builtin::BI__sync_sub_and_fetch_8:
606 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000607 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000608 case Builtin::BI__sync_and_and_fetch_1:
609 case Builtin::BI__sync_and_and_fetch_2:
610 case Builtin::BI__sync_and_and_fetch_4:
611 case Builtin::BI__sync_and_and_fetch_8:
612 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000613 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000614 case Builtin::BI__sync_or_and_fetch_1:
615 case Builtin::BI__sync_or_and_fetch_2:
616 case Builtin::BI__sync_or_and_fetch_4:
617 case Builtin::BI__sync_or_and_fetch_8:
618 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000619 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000620 case Builtin::BI__sync_xor_and_fetch_1:
621 case Builtin::BI__sync_xor_and_fetch_2:
622 case Builtin::BI__sync_xor_and_fetch_4:
623 case Builtin::BI__sync_xor_and_fetch_8:
624 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000625 case Builtin::BI__sync_nand_and_fetch:
626 case Builtin::BI__sync_nand_and_fetch_1:
627 case Builtin::BI__sync_nand_and_fetch_2:
628 case Builtin::BI__sync_nand_and_fetch_4:
629 case Builtin::BI__sync_nand_and_fetch_8:
630 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000631 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000632 case Builtin::BI__sync_val_compare_and_swap_1:
633 case Builtin::BI__sync_val_compare_and_swap_2:
634 case Builtin::BI__sync_val_compare_and_swap_4:
635 case Builtin::BI__sync_val_compare_and_swap_8:
636 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000637 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000638 case Builtin::BI__sync_bool_compare_and_swap_1:
639 case Builtin::BI__sync_bool_compare_and_swap_2:
640 case Builtin::BI__sync_bool_compare_and_swap_4:
641 case Builtin::BI__sync_bool_compare_and_swap_8:
642 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000643 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000644 case Builtin::BI__sync_lock_test_and_set_1:
645 case Builtin::BI__sync_lock_test_and_set_2:
646 case Builtin::BI__sync_lock_test_and_set_4:
647 case Builtin::BI__sync_lock_test_and_set_8:
648 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000649 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000650 case Builtin::BI__sync_lock_release_1:
651 case Builtin::BI__sync_lock_release_2:
652 case Builtin::BI__sync_lock_release_4:
653 case Builtin::BI__sync_lock_release_8:
654 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000655 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000656 case Builtin::BI__sync_swap_1:
657 case Builtin::BI__sync_swap_2:
658 case Builtin::BI__sync_swap_4:
659 case Builtin::BI__sync_swap_8:
660 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000661 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000662 case Builtin::BI__builtin_nontemporal_load:
663 case Builtin::BI__builtin_nontemporal_store:
664 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000665#define BUILTIN(ID, TYPE, ATTRS)
666#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
667 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000668 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000669#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000670 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000671 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000672 return ExprError();
673 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000674 case Builtin::BI__builtin_addressof:
675 if (SemaBuiltinAddressof(*this, TheCall))
676 return ExprError();
677 break;
John McCall03107a42015-10-29 20:48:01 +0000678 case Builtin::BI__builtin_add_overflow:
679 case Builtin::BI__builtin_sub_overflow:
680 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000681 if (SemaBuiltinOverflow(*this, TheCall))
682 return ExprError();
683 break;
Richard Smith760520b2014-06-03 23:27:44 +0000684 case Builtin::BI__builtin_operator_new:
685 case Builtin::BI__builtin_operator_delete:
686 if (!getLangOpts().CPlusPlus) {
687 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
688 << (BuiltinID == Builtin::BI__builtin_operator_new
689 ? "__builtin_operator_new"
690 : "__builtin_operator_delete")
691 << "C++";
692 return ExprError();
693 }
694 // CodeGen assumes it can find the global new and delete to call,
695 // so ensure that they are declared.
696 DeclareGlobalNewDelete();
697 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000698
699 // check secure string manipulation functions where overflows
700 // are detectable at compile time
701 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000702 case Builtin::BI__builtin___memmove_chk:
703 case Builtin::BI__builtin___memset_chk:
704 case Builtin::BI__builtin___strlcat_chk:
705 case Builtin::BI__builtin___strlcpy_chk:
706 case Builtin::BI__builtin___strncat_chk:
707 case Builtin::BI__builtin___strncpy_chk:
708 case Builtin::BI__builtin___stpncpy_chk:
709 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
710 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000711 case Builtin::BI__builtin___memccpy_chk:
712 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
713 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000714 case Builtin::BI__builtin___snprintf_chk:
715 case Builtin::BI__builtin___vsnprintf_chk:
716 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
717 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000718 case Builtin::BI__builtin_call_with_static_chain:
719 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
720 return ExprError();
721 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000722 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000723 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000724 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
725 diag::err_seh___except_block))
726 return ExprError();
727 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000728 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000729 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000730 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
731 diag::err_seh___except_filter))
732 return ExprError();
733 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +0000734 case Builtin::BI__GetExceptionInfo:
735 if (checkArgCount(*this, TheCall, 1))
736 return ExprError();
737
738 if (CheckCXXThrowOperand(
739 TheCall->getLocStart(),
740 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
741 TheCall))
742 return ExprError();
743
744 TheCall->setType(Context.VoidPtrTy);
745 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000746 case Builtin::BIread_pipe:
747 case Builtin::BIwrite_pipe:
748 // Since those two functions are declared with var args, we need a semantic
749 // check for the argument.
750 if (SemaBuiltinRWPipe(*this, TheCall))
751 return ExprError();
752 break;
753 case Builtin::BIreserve_read_pipe:
754 case Builtin::BIreserve_write_pipe:
755 case Builtin::BIwork_group_reserve_read_pipe:
756 case Builtin::BIwork_group_reserve_write_pipe:
757 case Builtin::BIsub_group_reserve_read_pipe:
758 case Builtin::BIsub_group_reserve_write_pipe:
759 if (SemaBuiltinReserveRWPipe(*this, TheCall))
760 return ExprError();
761 // Since return type of reserve_read/write_pipe built-in function is
762 // reserve_id_t, which is not defined in the builtin def file , we used int
763 // as return type and need to override the return type of these functions.
764 TheCall->setType(Context.OCLReserveIDTy);
765 break;
766 case Builtin::BIcommit_read_pipe:
767 case Builtin::BIcommit_write_pipe:
768 case Builtin::BIwork_group_commit_read_pipe:
769 case Builtin::BIwork_group_commit_write_pipe:
770 case Builtin::BIsub_group_commit_read_pipe:
771 case Builtin::BIsub_group_commit_write_pipe:
772 if (SemaBuiltinCommitRWPipe(*this, TheCall))
773 return ExprError();
774 break;
775 case Builtin::BIget_pipe_num_packets:
776 case Builtin::BIget_pipe_max_packets:
777 if (SemaBuiltinPipePackets(*this, TheCall))
778 return ExprError();
779 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000780 }
Richard Smith760520b2014-06-03 23:27:44 +0000781
Nate Begeman4904e322010-06-08 02:47:44 +0000782 // Since the target specific builtins for each arch overlap, only check those
783 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +0000784 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000785 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000786 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000787 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000788 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000789 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000790 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
791 return ExprError();
792 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000793 case llvm::Triple::aarch64:
794 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000795 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000796 return ExprError();
797 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000798 case llvm::Triple::mips:
799 case llvm::Triple::mipsel:
800 case llvm::Triple::mips64:
801 case llvm::Triple::mips64el:
802 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
803 return ExprError();
804 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000805 case llvm::Triple::systemz:
806 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
807 return ExprError();
808 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000809 case llvm::Triple::x86:
810 case llvm::Triple::x86_64:
811 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
812 return ExprError();
813 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000814 case llvm::Triple::ppc:
815 case llvm::Triple::ppc64:
816 case llvm::Triple::ppc64le:
817 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
818 return ExprError();
819 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000820 default:
821 break;
822 }
823 }
824
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000825 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000826}
827
Nate Begeman91e1fea2010-06-14 05:21:25 +0000828// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000829static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000830 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000831 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000832 switch (Type.getEltType()) {
833 case NeonTypeFlags::Int8:
834 case NeonTypeFlags::Poly8:
835 return shift ? 7 : (8 << IsQuad) - 1;
836 case NeonTypeFlags::Int16:
837 case NeonTypeFlags::Poly16:
838 return shift ? 15 : (4 << IsQuad) - 1;
839 case NeonTypeFlags::Int32:
840 return shift ? 31 : (2 << IsQuad) - 1;
841 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000842 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000843 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000844 case NeonTypeFlags::Poly128:
845 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000846 case NeonTypeFlags::Float16:
847 assert(!shift && "cannot shift float types!");
848 return (4 << IsQuad) - 1;
849 case NeonTypeFlags::Float32:
850 assert(!shift && "cannot shift float types!");
851 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000852 case NeonTypeFlags::Float64:
853 assert(!shift && "cannot shift float types!");
854 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000855 }
David Blaikie8a40f702012-01-17 06:56:22 +0000856 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000857}
858
Bob Wilsone4d77232011-11-08 05:04:11 +0000859/// getNeonEltType - Return the QualType corresponding to the elements of
860/// the vector type specified by the NeonTypeFlags. This is used to check
861/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000862static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000863 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000864 switch (Flags.getEltType()) {
865 case NeonTypeFlags::Int8:
866 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
867 case NeonTypeFlags::Int16:
868 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
869 case NeonTypeFlags::Int32:
870 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
871 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000872 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000873 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
874 else
875 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
876 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000877 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000878 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000879 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000880 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000881 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000882 if (IsInt64Long)
883 return Context.UnsignedLongTy;
884 else
885 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000886 case NeonTypeFlags::Poly128:
887 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000888 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000889 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000890 case NeonTypeFlags::Float32:
891 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000892 case NeonTypeFlags::Float64:
893 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000894 }
David Blaikie8a40f702012-01-17 06:56:22 +0000895 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000896}
897
Tim Northover12670412014-02-19 10:37:05 +0000898bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000899 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000900 uint64_t mask = 0;
901 unsigned TV = 0;
902 int PtrArgNum = -1;
903 bool HasConstPtr = false;
904 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000905#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000906#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000907#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000908 }
909
910 // For NEON intrinsics which are overloaded on vector element type, validate
911 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000912 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000913 if (mask) {
914 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
915 return true;
916
917 TV = Result.getLimitedValue(64);
918 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
919 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000920 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000921 }
922
923 if (PtrArgNum >= 0) {
924 // Check that pointer arguments have the specified type.
925 Expr *Arg = TheCall->getArg(PtrArgNum);
926 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
927 Arg = ICE->getSubExpr();
928 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
929 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000930
Tim Northovera2ee4332014-03-29 15:09:45 +0000931 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000932 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000933 bool IsInt64Long =
934 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
935 QualType EltTy =
936 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000937 if (HasConstPtr)
938 EltTy = EltTy.withConst();
939 QualType LHSTy = Context.getPointerType(EltTy);
940 AssignConvertType ConvTy;
941 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
942 if (RHS.isInvalid())
943 return true;
944 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
945 RHS.get(), AA_Assigning))
946 return true;
947 }
948
949 // For NEON intrinsics which take an immediate value as part of the
950 // instruction, range check them here.
951 unsigned i = 0, l = 0, u = 0;
952 switch (BuiltinID) {
953 default:
954 return false;
Tim Northover12670412014-02-19 10:37:05 +0000955#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000956#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000957#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000958 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000959
Richard Sandiford28940af2014-04-16 08:47:51 +0000960 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000961}
962
Tim Northovera2ee4332014-03-29 15:09:45 +0000963bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
964 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000965 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000966 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000967 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000968 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000969 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000970 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
971 BuiltinID == AArch64::BI__builtin_arm_strex ||
972 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000973 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000974 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000975 BuiltinID == ARM::BI__builtin_arm_ldaex ||
976 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
977 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000978
979 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
980
981 // Ensure that we have the proper number of arguments.
982 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
983 return true;
984
985 // Inspect the pointer argument of the atomic builtin. This should always be
986 // a pointer type, whose element is an integral scalar or pointer type.
987 // Because it is a pointer type, we don't have to worry about any implicit
988 // casts here.
989 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
990 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
991 if (PointerArgRes.isInvalid())
992 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000993 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000994
995 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
996 if (!pointerType) {
997 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
998 << PointerArg->getType() << PointerArg->getSourceRange();
999 return true;
1000 }
1001
1002 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1003 // task is to insert the appropriate casts into the AST. First work out just
1004 // what the appropriate type is.
1005 QualType ValType = pointerType->getPointeeType();
1006 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1007 if (IsLdrex)
1008 AddrType.addConst();
1009
1010 // Issue a warning if the cast is dodgy.
1011 CastKind CastNeeded = CK_NoOp;
1012 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1013 CastNeeded = CK_BitCast;
1014 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1015 << PointerArg->getType()
1016 << Context.getPointerType(AddrType)
1017 << AA_Passing << PointerArg->getSourceRange();
1018 }
1019
1020 // Finally, do the cast and replace the argument with the corrected version.
1021 AddrType = Context.getPointerType(AddrType);
1022 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1023 if (PointerArgRes.isInvalid())
1024 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001025 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001026
1027 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1028
1029 // In general, we allow ints, floats and pointers to be loaded and stored.
1030 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1031 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1032 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1033 << PointerArg->getType() << PointerArg->getSourceRange();
1034 return true;
1035 }
1036
1037 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001038 if (Context.getTypeSize(ValType) > MaxWidth) {
1039 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001040 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1041 << PointerArg->getType() << PointerArg->getSourceRange();
1042 return true;
1043 }
1044
1045 switch (ValType.getObjCLifetime()) {
1046 case Qualifiers::OCL_None:
1047 case Qualifiers::OCL_ExplicitNone:
1048 // okay
1049 break;
1050
1051 case Qualifiers::OCL_Weak:
1052 case Qualifiers::OCL_Strong:
1053 case Qualifiers::OCL_Autoreleasing:
1054 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1055 << ValType << PointerArg->getSourceRange();
1056 return true;
1057 }
1058
Tim Northover6aacd492013-07-16 09:47:53 +00001059 if (IsLdrex) {
1060 TheCall->setType(ValType);
1061 return false;
1062 }
1063
1064 // Initialize the argument to be stored.
1065 ExprResult ValArg = TheCall->getArg(0);
1066 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1067 Context, ValType, /*consume*/ false);
1068 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1069 if (ValArg.isInvalid())
1070 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001071 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001072
1073 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1074 // but the custom checker bypasses all default analysis.
1075 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001076 return false;
1077}
1078
Nate Begeman4904e322010-06-08 02:47:44 +00001079bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001080 llvm::APSInt Result;
1081
Tim Northover6aacd492013-07-16 09:47:53 +00001082 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001083 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1084 BuiltinID == ARM::BI__builtin_arm_strex ||
1085 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001086 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001087 }
1088
Yi Kong26d104a2014-08-13 19:18:14 +00001089 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1090 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1091 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1092 }
1093
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001094 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1095 BuiltinID == ARM::BI__builtin_arm_wsr64)
1096 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1097
1098 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1099 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1100 BuiltinID == ARM::BI__builtin_arm_wsr ||
1101 BuiltinID == ARM::BI__builtin_arm_wsrp)
1102 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1103
Tim Northover12670412014-02-19 10:37:05 +00001104 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1105 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001106
Yi Kong4efadfb2014-07-03 16:01:25 +00001107 // For intrinsics which take an immediate value as part of the instruction,
1108 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001109 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001110 switch (BuiltinID) {
1111 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001112 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1113 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001114 case ARM::BI__builtin_arm_vcvtr_f:
1115 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001116 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001117 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001118 case ARM::BI__builtin_arm_isb:
1119 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001120 }
Nate Begemand773fe62010-06-13 04:47:52 +00001121
Nate Begemanf568b072010-08-03 21:32:34 +00001122 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001123 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001124}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001125
Tim Northover573cbee2014-05-24 12:52:07 +00001126bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001127 CallExpr *TheCall) {
1128 llvm::APSInt Result;
1129
Tim Northover573cbee2014-05-24 12:52:07 +00001130 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001131 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1132 BuiltinID == AArch64::BI__builtin_arm_strex ||
1133 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001134 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1135 }
1136
Yi Konga5548432014-08-13 19:18:20 +00001137 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1138 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1139 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1140 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1141 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1142 }
1143
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001144 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1145 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1146 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
1147
1148 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1149 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1150 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1151 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1152 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1153
Tim Northovera2ee4332014-03-29 15:09:45 +00001154 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1155 return true;
1156
Yi Kong19a29ac2014-07-17 10:52:06 +00001157 // For intrinsics which take an immediate value as part of the instruction,
1158 // range check them here.
1159 unsigned i = 0, l = 0, u = 0;
1160 switch (BuiltinID) {
1161 default: return false;
1162 case AArch64::BI__builtin_arm_dmb:
1163 case AArch64::BI__builtin_arm_dsb:
1164 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1165 }
1166
Yi Kong19a29ac2014-07-17 10:52:06 +00001167 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001168}
1169
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001170bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1171 unsigned i = 0, l = 0, u = 0;
1172 switch (BuiltinID) {
1173 default: return false;
1174 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1175 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001176 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1177 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1178 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1179 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1180 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001181 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001182
Richard Sandiford28940af2014-04-16 08:47:51 +00001183 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001184}
1185
Kit Bartone50adcb2015-03-30 19:40:59 +00001186bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1187 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001188 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1189 BuiltinID == PPC::BI__builtin_divdeu ||
1190 BuiltinID == PPC::BI__builtin_bpermd;
1191 bool IsTarget64Bit = Context.getTargetInfo()
1192 .getTypeWidth(Context
1193 .getTargetInfo()
1194 .getIntPtrType()) == 64;
1195 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1196 BuiltinID == PPC::BI__builtin_divweu ||
1197 BuiltinID == PPC::BI__builtin_divde ||
1198 BuiltinID == PPC::BI__builtin_divdeu;
1199
1200 if (Is64BitBltin && !IsTarget64Bit)
1201 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1202 << TheCall->getSourceRange();
1203
1204 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1205 (BuiltinID == PPC::BI__builtin_bpermd &&
1206 !Context.getTargetInfo().hasFeature("bpermd")))
1207 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1208 << TheCall->getSourceRange();
1209
Kit Bartone50adcb2015-03-30 19:40:59 +00001210 switch (BuiltinID) {
1211 default: return false;
1212 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1213 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1214 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1215 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1216 case PPC::BI__builtin_tbegin:
1217 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1218 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1219 case PPC::BI__builtin_tabortwc:
1220 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1221 case PPC::BI__builtin_tabortwci:
1222 case PPC::BI__builtin_tabortdci:
1223 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1224 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1225 }
1226 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1227}
1228
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001229bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1230 CallExpr *TheCall) {
1231 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1232 Expr *Arg = TheCall->getArg(0);
1233 llvm::APSInt AbortCode(32);
1234 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1235 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1236 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1237 << Arg->getSourceRange();
1238 }
1239
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001240 // For intrinsics which take an immediate value as part of the instruction,
1241 // range check them here.
1242 unsigned i = 0, l = 0, u = 0;
1243 switch (BuiltinID) {
1244 default: return false;
1245 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1246 case SystemZ::BI__builtin_s390_verimb:
1247 case SystemZ::BI__builtin_s390_verimh:
1248 case SystemZ::BI__builtin_s390_verimf:
1249 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1250 case SystemZ::BI__builtin_s390_vfaeb:
1251 case SystemZ::BI__builtin_s390_vfaeh:
1252 case SystemZ::BI__builtin_s390_vfaef:
1253 case SystemZ::BI__builtin_s390_vfaebs:
1254 case SystemZ::BI__builtin_s390_vfaehs:
1255 case SystemZ::BI__builtin_s390_vfaefs:
1256 case SystemZ::BI__builtin_s390_vfaezb:
1257 case SystemZ::BI__builtin_s390_vfaezh:
1258 case SystemZ::BI__builtin_s390_vfaezf:
1259 case SystemZ::BI__builtin_s390_vfaezbs:
1260 case SystemZ::BI__builtin_s390_vfaezhs:
1261 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1262 case SystemZ::BI__builtin_s390_vfidb:
1263 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1264 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1265 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1266 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1267 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1268 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1269 case SystemZ::BI__builtin_s390_vstrcb:
1270 case SystemZ::BI__builtin_s390_vstrch:
1271 case SystemZ::BI__builtin_s390_vstrcf:
1272 case SystemZ::BI__builtin_s390_vstrczb:
1273 case SystemZ::BI__builtin_s390_vstrczh:
1274 case SystemZ::BI__builtin_s390_vstrczf:
1275 case SystemZ::BI__builtin_s390_vstrcbs:
1276 case SystemZ::BI__builtin_s390_vstrchs:
1277 case SystemZ::BI__builtin_s390_vstrcfs:
1278 case SystemZ::BI__builtin_s390_vstrczbs:
1279 case SystemZ::BI__builtin_s390_vstrczhs:
1280 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1281 }
1282 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001283}
1284
Craig Topper5ba2c502015-11-07 08:08:31 +00001285/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1286/// This checks that the target supports __builtin_cpu_supports and
1287/// that the string argument is constant and valid.
1288static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1289 Expr *Arg = TheCall->getArg(0);
1290
1291 // Check if the argument is a string literal.
1292 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1293 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1294 << Arg->getSourceRange();
1295
1296 // Check the contents of the string.
1297 StringRef Feature =
1298 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1299 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1300 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1301 << Arg->getSourceRange();
1302 return false;
1303}
1304
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001305bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001306 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001307 switch (BuiltinID) {
Richard Trieucc3949d2016-02-18 22:34:54 +00001308 default:
1309 return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001310 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001311 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001312 case X86::BI__builtin_ms_va_start:
1313 return SemaBuiltinMSVAStart(TheCall);
Richard Trieucc3949d2016-02-18 22:34:54 +00001314 case X86::BI_mm_prefetch:
1315 i = 1;
1316 l = 0;
1317 u = 3;
1318 break;
1319 case X86::BI__builtin_ia32_sha1rnds4:
1320 i = 2;
1321 l = 0;
1322 u = 3;
1323 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001324 case X86::BI__builtin_ia32_vpermil2pd:
1325 case X86::BI__builtin_ia32_vpermil2pd256:
1326 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001327 case X86::BI__builtin_ia32_vpermil2ps256:
1328 i = 3;
1329 l = 0;
1330 u = 3;
1331 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001332 case X86::BI__builtin_ia32_cmpb128_mask:
1333 case X86::BI__builtin_ia32_cmpw128_mask:
1334 case X86::BI__builtin_ia32_cmpd128_mask:
1335 case X86::BI__builtin_ia32_cmpq128_mask:
1336 case X86::BI__builtin_ia32_cmpb256_mask:
1337 case X86::BI__builtin_ia32_cmpw256_mask:
1338 case X86::BI__builtin_ia32_cmpd256_mask:
1339 case X86::BI__builtin_ia32_cmpq256_mask:
1340 case X86::BI__builtin_ia32_cmpb512_mask:
1341 case X86::BI__builtin_ia32_cmpw512_mask:
1342 case X86::BI__builtin_ia32_cmpd512_mask:
1343 case X86::BI__builtin_ia32_cmpq512_mask:
1344 case X86::BI__builtin_ia32_ucmpb128_mask:
1345 case X86::BI__builtin_ia32_ucmpw128_mask:
1346 case X86::BI__builtin_ia32_ucmpd128_mask:
1347 case X86::BI__builtin_ia32_ucmpq128_mask:
1348 case X86::BI__builtin_ia32_ucmpb256_mask:
1349 case X86::BI__builtin_ia32_ucmpw256_mask:
1350 case X86::BI__builtin_ia32_ucmpd256_mask:
1351 case X86::BI__builtin_ia32_ucmpq256_mask:
1352 case X86::BI__builtin_ia32_ucmpb512_mask:
1353 case X86::BI__builtin_ia32_ucmpw512_mask:
1354 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001355 case X86::BI__builtin_ia32_ucmpq512_mask:
1356 i = 2;
1357 l = 0;
1358 u = 7;
1359 break;
Craig Topper16015252015-01-31 06:31:23 +00001360 case X86::BI__builtin_ia32_roundps:
1361 case X86::BI__builtin_ia32_roundpd:
1362 case X86::BI__builtin_ia32_roundps256:
Richard Trieucc3949d2016-02-18 22:34:54 +00001363 case X86::BI__builtin_ia32_roundpd256:
1364 i = 1;
1365 l = 0;
1366 u = 15;
1367 break;
Craig Topper16015252015-01-31 06:31:23 +00001368 case X86::BI__builtin_ia32_roundss:
Richard Trieucc3949d2016-02-18 22:34:54 +00001369 case X86::BI__builtin_ia32_roundsd:
1370 i = 2;
1371 l = 0;
1372 u = 15;
1373 break;
Craig Topper16015252015-01-31 06:31:23 +00001374 case X86::BI__builtin_ia32_cmpps:
1375 case X86::BI__builtin_ia32_cmpss:
1376 case X86::BI__builtin_ia32_cmppd:
1377 case X86::BI__builtin_ia32_cmpsd:
1378 case X86::BI__builtin_ia32_cmpps256:
1379 case X86::BI__builtin_ia32_cmppd256:
1380 case X86::BI__builtin_ia32_cmpps512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001381 case X86::BI__builtin_ia32_cmppd512_mask:
1382 i = 2;
1383 l = 0;
1384 u = 31;
1385 break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001386 case X86::BI__builtin_ia32_vpcomub:
1387 case X86::BI__builtin_ia32_vpcomuw:
1388 case X86::BI__builtin_ia32_vpcomud:
1389 case X86::BI__builtin_ia32_vpcomuq:
1390 case X86::BI__builtin_ia32_vpcomb:
1391 case X86::BI__builtin_ia32_vpcomw:
1392 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001393 case X86::BI__builtin_ia32_vpcomq:
1394 i = 2;
1395 l = 0;
1396 u = 7;
1397 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001398 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001399 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001400}
1401
Richard Smith55ce3522012-06-25 20:30:08 +00001402/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1403/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1404/// Returns true when the format fits the function and the FormatStringInfo has
1405/// been populated.
1406bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1407 FormatStringInfo *FSI) {
1408 FSI->HasVAListArg = Format->getFirstArg() == 0;
1409 FSI->FormatIdx = Format->getFormatIdx() - 1;
1410 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001411
Richard Smith55ce3522012-06-25 20:30:08 +00001412 // The way the format attribute works in GCC, the implicit this argument
1413 // of member functions is counted. However, it doesn't appear in our own
1414 // lists, so decrement format_idx in that case.
1415 if (IsCXXMember) {
1416 if(FSI->FormatIdx == 0)
1417 return false;
1418 --FSI->FormatIdx;
1419 if (FSI->FirstDataArg != 0)
1420 --FSI->FirstDataArg;
1421 }
1422 return true;
1423}
Mike Stump11289f42009-09-09 15:08:12 +00001424
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001425/// Checks if a the given expression evaluates to null.
1426///
1427/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001428static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001429 // If the expression has non-null type, it doesn't evaluate to null.
1430 if (auto nullability
1431 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1432 if (*nullability == NullabilityKind::NonNull)
1433 return false;
1434 }
1435
Ted Kremeneka146db32014-01-17 06:24:47 +00001436 // As a special case, transparent unions initialized with zero are
1437 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001438 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001439 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1440 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001441 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001442 if (const InitListExpr *ILE =
1443 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001444 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001445 }
1446
1447 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001448 return (!Expr->isValueDependent() &&
1449 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1450 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001451}
1452
1453static void CheckNonNullArgument(Sema &S,
1454 const Expr *ArgExpr,
1455 SourceLocation CallSiteLoc) {
1456 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001457 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1458 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001459}
1460
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001461bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1462 FormatStringInfo FSI;
1463 if ((GetFormatStringType(Format) == FST_NSString) &&
1464 getFormatStringInfo(Format, false, &FSI)) {
1465 Idx = FSI.FormatIdx;
1466 return true;
1467 }
1468 return false;
1469}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001470/// \brief Diagnose use of %s directive in an NSString which is being passed
1471/// as formatting string to formatting method.
1472static void
1473DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1474 const NamedDecl *FDecl,
1475 Expr **Args,
1476 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001477 unsigned Idx = 0;
1478 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001479 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1480 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001481 Idx = 2;
1482 Format = true;
1483 }
1484 else
1485 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1486 if (S.GetFormatNSStringIdx(I, Idx)) {
1487 Format = true;
1488 break;
1489 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001490 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001491 if (!Format || NumArgs <= Idx)
1492 return;
1493 const Expr *FormatExpr = Args[Idx];
1494 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1495 FormatExpr = CSCE->getSubExpr();
1496 const StringLiteral *FormatString;
1497 if (const ObjCStringLiteral *OSL =
1498 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1499 FormatString = OSL->getString();
1500 else
1501 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1502 if (!FormatString)
1503 return;
1504 if (S.FormatStringHasSArg(FormatString)) {
1505 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1506 << "%s" << 1 << 1;
1507 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1508 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001509 }
1510}
1511
Douglas Gregorb4866e82015-06-19 18:13:19 +00001512/// Determine whether the given type has a non-null nullability annotation.
1513static bool isNonNullType(ASTContext &ctx, QualType type) {
1514 if (auto nullability = type->getNullability(ctx))
1515 return *nullability == NullabilityKind::NonNull;
1516
1517 return false;
1518}
1519
Ted Kremenek2bc73332014-01-17 06:24:43 +00001520static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001521 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001522 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001523 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001524 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001525 assert((FDecl || Proto) && "Need a function declaration or prototype");
1526
Ted Kremenek9aedc152014-01-17 06:24:56 +00001527 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001528 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001529 if (FDecl) {
1530 // Handle the nonnull attribute on the function/method declaration itself.
1531 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1532 if (!NonNull->args_size()) {
1533 // Easy case: all pointer arguments are nonnull.
1534 for (const auto *Arg : Args)
1535 if (S.isValidPointerAttrType(Arg->getType()))
1536 CheckNonNullArgument(S, Arg, CallSiteLoc);
1537 return;
1538 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001539
Douglas Gregorb4866e82015-06-19 18:13:19 +00001540 for (unsigned Val : NonNull->args()) {
1541 if (Val >= Args.size())
1542 continue;
1543 if (NonNullArgs.empty())
1544 NonNullArgs.resize(Args.size());
1545 NonNullArgs.set(Val);
1546 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001547 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001548 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001549
Douglas Gregorb4866e82015-06-19 18:13:19 +00001550 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1551 // Handle the nonnull attribute on the parameters of the
1552 // function/method.
1553 ArrayRef<ParmVarDecl*> parms;
1554 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1555 parms = FD->parameters();
1556 else
1557 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1558
1559 unsigned ParamIndex = 0;
1560 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1561 I != E; ++I, ++ParamIndex) {
1562 const ParmVarDecl *PVD = *I;
1563 if (PVD->hasAttr<NonNullAttr>() ||
1564 isNonNullType(S.Context, PVD->getType())) {
1565 if (NonNullArgs.empty())
1566 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001567
Douglas Gregorb4866e82015-06-19 18:13:19 +00001568 NonNullArgs.set(ParamIndex);
1569 }
1570 }
1571 } else {
1572 // If we have a non-function, non-method declaration but no
1573 // function prototype, try to dig out the function prototype.
1574 if (!Proto) {
1575 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1576 QualType type = VD->getType().getNonReferenceType();
1577 if (auto pointerType = type->getAs<PointerType>())
1578 type = pointerType->getPointeeType();
1579 else if (auto blockType = type->getAs<BlockPointerType>())
1580 type = blockType->getPointeeType();
1581 // FIXME: data member pointers?
1582
1583 // Dig out the function prototype, if there is one.
1584 Proto = type->getAs<FunctionProtoType>();
1585 }
1586 }
1587
1588 // Fill in non-null argument information from the nullability
1589 // information on the parameter types (if we have them).
1590 if (Proto) {
1591 unsigned Index = 0;
1592 for (auto paramType : Proto->getParamTypes()) {
1593 if (isNonNullType(S.Context, paramType)) {
1594 if (NonNullArgs.empty())
1595 NonNullArgs.resize(Args.size());
1596
1597 NonNullArgs.set(Index);
1598 }
1599
1600 ++Index;
1601 }
1602 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001603 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001604
Douglas Gregorb4866e82015-06-19 18:13:19 +00001605 // Check for non-null arguments.
1606 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1607 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001608 if (NonNullArgs[ArgIndex])
1609 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001610 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001611}
1612
Richard Smith55ce3522012-06-25 20:30:08 +00001613/// Handles the checks for format strings, non-POD arguments to vararg
1614/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001615void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1616 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001617 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001618 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001619 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001620 if (CurContext->isDependentContext())
1621 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001622
Ted Kremenekb8176da2010-09-09 04:33:05 +00001623 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001624 llvm::SmallBitVector CheckedVarArgs;
1625 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001626 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001627 // Only create vector if there are format attributes.
1628 CheckedVarArgs.resize(Args.size());
1629
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001630 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001631 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001632 }
Richard Smithd7293d72013-08-05 18:49:43 +00001633 }
Richard Smith55ce3522012-06-25 20:30:08 +00001634
1635 // Refuse POD arguments that weren't caught by the format string
1636 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001637 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001638 unsigned NumParams = Proto ? Proto->getNumParams()
1639 : FDecl && isa<FunctionDecl>(FDecl)
1640 ? cast<FunctionDecl>(FDecl)->getNumParams()
1641 : FDecl && isa<ObjCMethodDecl>(FDecl)
1642 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1643 : 0;
1644
Alp Toker9cacbab2014-01-20 20:26:09 +00001645 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001646 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001647 if (const Expr *Arg = Args[ArgIdx]) {
1648 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1649 checkVariadicArgument(Arg, CallType);
1650 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001651 }
Richard Smithd7293d72013-08-05 18:49:43 +00001652 }
Mike Stump11289f42009-09-09 15:08:12 +00001653
Douglas Gregorb4866e82015-06-19 18:13:19 +00001654 if (FDecl || Proto) {
1655 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001656
Richard Trieu41bc0992013-06-22 00:20:41 +00001657 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001658 if (FDecl) {
1659 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1660 CheckArgumentWithTypeTag(I, Args.data());
1661 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001662 }
Richard Smith55ce3522012-06-25 20:30:08 +00001663}
1664
1665/// CheckConstructorCall - Check a constructor call for correctness and safety
1666/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001667void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1668 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001669 const FunctionProtoType *Proto,
1670 SourceLocation Loc) {
1671 VariadicCallType CallType =
1672 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001673 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1674 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001675}
1676
1677/// CheckFunctionCall - Check a direct function call for various correctness
1678/// and safety properties not strictly enforced by the C type system.
1679bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1680 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001681 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1682 isa<CXXMethodDecl>(FDecl);
1683 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1684 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001685 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1686 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001687 Expr** Args = TheCall->getArgs();
1688 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001689 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001690 // If this is a call to a member operator, hide the first argument
1691 // from checkCall.
1692 // FIXME: Our choice of AST representation here is less than ideal.
1693 ++Args;
1694 --NumArgs;
1695 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001696 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001697 IsMemberFunction, TheCall->getRParenLoc(),
1698 TheCall->getCallee()->getSourceRange(), CallType);
1699
1700 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1701 // None of the checks below are needed for functions that don't have
1702 // simple names (e.g., C++ conversion functions).
1703 if (!FnInfo)
1704 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001705
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001706 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001707 if (getLangOpts().ObjC1)
1708 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001709
Anna Zaks22122702012-01-17 00:37:07 +00001710 unsigned CMId = FDecl->getMemoryFunctionKind();
1711 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001712 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001713
Anna Zaks201d4892012-01-13 21:52:01 +00001714 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001715 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001716 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001717 else if (CMId == Builtin::BIstrncat)
1718 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001719 else
Anna Zaks22122702012-01-17 00:37:07 +00001720 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001721
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001722 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001723}
1724
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001725bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001726 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001727 VariadicCallType CallType =
1728 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001729
Douglas Gregorb4866e82015-06-19 18:13:19 +00001730 checkCall(Method, nullptr, Args,
1731 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1732 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001733
1734 return false;
1735}
1736
Richard Trieu664c4c62013-06-20 21:03:13 +00001737bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1738 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001739 QualType Ty;
1740 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001741 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001742 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001743 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001744 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001745 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001746
Douglas Gregorb4866e82015-06-19 18:13:19 +00001747 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1748 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001749 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001750
Richard Trieu664c4c62013-06-20 21:03:13 +00001751 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001752 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001753 CallType = VariadicDoesNotApply;
1754 } else if (Ty->isBlockPointerType()) {
1755 CallType = VariadicBlock;
1756 } else { // Ty->isFunctionPointerType()
1757 CallType = VariadicFunction;
1758 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001759
Douglas Gregorb4866e82015-06-19 18:13:19 +00001760 checkCall(NDecl, Proto,
1761 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1762 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001763 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001764
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001765 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001766}
1767
Richard Trieu41bc0992013-06-22 00:20:41 +00001768/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1769/// such as function pointers returned from functions.
1770bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001771 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001772 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001773 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001774 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001775 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001776 TheCall->getCallee()->getSourceRange(), CallType);
1777
1778 return false;
1779}
1780
Tim Northovere94a34c2014-03-11 10:49:14 +00001781static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1782 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1783 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1784 return false;
1785
1786 switch (Op) {
1787 case AtomicExpr::AO__c11_atomic_init:
1788 llvm_unreachable("There is no ordering argument for an init");
1789
1790 case AtomicExpr::AO__c11_atomic_load:
1791 case AtomicExpr::AO__atomic_load_n:
1792 case AtomicExpr::AO__atomic_load:
1793 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1794 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1795
1796 case AtomicExpr::AO__c11_atomic_store:
1797 case AtomicExpr::AO__atomic_store:
1798 case AtomicExpr::AO__atomic_store_n:
1799 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1800 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1801 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1802
1803 default:
1804 return true;
1805 }
1806}
1807
Richard Smithfeea8832012-04-12 05:08:17 +00001808ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1809 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001810 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1811 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001812
Richard Smithfeea8832012-04-12 05:08:17 +00001813 // All these operations take one of the following forms:
1814 enum {
1815 // C __c11_atomic_init(A *, C)
1816 Init,
1817 // C __c11_atomic_load(A *, int)
1818 Load,
1819 // void __atomic_load(A *, CP, int)
1820 Copy,
1821 // C __c11_atomic_add(A *, M, int)
1822 Arithmetic,
1823 // C __atomic_exchange_n(A *, CP, int)
1824 Xchg,
1825 // void __atomic_exchange(A *, C *, CP, int)
1826 GNUXchg,
1827 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1828 C11CmpXchg,
1829 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1830 GNUCmpXchg
1831 } Form = Init;
1832 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1833 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1834 // where:
1835 // C is an appropriate type,
1836 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1837 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1838 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1839 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001840
Gabor Horvath98bd0982015-03-16 09:59:54 +00001841 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1842 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1843 AtomicExpr::AO__atomic_load,
1844 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001845 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1846 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1847 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1848 Op == AtomicExpr::AO__atomic_store_n ||
1849 Op == AtomicExpr::AO__atomic_exchange_n ||
1850 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1851 bool IsAddSub = false;
1852
1853 switch (Op) {
1854 case AtomicExpr::AO__c11_atomic_init:
1855 Form = Init;
1856 break;
1857
1858 case AtomicExpr::AO__c11_atomic_load:
1859 case AtomicExpr::AO__atomic_load_n:
1860 Form = Load;
1861 break;
1862
1863 case AtomicExpr::AO__c11_atomic_store:
1864 case AtomicExpr::AO__atomic_load:
1865 case AtomicExpr::AO__atomic_store:
1866 case AtomicExpr::AO__atomic_store_n:
1867 Form = Copy;
1868 break;
1869
1870 case AtomicExpr::AO__c11_atomic_fetch_add:
1871 case AtomicExpr::AO__c11_atomic_fetch_sub:
1872 case AtomicExpr::AO__atomic_fetch_add:
1873 case AtomicExpr::AO__atomic_fetch_sub:
1874 case AtomicExpr::AO__atomic_add_fetch:
1875 case AtomicExpr::AO__atomic_sub_fetch:
1876 IsAddSub = true;
1877 // Fall through.
1878 case AtomicExpr::AO__c11_atomic_fetch_and:
1879 case AtomicExpr::AO__c11_atomic_fetch_or:
1880 case AtomicExpr::AO__c11_atomic_fetch_xor:
1881 case AtomicExpr::AO__atomic_fetch_and:
1882 case AtomicExpr::AO__atomic_fetch_or:
1883 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001884 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001885 case AtomicExpr::AO__atomic_and_fetch:
1886 case AtomicExpr::AO__atomic_or_fetch:
1887 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001888 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001889 Form = Arithmetic;
1890 break;
1891
1892 case AtomicExpr::AO__c11_atomic_exchange:
1893 case AtomicExpr::AO__atomic_exchange_n:
1894 Form = Xchg;
1895 break;
1896
1897 case AtomicExpr::AO__atomic_exchange:
1898 Form = GNUXchg;
1899 break;
1900
1901 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1902 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1903 Form = C11CmpXchg;
1904 break;
1905
1906 case AtomicExpr::AO__atomic_compare_exchange:
1907 case AtomicExpr::AO__atomic_compare_exchange_n:
1908 Form = GNUCmpXchg;
1909 break;
1910 }
1911
1912 // Check we have the right number of arguments.
1913 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001914 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001915 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001916 << TheCall->getCallee()->getSourceRange();
1917 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001918 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1919 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001920 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001921 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001922 << TheCall->getCallee()->getSourceRange();
1923 return ExprError();
1924 }
1925
Richard Smithfeea8832012-04-12 05:08:17 +00001926 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001927 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001928 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1929 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1930 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001931 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001932 << Ptr->getType() << Ptr->getSourceRange();
1933 return ExprError();
1934 }
1935
Richard Smithfeea8832012-04-12 05:08:17 +00001936 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1937 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1938 QualType ValType = AtomTy; // 'C'
1939 if (IsC11) {
1940 if (!AtomTy->isAtomicType()) {
1941 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1942 << Ptr->getType() << Ptr->getSourceRange();
1943 return ExprError();
1944 }
Richard Smithe00921a2012-09-15 06:09:58 +00001945 if (AtomTy.isConstQualified()) {
1946 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1947 << Ptr->getType() << Ptr->getSourceRange();
1948 return ExprError();
1949 }
Richard Smithfeea8832012-04-12 05:08:17 +00001950 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001951 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1952 if (ValType.isConstQualified()) {
1953 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1954 << Ptr->getType() << Ptr->getSourceRange();
1955 return ExprError();
1956 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001957 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001958
Richard Smithfeea8832012-04-12 05:08:17 +00001959 // For an arithmetic operation, the implied arithmetic must be well-formed.
1960 if (Form == Arithmetic) {
1961 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1962 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1963 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1964 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1965 return ExprError();
1966 }
1967 if (!IsAddSub && !ValType->isIntegerType()) {
1968 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1969 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1970 return ExprError();
1971 }
David Majnemere85cff82015-01-28 05:48:06 +00001972 if (IsC11 && ValType->isPointerType() &&
1973 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1974 diag::err_incomplete_type)) {
1975 return ExprError();
1976 }
Richard Smithfeea8832012-04-12 05:08:17 +00001977 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1978 // For __atomic_*_n operations, the value type must be a scalar integral or
1979 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001980 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001981 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1982 return ExprError();
1983 }
1984
Eli Friedmanaa769812013-09-11 03:49:34 +00001985 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1986 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001987 // For GNU atomics, require a trivially-copyable type. This is not part of
1988 // the GNU atomics specification, but we enforce it for sanity.
1989 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001990 << Ptr->getType() << Ptr->getSourceRange();
1991 return ExprError();
1992 }
1993
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001994 switch (ValType.getObjCLifetime()) {
1995 case Qualifiers::OCL_None:
1996 case Qualifiers::OCL_ExplicitNone:
1997 // okay
1998 break;
1999
2000 case Qualifiers::OCL_Weak:
2001 case Qualifiers::OCL_Strong:
2002 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002003 // FIXME: Can this happen? By this point, ValType should be known
2004 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002005 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2006 << ValType << Ptr->getSourceRange();
2007 return ExprError();
2008 }
2009
David Majnemerc6eb6502015-06-03 00:26:35 +00002010 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2011 // volatile-ness of the pointee-type inject itself into the result or the
2012 // other operands.
2013 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002014 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00002015 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002016 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002017 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002018 ResultType = Context.BoolTy;
2019
Richard Smithfeea8832012-04-12 05:08:17 +00002020 // The type of a parameter passed 'by value'. In the GNU atomics, such
2021 // arguments are actually passed as pointers.
2022 QualType ByValType = ValType; // 'CP'
2023 if (!IsC11 && !IsN)
2024 ByValType = Ptr->getType();
2025
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002026 // FIXME: __atomic_load allows the first argument to be a a pointer to const
2027 // but not the second argument. We need to manually remove possible const
2028 // qualifiers.
2029
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002030 // The first argument --- the pointer --- has a fixed type; we
2031 // deduce the types of the rest of the arguments accordingly. Walk
2032 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002033 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002034 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002035 if (i < NumVals[Form] + 1) {
2036 switch (i) {
2037 case 1:
2038 // The second argument is the non-atomic operand. For arithmetic, this
2039 // is always passed by value, and for a compare_exchange it is always
2040 // passed by address. For the rest, GNU uses by-address and C11 uses
2041 // by-value.
2042 assert(Form != Load);
2043 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2044 Ty = ValType;
2045 else if (Form == Copy || Form == Xchg)
2046 Ty = ByValType;
2047 else if (Form == Arithmetic)
2048 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002049 else {
2050 Expr *ValArg = TheCall->getArg(i);
2051 unsigned AS = 0;
2052 // Keep address space of non-atomic pointer type.
2053 if (const PointerType *PtrTy =
2054 ValArg->getType()->getAs<PointerType>()) {
2055 AS = PtrTy->getPointeeType().getAddressSpace();
2056 }
2057 Ty = Context.getPointerType(
2058 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2059 }
Richard Smithfeea8832012-04-12 05:08:17 +00002060 break;
2061 case 2:
2062 // The third argument to compare_exchange / GNU exchange is a
2063 // (pointer to a) desired value.
2064 Ty = ByValType;
2065 break;
2066 case 3:
2067 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2068 Ty = Context.BoolTy;
2069 break;
2070 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002071 } else {
2072 // The order(s) are always converted to int.
2073 Ty = Context.IntTy;
2074 }
Richard Smithfeea8832012-04-12 05:08:17 +00002075
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002076 InitializedEntity Entity =
2077 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002078 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002079 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2080 if (Arg.isInvalid())
2081 return true;
2082 TheCall->setArg(i, Arg.get());
2083 }
2084
Richard Smithfeea8832012-04-12 05:08:17 +00002085 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002086 SmallVector<Expr*, 5> SubExprs;
2087 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002088 switch (Form) {
2089 case Init:
2090 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002091 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002092 break;
2093 case Load:
2094 SubExprs.push_back(TheCall->getArg(1)); // Order
2095 break;
2096 case Copy:
2097 case Arithmetic:
2098 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002099 SubExprs.push_back(TheCall->getArg(2)); // Order
2100 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002101 break;
2102 case GNUXchg:
2103 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2104 SubExprs.push_back(TheCall->getArg(3)); // Order
2105 SubExprs.push_back(TheCall->getArg(1)); // Val1
2106 SubExprs.push_back(TheCall->getArg(2)); // Val2
2107 break;
2108 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002109 SubExprs.push_back(TheCall->getArg(3)); // Order
2110 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002111 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002112 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002113 break;
2114 case GNUCmpXchg:
2115 SubExprs.push_back(TheCall->getArg(4)); // Order
2116 SubExprs.push_back(TheCall->getArg(1)); // Val1
2117 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2118 SubExprs.push_back(TheCall->getArg(2)); // Val2
2119 SubExprs.push_back(TheCall->getArg(3)); // Weak
2120 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002121 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002122
2123 if (SubExprs.size() >= 2 && Form != Init) {
2124 llvm::APSInt Result(32);
2125 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2126 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002127 Diag(SubExprs[1]->getLocStart(),
2128 diag::warn_atomic_op_has_invalid_memory_order)
2129 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002130 }
2131
Fariborz Jahanian615de762013-05-28 17:37:39 +00002132 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2133 SubExprs, ResultType, Op,
2134 TheCall->getRParenLoc());
2135
2136 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2137 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2138 Context.AtomicUsesUnsupportedLibcall(AE))
2139 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2140 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002141
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002142 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002143}
2144
John McCall29ad95b2011-08-27 01:09:30 +00002145/// checkBuiltinArgument - Given a call to a builtin function, perform
2146/// normal type-checking on the given argument, updating the call in
2147/// place. This is useful when a builtin function requires custom
2148/// type-checking for some of its arguments but not necessarily all of
2149/// them.
2150///
2151/// Returns true on error.
2152static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2153 FunctionDecl *Fn = E->getDirectCallee();
2154 assert(Fn && "builtin call without direct callee!");
2155
2156 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2157 InitializedEntity Entity =
2158 InitializedEntity::InitializeParameter(S.Context, Param);
2159
2160 ExprResult Arg = E->getArg(0);
2161 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2162 if (Arg.isInvalid())
2163 return true;
2164
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002165 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002166 return false;
2167}
2168
Chris Lattnerdc046542009-05-08 06:58:22 +00002169/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2170/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2171/// type of its first argument. The main ActOnCallExpr routines have already
2172/// promoted the types of arguments because all of these calls are prototyped as
2173/// void(...).
2174///
2175/// This function goes through and does final semantic checking for these
2176/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002177ExprResult
2178Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002179 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002180 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2181 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2182
2183 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002184 if (TheCall->getNumArgs() < 1) {
2185 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2186 << 0 << 1 << TheCall->getNumArgs()
2187 << TheCall->getCallee()->getSourceRange();
2188 return ExprError();
2189 }
Mike Stump11289f42009-09-09 15:08:12 +00002190
Chris Lattnerdc046542009-05-08 06:58:22 +00002191 // Inspect the first argument of the atomic builtin. This should always be
2192 // a pointer type, whose element is an integral scalar or pointer type.
2193 // Because it is a pointer type, we don't have to worry about any implicit
2194 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002195 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002196 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002197 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2198 if (FirstArgResult.isInvalid())
2199 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002200 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002201 TheCall->setArg(0, FirstArg);
2202
John McCall31168b02011-06-15 23:02:42 +00002203 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2204 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002205 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2206 << FirstArg->getType() << FirstArg->getSourceRange();
2207 return ExprError();
2208 }
Mike Stump11289f42009-09-09 15:08:12 +00002209
John McCall31168b02011-06-15 23:02:42 +00002210 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002211 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002212 !ValType->isBlockPointerType()) {
2213 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2214 << FirstArg->getType() << FirstArg->getSourceRange();
2215 return ExprError();
2216 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002217
John McCall31168b02011-06-15 23:02:42 +00002218 switch (ValType.getObjCLifetime()) {
2219 case Qualifiers::OCL_None:
2220 case Qualifiers::OCL_ExplicitNone:
2221 // okay
2222 break;
2223
2224 case Qualifiers::OCL_Weak:
2225 case Qualifiers::OCL_Strong:
2226 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002227 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002228 << ValType << FirstArg->getSourceRange();
2229 return ExprError();
2230 }
2231
John McCallb50451a2011-10-05 07:41:44 +00002232 // Strip any qualifiers off ValType.
2233 ValType = ValType.getUnqualifiedType();
2234
Chandler Carruth3973af72010-07-18 20:54:12 +00002235 // The majority of builtins return a value, but a few have special return
2236 // types, so allow them to override appropriately below.
2237 QualType ResultType = ValType;
2238
Chris Lattnerdc046542009-05-08 06:58:22 +00002239 // We need to figure out which concrete builtin this maps onto. For example,
2240 // __sync_fetch_and_add with a 2 byte object turns into
2241 // __sync_fetch_and_add_2.
2242#define BUILTIN_ROW(x) \
2243 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2244 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002245
Chris Lattnerdc046542009-05-08 06:58:22 +00002246 static const unsigned BuiltinIndices[][5] = {
2247 BUILTIN_ROW(__sync_fetch_and_add),
2248 BUILTIN_ROW(__sync_fetch_and_sub),
2249 BUILTIN_ROW(__sync_fetch_and_or),
2250 BUILTIN_ROW(__sync_fetch_and_and),
2251 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002252 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002253
Chris Lattnerdc046542009-05-08 06:58:22 +00002254 BUILTIN_ROW(__sync_add_and_fetch),
2255 BUILTIN_ROW(__sync_sub_and_fetch),
2256 BUILTIN_ROW(__sync_and_and_fetch),
2257 BUILTIN_ROW(__sync_or_and_fetch),
2258 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002259 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002260
Chris Lattnerdc046542009-05-08 06:58:22 +00002261 BUILTIN_ROW(__sync_val_compare_and_swap),
2262 BUILTIN_ROW(__sync_bool_compare_and_swap),
2263 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002264 BUILTIN_ROW(__sync_lock_release),
2265 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002266 };
Mike Stump11289f42009-09-09 15:08:12 +00002267#undef BUILTIN_ROW
2268
Chris Lattnerdc046542009-05-08 06:58:22 +00002269 // Determine the index of the size.
2270 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002271 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002272 case 1: SizeIndex = 0; break;
2273 case 2: SizeIndex = 1; break;
2274 case 4: SizeIndex = 2; break;
2275 case 8: SizeIndex = 3; break;
2276 case 16: SizeIndex = 4; break;
2277 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002278 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2279 << FirstArg->getType() << FirstArg->getSourceRange();
2280 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002281 }
Mike Stump11289f42009-09-09 15:08:12 +00002282
Chris Lattnerdc046542009-05-08 06:58:22 +00002283 // Each of these builtins has one pointer argument, followed by some number of
2284 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2285 // that we ignore. Find out which row of BuiltinIndices to read from as well
2286 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002287 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002288 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002289 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002290 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002291 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002292 case Builtin::BI__sync_fetch_and_add:
2293 case Builtin::BI__sync_fetch_and_add_1:
2294 case Builtin::BI__sync_fetch_and_add_2:
2295 case Builtin::BI__sync_fetch_and_add_4:
2296 case Builtin::BI__sync_fetch_and_add_8:
2297 case Builtin::BI__sync_fetch_and_add_16:
2298 BuiltinIndex = 0;
2299 break;
2300
2301 case Builtin::BI__sync_fetch_and_sub:
2302 case Builtin::BI__sync_fetch_and_sub_1:
2303 case Builtin::BI__sync_fetch_and_sub_2:
2304 case Builtin::BI__sync_fetch_and_sub_4:
2305 case Builtin::BI__sync_fetch_and_sub_8:
2306 case Builtin::BI__sync_fetch_and_sub_16:
2307 BuiltinIndex = 1;
2308 break;
2309
2310 case Builtin::BI__sync_fetch_and_or:
2311 case Builtin::BI__sync_fetch_and_or_1:
2312 case Builtin::BI__sync_fetch_and_or_2:
2313 case Builtin::BI__sync_fetch_and_or_4:
2314 case Builtin::BI__sync_fetch_and_or_8:
2315 case Builtin::BI__sync_fetch_and_or_16:
2316 BuiltinIndex = 2;
2317 break;
2318
2319 case Builtin::BI__sync_fetch_and_and:
2320 case Builtin::BI__sync_fetch_and_and_1:
2321 case Builtin::BI__sync_fetch_and_and_2:
2322 case Builtin::BI__sync_fetch_and_and_4:
2323 case Builtin::BI__sync_fetch_and_and_8:
2324 case Builtin::BI__sync_fetch_and_and_16:
2325 BuiltinIndex = 3;
2326 break;
Mike Stump11289f42009-09-09 15:08:12 +00002327
Douglas Gregor73722482011-11-28 16:30:08 +00002328 case Builtin::BI__sync_fetch_and_xor:
2329 case Builtin::BI__sync_fetch_and_xor_1:
2330 case Builtin::BI__sync_fetch_and_xor_2:
2331 case Builtin::BI__sync_fetch_and_xor_4:
2332 case Builtin::BI__sync_fetch_and_xor_8:
2333 case Builtin::BI__sync_fetch_and_xor_16:
2334 BuiltinIndex = 4;
2335 break;
2336
Hal Finkeld2208b52014-10-02 20:53:50 +00002337 case Builtin::BI__sync_fetch_and_nand:
2338 case Builtin::BI__sync_fetch_and_nand_1:
2339 case Builtin::BI__sync_fetch_and_nand_2:
2340 case Builtin::BI__sync_fetch_and_nand_4:
2341 case Builtin::BI__sync_fetch_and_nand_8:
2342 case Builtin::BI__sync_fetch_and_nand_16:
2343 BuiltinIndex = 5;
2344 WarnAboutSemanticsChange = true;
2345 break;
2346
Douglas Gregor73722482011-11-28 16:30:08 +00002347 case Builtin::BI__sync_add_and_fetch:
2348 case Builtin::BI__sync_add_and_fetch_1:
2349 case Builtin::BI__sync_add_and_fetch_2:
2350 case Builtin::BI__sync_add_and_fetch_4:
2351 case Builtin::BI__sync_add_and_fetch_8:
2352 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002353 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002354 break;
2355
2356 case Builtin::BI__sync_sub_and_fetch:
2357 case Builtin::BI__sync_sub_and_fetch_1:
2358 case Builtin::BI__sync_sub_and_fetch_2:
2359 case Builtin::BI__sync_sub_and_fetch_4:
2360 case Builtin::BI__sync_sub_and_fetch_8:
2361 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002362 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002363 break;
2364
2365 case Builtin::BI__sync_and_and_fetch:
2366 case Builtin::BI__sync_and_and_fetch_1:
2367 case Builtin::BI__sync_and_and_fetch_2:
2368 case Builtin::BI__sync_and_and_fetch_4:
2369 case Builtin::BI__sync_and_and_fetch_8:
2370 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002371 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002372 break;
2373
2374 case Builtin::BI__sync_or_and_fetch:
2375 case Builtin::BI__sync_or_and_fetch_1:
2376 case Builtin::BI__sync_or_and_fetch_2:
2377 case Builtin::BI__sync_or_and_fetch_4:
2378 case Builtin::BI__sync_or_and_fetch_8:
2379 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002380 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002381 break;
2382
2383 case Builtin::BI__sync_xor_and_fetch:
2384 case Builtin::BI__sync_xor_and_fetch_1:
2385 case Builtin::BI__sync_xor_and_fetch_2:
2386 case Builtin::BI__sync_xor_and_fetch_4:
2387 case Builtin::BI__sync_xor_and_fetch_8:
2388 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002389 BuiltinIndex = 10;
2390 break;
2391
2392 case Builtin::BI__sync_nand_and_fetch:
2393 case Builtin::BI__sync_nand_and_fetch_1:
2394 case Builtin::BI__sync_nand_and_fetch_2:
2395 case Builtin::BI__sync_nand_and_fetch_4:
2396 case Builtin::BI__sync_nand_and_fetch_8:
2397 case Builtin::BI__sync_nand_and_fetch_16:
2398 BuiltinIndex = 11;
2399 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002400 break;
Mike Stump11289f42009-09-09 15:08:12 +00002401
Chris Lattnerdc046542009-05-08 06:58:22 +00002402 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002403 case Builtin::BI__sync_val_compare_and_swap_1:
2404 case Builtin::BI__sync_val_compare_and_swap_2:
2405 case Builtin::BI__sync_val_compare_and_swap_4:
2406 case Builtin::BI__sync_val_compare_and_swap_8:
2407 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002408 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002409 NumFixed = 2;
2410 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002411
Chris Lattnerdc046542009-05-08 06:58:22 +00002412 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002413 case Builtin::BI__sync_bool_compare_and_swap_1:
2414 case Builtin::BI__sync_bool_compare_and_swap_2:
2415 case Builtin::BI__sync_bool_compare_and_swap_4:
2416 case Builtin::BI__sync_bool_compare_and_swap_8:
2417 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002418 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002419 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002420 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002421 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002422
2423 case Builtin::BI__sync_lock_test_and_set:
2424 case Builtin::BI__sync_lock_test_and_set_1:
2425 case Builtin::BI__sync_lock_test_and_set_2:
2426 case Builtin::BI__sync_lock_test_and_set_4:
2427 case Builtin::BI__sync_lock_test_and_set_8:
2428 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002429 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002430 break;
2431
Chris Lattnerdc046542009-05-08 06:58:22 +00002432 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002433 case Builtin::BI__sync_lock_release_1:
2434 case Builtin::BI__sync_lock_release_2:
2435 case Builtin::BI__sync_lock_release_4:
2436 case Builtin::BI__sync_lock_release_8:
2437 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002438 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002439 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002440 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002441 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002442
2443 case Builtin::BI__sync_swap:
2444 case Builtin::BI__sync_swap_1:
2445 case Builtin::BI__sync_swap_2:
2446 case Builtin::BI__sync_swap_4:
2447 case Builtin::BI__sync_swap_8:
2448 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002449 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002450 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002451 }
Mike Stump11289f42009-09-09 15:08:12 +00002452
Chris Lattnerdc046542009-05-08 06:58:22 +00002453 // Now that we know how many fixed arguments we expect, first check that we
2454 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002455 if (TheCall->getNumArgs() < 1+NumFixed) {
2456 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2457 << 0 << 1+NumFixed << TheCall->getNumArgs()
2458 << TheCall->getCallee()->getSourceRange();
2459 return ExprError();
2460 }
Mike Stump11289f42009-09-09 15:08:12 +00002461
Hal Finkeld2208b52014-10-02 20:53:50 +00002462 if (WarnAboutSemanticsChange) {
2463 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2464 << TheCall->getCallee()->getSourceRange();
2465 }
2466
Chris Lattner5b9241b2009-05-08 15:36:58 +00002467 // Get the decl for the concrete builtin from this, we can tell what the
2468 // concrete integer type we should convert to is.
2469 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002470 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002471 FunctionDecl *NewBuiltinDecl;
2472 if (NewBuiltinID == BuiltinID)
2473 NewBuiltinDecl = FDecl;
2474 else {
2475 // Perform builtin lookup to avoid redeclaring it.
2476 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2477 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2478 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2479 assert(Res.getFoundDecl());
2480 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002481 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002482 return ExprError();
2483 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002484
John McCallcf142162010-08-07 06:22:56 +00002485 // The first argument --- the pointer --- has a fixed type; we
2486 // deduce the types of the rest of the arguments accordingly. Walk
2487 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002488 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002489 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002490
Chris Lattnerdc046542009-05-08 06:58:22 +00002491 // GCC does an implicit conversion to the pointer or integer ValType. This
2492 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002493 // Initialize the argument.
2494 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2495 ValType, /*consume*/ false);
2496 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002497 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002498 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002499
Chris Lattnerdc046542009-05-08 06:58:22 +00002500 // Okay, we have something that *can* be converted to the right type. Check
2501 // to see if there is a potentially weird extension going on here. This can
2502 // happen when you do an atomic operation on something like an char* and
2503 // pass in 42. The 42 gets converted to char. This is even more strange
2504 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002505 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002506 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002507 }
Mike Stump11289f42009-09-09 15:08:12 +00002508
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002509 ASTContext& Context = this->getASTContext();
2510
2511 // Create a new DeclRefExpr to refer to the new decl.
2512 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2513 Context,
2514 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002515 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002516 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002517 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002518 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002519 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002520 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002521
Chris Lattnerdc046542009-05-08 06:58:22 +00002522 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002523 // FIXME: This loses syntactic information.
2524 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2525 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2526 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002527 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002528
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002529 // Change the result type of the call to match the original value type. This
2530 // is arbitrary, but the codegen for these builtins ins design to handle it
2531 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002532 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002533
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002534 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002535}
2536
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002537/// SemaBuiltinNontemporalOverloaded - We have a call to
2538/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2539/// overloaded function based on the pointer type of its last argument.
2540///
2541/// This function goes through and does final semantic checking for these
2542/// builtins.
2543ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2544 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2545 DeclRefExpr *DRE =
2546 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2547 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2548 unsigned BuiltinID = FDecl->getBuiltinID();
2549 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2550 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2551 "Unexpected nontemporal load/store builtin!");
2552 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2553 unsigned numArgs = isStore ? 2 : 1;
2554
2555 // Ensure that we have the proper number of arguments.
2556 if (checkArgCount(*this, TheCall, numArgs))
2557 return ExprError();
2558
2559 // Inspect the last argument of the nontemporal builtin. This should always
2560 // be a pointer type, from which we imply the type of the memory access.
2561 // Because it is a pointer type, we don't have to worry about any implicit
2562 // casts here.
2563 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2564 ExprResult PointerArgResult =
2565 DefaultFunctionArrayLvalueConversion(PointerArg);
2566
2567 if (PointerArgResult.isInvalid())
2568 return ExprError();
2569 PointerArg = PointerArgResult.get();
2570 TheCall->setArg(numArgs - 1, PointerArg);
2571
2572 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2573 if (!pointerType) {
2574 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2575 << PointerArg->getType() << PointerArg->getSourceRange();
2576 return ExprError();
2577 }
2578
2579 QualType ValType = pointerType->getPointeeType();
2580
2581 // Strip any qualifiers off ValType.
2582 ValType = ValType.getUnqualifiedType();
2583 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2584 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2585 !ValType->isVectorType()) {
2586 Diag(DRE->getLocStart(),
2587 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2588 << PointerArg->getType() << PointerArg->getSourceRange();
2589 return ExprError();
2590 }
2591
2592 if (!isStore) {
2593 TheCall->setType(ValType);
2594 return TheCallResult;
2595 }
2596
2597 ExprResult ValArg = TheCall->getArg(0);
2598 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2599 Context, ValType, /*consume*/ false);
2600 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2601 if (ValArg.isInvalid())
2602 return ExprError();
2603
2604 TheCall->setArg(0, ValArg.get());
2605 TheCall->setType(Context.VoidTy);
2606 return TheCallResult;
2607}
2608
Chris Lattner6436fb62009-02-18 06:01:06 +00002609/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002610/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002611/// Note: It might also make sense to do the UTF-16 conversion here (would
2612/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002613bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002614 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002615 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2616
Douglas Gregorfb65e592011-07-27 05:40:30 +00002617 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002618 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2619 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002620 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002621 }
Mike Stump11289f42009-09-09 15:08:12 +00002622
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002623 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002624 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002625 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002626 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002627 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002628 UTF16 *ToPtr = &ToBuf[0];
2629
2630 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2631 &ToPtr, ToPtr + NumBytes,
2632 strictConversion);
2633 // Check for conversion failure.
2634 if (Result != conversionOK)
2635 Diag(Arg->getLocStart(),
2636 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2637 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002638 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002639}
2640
Charles Davisc7d5c942015-09-17 20:55:33 +00002641/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2642/// for validity. Emit an error and return true on failure; return false
2643/// on success.
2644bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002645 Expr *Fn = TheCall->getCallee();
2646 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002647 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002648 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002649 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2650 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002651 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002652 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002653 return true;
2654 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002655
2656 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002657 return Diag(TheCall->getLocEnd(),
2658 diag::err_typecheck_call_too_few_args_at_least)
2659 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002660 }
2661
John McCall29ad95b2011-08-27 01:09:30 +00002662 // Type-check the first argument normally.
2663 if (checkBuiltinArgument(*this, TheCall, 0))
2664 return true;
2665
Chris Lattnere202e6a2007-12-20 00:05:45 +00002666 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002667 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002668 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002669 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002670 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002671 else if (FunctionDecl *FD = getCurFunctionDecl())
2672 isVariadic = FD->isVariadic();
2673 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002674 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002675
Chris Lattnere202e6a2007-12-20 00:05:45 +00002676 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002677 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2678 return true;
2679 }
Mike Stump11289f42009-09-09 15:08:12 +00002680
Chris Lattner43be2e62007-12-19 23:59:04 +00002681 // Verify that the second argument to the builtin is the last argument of the
2682 // current function or method.
2683 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002684 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002685
Nico Weber9eea7642013-05-24 23:31:57 +00002686 // These are valid if SecondArgIsLastNamedArgument is false after the next
2687 // block.
2688 QualType Type;
2689 SourceLocation ParamLoc;
2690
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002691 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2692 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002693 // FIXME: This isn't correct for methods (results in bogus warning).
2694 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002695 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002696 if (CurBlock)
2697 LastArg = *(CurBlock->TheDecl->param_end()-1);
2698 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002699 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002700 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002701 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002702 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002703
2704 Type = PV->getType();
2705 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002706 }
2707 }
Mike Stump11289f42009-09-09 15:08:12 +00002708
Chris Lattner43be2e62007-12-19 23:59:04 +00002709 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002710 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002711 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002712 else if (Type->isReferenceType()) {
2713 Diag(Arg->getLocStart(),
2714 diag::warn_va_start_of_reference_type_is_undefined);
2715 Diag(ParamLoc, diag::note_parameter_type) << Type;
2716 }
2717
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002718 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002719 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002720}
Chris Lattner43be2e62007-12-19 23:59:04 +00002721
Charles Davisc7d5c942015-09-17 20:55:33 +00002722/// Check the arguments to '__builtin_va_start' for validity, and that
2723/// it was called from a function of the native ABI.
2724/// Emit an error and return true on failure; return false on success.
2725bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2726 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2727 // On x64 Windows, don't allow this in System V ABI functions.
2728 // (Yes, that means there's no corresponding way to support variadic
2729 // System V ABI functions on Windows.)
2730 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2731 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2732 clang::CallingConv CC = CC_C;
2733 if (const FunctionDecl *FD = getCurFunctionDecl())
2734 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2735 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2736 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2737 return Diag(TheCall->getCallee()->getLocStart(),
2738 diag::err_va_start_used_in_wrong_abi_function)
2739 << (OS != llvm::Triple::Win32);
2740 }
2741 return SemaBuiltinVAStartImpl(TheCall);
2742}
2743
2744/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2745/// it was called from a Win64 ABI function.
2746/// Emit an error and return true on failure; return false on success.
2747bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2748 // This only makes sense for x86-64.
2749 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2750 Expr *Callee = TheCall->getCallee();
2751 if (TT.getArch() != llvm::Triple::x86_64)
2752 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2753 // Don't allow this in System V ABI functions.
2754 clang::CallingConv CC = CC_C;
2755 if (const FunctionDecl *FD = getCurFunctionDecl())
2756 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2757 if (CC == CC_X86_64SysV ||
2758 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2759 return Diag(Callee->getLocStart(),
2760 diag::err_ms_va_start_used_in_sysv_function);
2761 return SemaBuiltinVAStartImpl(TheCall);
2762}
2763
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002764bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2765 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2766 // const char *named_addr);
2767
2768 Expr *Func = Call->getCallee();
2769
2770 if (Call->getNumArgs() < 3)
2771 return Diag(Call->getLocEnd(),
2772 diag::err_typecheck_call_too_few_args_at_least)
2773 << 0 /*function call*/ << 3 << Call->getNumArgs();
2774
2775 // Determine whether the current function is variadic or not.
2776 bool IsVariadic;
2777 if (BlockScopeInfo *CurBlock = getCurBlock())
2778 IsVariadic = CurBlock->TheDecl->isVariadic();
2779 else if (FunctionDecl *FD = getCurFunctionDecl())
2780 IsVariadic = FD->isVariadic();
2781 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2782 IsVariadic = MD->isVariadic();
2783 else
2784 llvm_unreachable("unexpected statement type");
2785
2786 if (!IsVariadic) {
2787 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2788 return true;
2789 }
2790
2791 // Type-check the first argument normally.
2792 if (checkBuiltinArgument(*this, Call, 0))
2793 return true;
2794
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002795 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002796 unsigned ArgNo;
2797 QualType Type;
2798 } ArgumentTypes[] = {
2799 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2800 { 2, Context.getSizeType() },
2801 };
2802
2803 for (const auto &AT : ArgumentTypes) {
2804 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2805 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2806 continue;
2807 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2808 << Arg->getType() << AT.Type << 1 /* different class */
2809 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2810 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2811 }
2812
2813 return false;
2814}
2815
Chris Lattner2da14fb2007-12-20 00:26:33 +00002816/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2817/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002818bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2819 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002820 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002821 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002822 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002823 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002824 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002825 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002826 << SourceRange(TheCall->getArg(2)->getLocStart(),
2827 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002828
John Wiegley01296292011-04-08 18:41:53 +00002829 ExprResult OrigArg0 = TheCall->getArg(0);
2830 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002831
Chris Lattner2da14fb2007-12-20 00:26:33 +00002832 // Do standard promotions between the two arguments, returning their common
2833 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002834 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002835 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2836 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002837
2838 // Make sure any conversions are pushed back into the call; this is
2839 // type safe since unordered compare builtins are declared as "_Bool
2840 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002841 TheCall->setArg(0, OrigArg0.get());
2842 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002843
John Wiegley01296292011-04-08 18:41:53 +00002844 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002845 return false;
2846
Chris Lattner2da14fb2007-12-20 00:26:33 +00002847 // If the common type isn't a real floating type, then the arguments were
2848 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002849 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002850 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002851 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002852 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2853 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002854
Chris Lattner2da14fb2007-12-20 00:26:33 +00002855 return false;
2856}
2857
Benjamin Kramer634fc102010-02-15 22:42:31 +00002858/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2859/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002860/// to check everything. We expect the last argument to be a floating point
2861/// value.
2862bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2863 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002864 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002865 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002866 if (TheCall->getNumArgs() > NumArgs)
2867 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002868 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002869 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002870 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002871 (*(TheCall->arg_end()-1))->getLocEnd());
2872
Benjamin Kramer64aae502010-02-16 10:07:31 +00002873 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002874
Eli Friedman7e4faac2009-08-31 20:06:00 +00002875 if (OrigArg->isTypeDependent())
2876 return false;
2877
Chris Lattner68784ef2010-05-06 05:50:07 +00002878 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002879 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002880 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002881 diag::err_typecheck_call_invalid_unary_fp)
2882 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002883
Chris Lattner68784ef2010-05-06 05:50:07 +00002884 // If this is an implicit conversion from float -> double, remove it.
2885 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2886 Expr *CastArg = Cast->getSubExpr();
2887 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2888 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2889 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002890 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002891 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002892 }
2893 }
2894
Eli Friedman7e4faac2009-08-31 20:06:00 +00002895 return false;
2896}
2897
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002898/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2899// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002900ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002901 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002902 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002903 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002904 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2905 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002906
Nate Begemana0110022010-06-08 00:16:34 +00002907 // Determine which of the following types of shufflevector we're checking:
2908 // 1) unary, vector mask: (lhs, mask)
2909 // 2) binary, vector mask: (lhs, rhs, mask)
2910 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2911 QualType resType = TheCall->getArg(0)->getType();
2912 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002913
Douglas Gregorc25f7662009-05-19 22:10:17 +00002914 if (!TheCall->getArg(0)->isTypeDependent() &&
2915 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002916 QualType LHSType = TheCall->getArg(0)->getType();
2917 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002918
Craig Topperbaca3892013-07-29 06:47:04 +00002919 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2920 return ExprError(Diag(TheCall->getLocStart(),
2921 diag::err_shufflevector_non_vector)
2922 << SourceRange(TheCall->getArg(0)->getLocStart(),
2923 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002924
Nate Begemana0110022010-06-08 00:16:34 +00002925 numElements = LHSType->getAs<VectorType>()->getNumElements();
2926 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002927
Nate Begemana0110022010-06-08 00:16:34 +00002928 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2929 // with mask. If so, verify that RHS is an integer vector type with the
2930 // same number of elts as lhs.
2931 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002932 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002933 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002934 return ExprError(Diag(TheCall->getLocStart(),
2935 diag::err_shufflevector_incompatible_vector)
2936 << SourceRange(TheCall->getArg(1)->getLocStart(),
2937 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002938 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002939 return ExprError(Diag(TheCall->getLocStart(),
2940 diag::err_shufflevector_incompatible_vector)
2941 << SourceRange(TheCall->getArg(0)->getLocStart(),
2942 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002943 } else if (numElements != numResElements) {
2944 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002945 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002946 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002947 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002948 }
2949
2950 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002951 if (TheCall->getArg(i)->isTypeDependent() ||
2952 TheCall->getArg(i)->isValueDependent())
2953 continue;
2954
Nate Begemana0110022010-06-08 00:16:34 +00002955 llvm::APSInt Result(32);
2956 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2957 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002958 diag::err_shufflevector_nonconstant_argument)
2959 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002960
Craig Topper50ad5b72013-08-03 17:40:38 +00002961 // Allow -1 which will be translated to undef in the IR.
2962 if (Result.isSigned() && Result.isAllOnesValue())
2963 continue;
2964
Chris Lattner7ab824e2008-08-10 02:05:13 +00002965 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002966 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002967 diag::err_shufflevector_argument_too_large)
2968 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002969 }
2970
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002971 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002972
Chris Lattner7ab824e2008-08-10 02:05:13 +00002973 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002974 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002975 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002976 }
2977
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002978 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2979 TheCall->getCallee()->getLocStart(),
2980 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002981}
Chris Lattner43be2e62007-12-19 23:59:04 +00002982
Hal Finkelc4d7c822013-09-18 03:29:45 +00002983/// SemaConvertVectorExpr - Handle __builtin_convertvector
2984ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2985 SourceLocation BuiltinLoc,
2986 SourceLocation RParenLoc) {
2987 ExprValueKind VK = VK_RValue;
2988 ExprObjectKind OK = OK_Ordinary;
2989 QualType DstTy = TInfo->getType();
2990 QualType SrcTy = E->getType();
2991
2992 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2993 return ExprError(Diag(BuiltinLoc,
2994 diag::err_convertvector_non_vector)
2995 << E->getSourceRange());
2996 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2997 return ExprError(Diag(BuiltinLoc,
2998 diag::err_convertvector_non_vector_type));
2999
3000 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3001 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3002 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3003 if (SrcElts != DstElts)
3004 return ExprError(Diag(BuiltinLoc,
3005 diag::err_convertvector_incompatible_vector)
3006 << E->getSourceRange());
3007 }
3008
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003009 return new (Context)
3010 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003011}
3012
Daniel Dunbarb7257262008-07-21 22:59:13 +00003013/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3014// This is declared to take (const void*, ...) and can take two
3015// optional constant int args.
3016bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003017 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003018
Chris Lattner3b054132008-11-19 05:08:23 +00003019 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003020 return Diag(TheCall->getLocEnd(),
3021 diag::err_typecheck_call_too_many_args_at_most)
3022 << 0 /*function call*/ << 3 << NumArgs
3023 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003024
3025 // Argument 0 is checked for us and the remaining arguments must be
3026 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003027 for (unsigned i = 1; i != NumArgs; ++i)
3028 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003029 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003030
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003031 return false;
3032}
3033
Hal Finkelf0417332014-07-17 14:25:55 +00003034/// SemaBuiltinAssume - Handle __assume (MS Extension).
3035// __assume does not evaluate its arguments, and should warn if its argument
3036// has side effects.
3037bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3038 Expr *Arg = TheCall->getArg(0);
3039 if (Arg->isInstantiationDependent()) return false;
3040
3041 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003042 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003043 << Arg->getSourceRange()
3044 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3045
3046 return false;
3047}
3048
3049/// Handle __builtin_assume_aligned. This is declared
3050/// as (const void*, size_t, ...) and can take one optional constant int arg.
3051bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3052 unsigned NumArgs = TheCall->getNumArgs();
3053
3054 if (NumArgs > 3)
3055 return Diag(TheCall->getLocEnd(),
3056 diag::err_typecheck_call_too_many_args_at_most)
3057 << 0 /*function call*/ << 3 << NumArgs
3058 << TheCall->getSourceRange();
3059
3060 // The alignment must be a constant integer.
3061 Expr *Arg = TheCall->getArg(1);
3062
3063 // We can't check the value of a dependent argument.
3064 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3065 llvm::APSInt Result;
3066 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3067 return true;
3068
3069 if (!Result.isPowerOf2())
3070 return Diag(TheCall->getLocStart(),
3071 diag::err_alignment_not_power_of_two)
3072 << Arg->getSourceRange();
3073 }
3074
3075 if (NumArgs > 2) {
3076 ExprResult Arg(TheCall->getArg(2));
3077 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3078 Context.getSizeType(), false);
3079 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3080 if (Arg.isInvalid()) return true;
3081 TheCall->setArg(2, Arg.get());
3082 }
Hal Finkelf0417332014-07-17 14:25:55 +00003083
3084 return false;
3085}
3086
Eric Christopher8d0c6212010-04-17 02:26:23 +00003087/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3088/// TheCall is a constant expression.
3089bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3090 llvm::APSInt &Result) {
3091 Expr *Arg = TheCall->getArg(ArgNum);
3092 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3093 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3094
3095 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3096
3097 if (!Arg->isIntegerConstantExpr(Result, Context))
3098 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003099 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003100
Chris Lattnerd545ad12009-09-23 06:06:36 +00003101 return false;
3102}
3103
Richard Sandiford28940af2014-04-16 08:47:51 +00003104/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3105/// TheCall is a constant expression in the range [Low, High].
3106bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3107 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003108 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003109
3110 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003111 Expr *Arg = TheCall->getArg(ArgNum);
3112 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003113 return false;
3114
Eric Christopher8d0c6212010-04-17 02:26:23 +00003115 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003116 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003117 return true;
3118
Richard Sandiford28940af2014-04-16 08:47:51 +00003119 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003120 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003121 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003122
3123 return false;
3124}
3125
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003126/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3127/// TheCall is an ARM/AArch64 special register string literal.
3128bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3129 int ArgNum, unsigned ExpectedFieldNum,
3130 bool AllowName) {
3131 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3132 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3133 BuiltinID == ARM::BI__builtin_arm_rsr ||
3134 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3135 BuiltinID == ARM::BI__builtin_arm_wsr ||
3136 BuiltinID == ARM::BI__builtin_arm_wsrp;
3137 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3138 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3139 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3140 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3141 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3142 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3143 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3144
3145 // We can't check the value of a dependent argument.
3146 Expr *Arg = TheCall->getArg(ArgNum);
3147 if (Arg->isTypeDependent() || Arg->isValueDependent())
3148 return false;
3149
3150 // Check if the argument is a string literal.
3151 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3152 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3153 << Arg->getSourceRange();
3154
3155 // Check the type of special register given.
3156 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3157 SmallVector<StringRef, 6> Fields;
3158 Reg.split(Fields, ":");
3159
3160 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3161 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3162 << Arg->getSourceRange();
3163
3164 // If the string is the name of a register then we cannot check that it is
3165 // valid here but if the string is of one the forms described in ACLE then we
3166 // can check that the supplied fields are integers and within the valid
3167 // ranges.
3168 if (Fields.size() > 1) {
3169 bool FiveFields = Fields.size() == 5;
3170
3171 bool ValidString = true;
3172 if (IsARMBuiltin) {
3173 ValidString &= Fields[0].startswith_lower("cp") ||
3174 Fields[0].startswith_lower("p");
3175 if (ValidString)
3176 Fields[0] =
3177 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3178
3179 ValidString &= Fields[2].startswith_lower("c");
3180 if (ValidString)
3181 Fields[2] = Fields[2].drop_front(1);
3182
3183 if (FiveFields) {
3184 ValidString &= Fields[3].startswith_lower("c");
3185 if (ValidString)
3186 Fields[3] = Fields[3].drop_front(1);
3187 }
3188 }
3189
3190 SmallVector<int, 5> Ranges;
3191 if (FiveFields)
3192 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3193 else
3194 Ranges.append({15, 7, 15});
3195
3196 for (unsigned i=0; i<Fields.size(); ++i) {
3197 int IntField;
3198 ValidString &= !Fields[i].getAsInteger(10, IntField);
3199 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3200 }
3201
3202 if (!ValidString)
3203 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3204 << Arg->getSourceRange();
3205
3206 } else if (IsAArch64Builtin && Fields.size() == 1) {
3207 // If the register name is one of those that appear in the condition below
3208 // and the special register builtin being used is one of the write builtins,
3209 // then we require that the argument provided for writing to the register
3210 // is an integer constant expression. This is because it will be lowered to
3211 // an MSR (immediate) instruction, so we need to know the immediate at
3212 // compile time.
3213 if (TheCall->getNumArgs() != 2)
3214 return false;
3215
3216 std::string RegLower = Reg.lower();
3217 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3218 RegLower != "pan" && RegLower != "uao")
3219 return false;
3220
3221 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3222 }
3223
3224 return false;
3225}
3226
Eli Friedmanc97d0142009-05-03 06:04:26 +00003227/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003228/// This checks that the target supports __builtin_longjmp and
3229/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003230bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003231 if (!Context.getTargetInfo().hasSjLjLowering())
3232 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3233 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3234
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003235 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003236 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003237
Eric Christopher8d0c6212010-04-17 02:26:23 +00003238 // TODO: This is less than ideal. Overload this to take a value.
3239 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3240 return true;
3241
3242 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003243 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3244 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3245
3246 return false;
3247}
3248
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003249/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3250/// This checks that the target supports __builtin_setjmp.
3251bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3252 if (!Context.getTargetInfo().hasSjLjLowering())
3253 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3254 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3255 return false;
3256}
3257
Richard Smithd7293d72013-08-05 18:49:43 +00003258namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003259class UncoveredArgHandler {
3260 enum { Unknown = -1, AllCovered = -2 };
3261 signed FirstUncoveredArg;
3262 SmallVector<const Expr *, 4> DiagnosticExprs;
3263
3264public:
3265 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3266
3267 bool hasUncoveredArg() const {
3268 return (FirstUncoveredArg >= 0);
3269 }
3270
3271 unsigned getUncoveredArg() const {
3272 assert(hasUncoveredArg() && "no uncovered argument");
3273 return FirstUncoveredArg;
3274 }
3275
3276 void setAllCovered() {
3277 // A string has been found with all arguments covered, so clear out
3278 // the diagnostics.
3279 DiagnosticExprs.clear();
3280 FirstUncoveredArg = AllCovered;
3281 }
3282
3283 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3284 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3285
3286 // Don't update if a previous string covers all arguments.
3287 if (FirstUncoveredArg == AllCovered)
3288 return;
3289
3290 // UncoveredArgHandler tracks the highest uncovered argument index
3291 // and with it all the strings that match this index.
3292 if (NewFirstUncoveredArg == FirstUncoveredArg)
3293 DiagnosticExprs.push_back(StrExpr);
3294 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3295 DiagnosticExprs.clear();
3296 DiagnosticExprs.push_back(StrExpr);
3297 FirstUncoveredArg = NewFirstUncoveredArg;
3298 }
3299 }
3300
3301 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3302};
3303
Richard Smithd7293d72013-08-05 18:49:43 +00003304enum StringLiteralCheckType {
3305 SLCT_NotALiteral,
3306 SLCT_UncheckedLiteral,
3307 SLCT_CheckedLiteral
3308};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003309} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003310
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003311static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3312 const Expr *OrigFormatExpr,
3313 ArrayRef<const Expr *> Args,
3314 bool HasVAListArg, unsigned format_idx,
3315 unsigned firstDataArg,
3316 Sema::FormatStringType Type,
3317 bool inFunctionCall,
3318 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003319 llvm::SmallBitVector &CheckedVarArgs,
3320 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003321
Richard Smith55ce3522012-06-25 20:30:08 +00003322// Determine if an expression is a string literal or constant string.
3323// If this function returns false on the arguments to a function expecting a
3324// format string, we will usually need to emit a warning.
3325// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003326static StringLiteralCheckType
3327checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3328 bool HasVAListArg, unsigned format_idx,
3329 unsigned firstDataArg, Sema::FormatStringType Type,
3330 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003331 llvm::SmallBitVector &CheckedVarArgs,
3332 UncoveredArgHandler &UncoveredArg) {
Ted Kremenek808829352010-09-09 03:51:39 +00003333 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003334 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003335 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003336
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003337 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003338
Richard Smithd7293d72013-08-05 18:49:43 +00003339 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003340 // Technically -Wformat-nonliteral does not warn about this case.
3341 // The behavior of printf and friends in this case is implementation
3342 // dependent. Ideally if the format string cannot be null then
3343 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003344 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003345
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003346 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003347 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003348 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003349 // The expression is a literal if both sub-expressions were, and it was
3350 // completely checked only if both sub-expressions were checked.
3351 const AbstractConditionalOperator *C =
3352 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003353
3354 // Determine whether it is necessary to check both sub-expressions, for
3355 // example, because the condition expression is a constant that can be
3356 // evaluated at compile time.
3357 bool CheckLeft = true, CheckRight = true;
3358
3359 bool Cond;
3360 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3361 if (Cond)
3362 CheckRight = false;
3363 else
3364 CheckLeft = false;
3365 }
3366
3367 StringLiteralCheckType Left;
3368 if (!CheckLeft)
3369 Left = SLCT_UncheckedLiteral;
3370 else {
3371 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3372 HasVAListArg, format_idx, firstDataArg,
3373 Type, CallType, InFunctionCall,
3374 CheckedVarArgs, UncoveredArg);
3375 if (Left == SLCT_NotALiteral || !CheckRight)
3376 return Left;
3377 }
3378
Richard Smith55ce3522012-06-25 20:30:08 +00003379 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003380 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003381 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003382 Type, CallType, InFunctionCall, CheckedVarArgs,
3383 UncoveredArg);
3384
3385 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003386 }
3387
3388 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003389 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3390 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003391 }
3392
John McCallc07a0c72011-02-17 10:25:35 +00003393 case Stmt::OpaqueValueExprClass:
3394 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3395 E = src;
3396 goto tryAgain;
3397 }
Richard Smith55ce3522012-06-25 20:30:08 +00003398 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003399
Ted Kremeneka8890832011-02-24 23:03:04 +00003400 case Stmt::PredefinedExprClass:
3401 // While __func__, etc., are technically not string literals, they
3402 // cannot contain format specifiers and thus are not a security
3403 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003404 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003405
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003406 case Stmt::DeclRefExprClass: {
3407 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003408
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003409 // As an exception, do not flag errors for variables binding to
3410 // const string literals.
3411 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3412 bool isConstant = false;
3413 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003414
Richard Smithd7293d72013-08-05 18:49:43 +00003415 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3416 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003417 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003418 isConstant = T.isConstant(S.Context) &&
3419 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003420 } else if (T->isObjCObjectPointerType()) {
3421 // In ObjC, there is usually no "const ObjectPointer" type,
3422 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003423 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003424 }
Mike Stump11289f42009-09-09 15:08:12 +00003425
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003426 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003427 if (const Expr *Init = VD->getAnyInitializer()) {
3428 // Look through initializers like const char c[] = { "foo" }
3429 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3430 if (InitList->isStringLiteralInit())
3431 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3432 }
Richard Smithd7293d72013-08-05 18:49:43 +00003433 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003434 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003435 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003436 /*InFunctionCall*/false, CheckedVarArgs,
3437 UncoveredArg);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003438 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003439 }
Mike Stump11289f42009-09-09 15:08:12 +00003440
Anders Carlssonb012ca92009-06-28 19:55:58 +00003441 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3442 // special check to see if the format string is a function parameter
3443 // of the function calling the printf function. If the function
3444 // has an attribute indicating it is a printf-like function, then we
3445 // should suppress warnings concerning non-literals being used in a call
3446 // to a vprintf function. For example:
3447 //
3448 // void
3449 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3450 // va_list ap;
3451 // va_start(ap, fmt);
3452 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3453 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003454 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003455 if (HasVAListArg) {
3456 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3457 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3458 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003459 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003460 // adjust for implicit parameter
3461 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3462 if (MD->isInstance())
3463 ++PVIndex;
3464 // We also check if the formats are compatible.
3465 // We can't pass a 'scanf' string to a 'printf' function.
3466 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003467 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003468 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003469 }
3470 }
3471 }
3472 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003473 }
Mike Stump11289f42009-09-09 15:08:12 +00003474
Richard Smith55ce3522012-06-25 20:30:08 +00003475 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003476 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003477
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003478 case Stmt::CallExprClass:
3479 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003480 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003481 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3482 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3483 unsigned ArgIndex = FA->getFormatIdx();
3484 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3485 if (MD->isInstance())
3486 --ArgIndex;
3487 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003488
Richard Smithd7293d72013-08-05 18:49:43 +00003489 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003490 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003491 Type, CallType, InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003492 CheckedVarArgs, UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003493 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3494 unsigned BuiltinID = FD->getBuiltinID();
3495 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3496 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3497 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003498 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003499 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003500 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003501 InFunctionCall, CheckedVarArgs,
3502 UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003503 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003504 }
3505 }
Mike Stump11289f42009-09-09 15:08:12 +00003506
Richard Smith55ce3522012-06-25 20:30:08 +00003507 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003508 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003509 case Stmt::ObjCStringLiteralClass:
3510 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003511 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003512
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003513 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003514 StrE = ObjCFExpr->getString();
3515 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003516 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003517
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003518 if (StrE) {
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003519 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
3520 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003521 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00003522 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003523 }
Mike Stump11289f42009-09-09 15:08:12 +00003524
Richard Smith55ce3522012-06-25 20:30:08 +00003525 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003526 }
Mike Stump11289f42009-09-09 15:08:12 +00003527
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003528 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003529 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003530 }
3531}
3532
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003533Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003534 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003535 .Case("scanf", FST_Scanf)
3536 .Cases("printf", "printf0", FST_Printf)
3537 .Cases("NSString", "CFString", FST_NSString)
3538 .Case("strftime", FST_Strftime)
3539 .Case("strfmon", FST_Strfmon)
3540 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003541 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003542 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003543 .Default(FST_Unknown);
3544}
3545
Jordan Rose3e0ec582012-07-19 18:10:23 +00003546/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003547/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003548/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003549bool Sema::CheckFormatArguments(const FormatAttr *Format,
3550 ArrayRef<const Expr *> Args,
3551 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003552 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003553 SourceLocation Loc, SourceRange Range,
3554 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003555 FormatStringInfo FSI;
3556 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003557 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003558 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003559 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003560 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003561}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003562
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003563bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003564 bool HasVAListArg, unsigned format_idx,
3565 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003566 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003567 SourceLocation Loc, SourceRange Range,
3568 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003569 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003570 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003571 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003572 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003573 }
Mike Stump11289f42009-09-09 15:08:12 +00003574
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003575 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003576
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003577 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003578 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003579 // Dynamically generated format strings are difficult to
3580 // automatically vet at compile time. Requiring that format strings
3581 // are string literals: (1) permits the checking of format strings by
3582 // the compiler and thereby (2) can practically remove the source of
3583 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003584
Mike Stump11289f42009-09-09 15:08:12 +00003585 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003586 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003587 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003588 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003589 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00003590 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003591 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3592 format_idx, firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003593 /*IsFunctionCall*/true, CheckedVarArgs,
3594 UncoveredArg);
3595
3596 // Generate a diagnostic where an uncovered argument is detected.
3597 if (UncoveredArg.hasUncoveredArg()) {
3598 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
3599 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
3600 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
3601 }
3602
Richard Smith55ce3522012-06-25 20:30:08 +00003603 if (CT != SLCT_NotALiteral)
3604 // Literal format string found, check done!
3605 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003606
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003607 // Strftime is particular as it always uses a single 'time' argument,
3608 // so it is safe to pass a non-literal string.
3609 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003610 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003611
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003612 // Do not emit diag when the string param is a macro expansion and the
3613 // format is either NSString or CFString. This is a hack to prevent
3614 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3615 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003616 if (Type == FST_NSString &&
3617 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003618 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003619
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003620 // If there are no arguments specified, warn with -Wformat-security, otherwise
3621 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003622 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003623 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003624 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003625 << OrigFormatExpr->getSourceRange();
3626 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003627 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003628 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003629 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003630 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003631}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003632
Ted Kremenekab278de2010-01-28 23:39:18 +00003633namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003634class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3635protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003636 Sema &S;
3637 const StringLiteral *FExpr;
3638 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003639 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003640 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003641 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003642 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003643 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003644 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003645 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003646 bool usesPositionalArgs;
3647 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003648 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003649 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003650 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003651 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003652
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003653public:
Ted Kremenek02087932010-07-16 02:11:22 +00003654 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003655 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003656 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003657 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003658 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003659 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003660 llvm::SmallBitVector &CheckedVarArgs,
3661 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00003662 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003663 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3664 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003665 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003666 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003667 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003668 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00003669 CoveredArgs.resize(numDataArgs);
3670 CoveredArgs.reset();
3671 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003672
Ted Kremenek019d2242010-01-29 01:50:07 +00003673 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003674
Ted Kremenek02087932010-07-16 02:11:22 +00003675 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003676 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003677
Jordan Rose92303592012-09-08 04:00:03 +00003678 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003679 const analyze_format_string::FormatSpecifier &FS,
3680 const analyze_format_string::ConversionSpecifier &CS,
3681 const char *startSpecifier, unsigned specifierLen,
3682 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003683
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003684 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003685 const analyze_format_string::FormatSpecifier &FS,
3686 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003687
3688 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003689 const analyze_format_string::ConversionSpecifier &CS,
3690 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003691
Craig Toppere14c0f82014-03-12 04:55:44 +00003692 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003693
Craig Toppere14c0f82014-03-12 04:55:44 +00003694 void HandleInvalidPosition(const char *startSpecifier,
3695 unsigned specifierLen,
3696 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003697
Craig Toppere14c0f82014-03-12 04:55:44 +00003698 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003699
Craig Toppere14c0f82014-03-12 04:55:44 +00003700 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003701
Richard Trieu03cf7b72011-10-28 00:41:25 +00003702 template <typename Range>
3703 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3704 const Expr *ArgumentExpr,
3705 PartialDiagnostic PDiag,
3706 SourceLocation StringLoc,
3707 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003708 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003709
Ted Kremenek02087932010-07-16 02:11:22 +00003710protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003711 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3712 const char *startSpec,
3713 unsigned specifierLen,
3714 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003715
3716 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3717 const char *startSpec,
3718 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003719
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003720 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003721 CharSourceRange getSpecifierRange(const char *startSpecifier,
3722 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003723 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003724
Ted Kremenek5739de72010-01-29 01:06:55 +00003725 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003726
3727 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3728 const analyze_format_string::ConversionSpecifier &CS,
3729 const char *startSpecifier, unsigned specifierLen,
3730 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003731
3732 template <typename Range>
3733 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3734 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003735 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003736};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003737} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00003738
Ted Kremenek02087932010-07-16 02:11:22 +00003739SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003740 return OrigFormatExpr->getSourceRange();
3741}
3742
Ted Kremenek02087932010-07-16 02:11:22 +00003743CharSourceRange CheckFormatHandler::
3744getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003745 SourceLocation Start = getLocationOfByte(startSpecifier);
3746 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3747
3748 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003749 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003750
3751 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003752}
3753
Ted Kremenek02087932010-07-16 02:11:22 +00003754SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003755 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003756}
3757
Ted Kremenek02087932010-07-16 02:11:22 +00003758void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3759 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003760 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3761 getLocationOfByte(startSpecifier),
3762 /*IsStringLocation*/true,
3763 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003764}
3765
Jordan Rose92303592012-09-08 04:00:03 +00003766void CheckFormatHandler::HandleInvalidLengthModifier(
3767 const analyze_format_string::FormatSpecifier &FS,
3768 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003769 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003770 using namespace analyze_format_string;
3771
3772 const LengthModifier &LM = FS.getLengthModifier();
3773 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3774
3775 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003776 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003777 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003778 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003779 getLocationOfByte(LM.getStart()),
3780 /*IsStringLocation*/true,
3781 getSpecifierRange(startSpecifier, specifierLen));
3782
3783 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3784 << FixedLM->toString()
3785 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3786
3787 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003788 FixItHint Hint;
3789 if (DiagID == diag::warn_format_nonsensical_length)
3790 Hint = FixItHint::CreateRemoval(LMRange);
3791
3792 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003793 getLocationOfByte(LM.getStart()),
3794 /*IsStringLocation*/true,
3795 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003796 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003797 }
3798}
3799
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003800void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003801 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003802 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003803 using namespace analyze_format_string;
3804
3805 const LengthModifier &LM = FS.getLengthModifier();
3806 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3807
3808 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003809 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003810 if (FixedLM) {
3811 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3812 << LM.toString() << 0,
3813 getLocationOfByte(LM.getStart()),
3814 /*IsStringLocation*/true,
3815 getSpecifierRange(startSpecifier, specifierLen));
3816
3817 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3818 << FixedLM->toString()
3819 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3820
3821 } else {
3822 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3823 << LM.toString() << 0,
3824 getLocationOfByte(LM.getStart()),
3825 /*IsStringLocation*/true,
3826 getSpecifierRange(startSpecifier, specifierLen));
3827 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003828}
3829
3830void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3831 const analyze_format_string::ConversionSpecifier &CS,
3832 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003833 using namespace analyze_format_string;
3834
3835 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003836 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003837 if (FixedCS) {
3838 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3839 << CS.toString() << /*conversion specifier*/1,
3840 getLocationOfByte(CS.getStart()),
3841 /*IsStringLocation*/true,
3842 getSpecifierRange(startSpecifier, specifierLen));
3843
3844 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3845 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3846 << FixedCS->toString()
3847 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3848 } else {
3849 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3850 << CS.toString() << /*conversion specifier*/1,
3851 getLocationOfByte(CS.getStart()),
3852 /*IsStringLocation*/true,
3853 getSpecifierRange(startSpecifier, specifierLen));
3854 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003855}
3856
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003857void CheckFormatHandler::HandlePosition(const char *startPos,
3858 unsigned posLen) {
3859 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3860 getLocationOfByte(startPos),
3861 /*IsStringLocation*/true,
3862 getSpecifierRange(startPos, posLen));
3863}
3864
Ted Kremenekd1668192010-02-27 01:41:03 +00003865void
Ted Kremenek02087932010-07-16 02:11:22 +00003866CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3867 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003868 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3869 << (unsigned) p,
3870 getLocationOfByte(startPos), /*IsStringLocation*/true,
3871 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003872}
3873
Ted Kremenek02087932010-07-16 02:11:22 +00003874void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003875 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003876 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3877 getLocationOfByte(startPos),
3878 /*IsStringLocation*/true,
3879 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003880}
3881
Ted Kremenek02087932010-07-16 02:11:22 +00003882void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003883 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003884 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003885 EmitFormatDiagnostic(
3886 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3887 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3888 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003889 }
Ted Kremenek02087932010-07-16 02:11:22 +00003890}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003891
Jordan Rose58bbe422012-07-19 18:10:08 +00003892// Note that this may return NULL if there was an error parsing or building
3893// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003894const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003895 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003896}
3897
3898void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003899 // Does the number of data arguments exceed the number of
3900 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00003901 if (!HasVAListArg) {
3902 // Find any arguments that weren't covered.
3903 CoveredArgs.flip();
3904 signed notCoveredArg = CoveredArgs.find_first();
3905 if (notCoveredArg >= 0) {
3906 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003907 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
3908 } else {
3909 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00003910 }
3911 }
3912}
3913
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003914void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
3915 const Expr *ArgExpr) {
3916 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
3917 "Invalid state");
3918
3919 if (!ArgExpr)
3920 return;
3921
3922 SourceLocation Loc = ArgExpr->getLocStart();
3923
3924 if (S.getSourceManager().isInSystemMacro(Loc))
3925 return;
3926
3927 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
3928 for (auto E : DiagnosticExprs)
3929 PDiag << E->getSourceRange();
3930
3931 CheckFormatHandler::EmitFormatDiagnostic(
3932 S, IsFunctionCall, DiagnosticExprs[0],
3933 PDiag, Loc, /*IsStringLocation*/false,
3934 DiagnosticExprs[0]->getSourceRange());
3935}
3936
Ted Kremenekce815422010-07-19 21:25:57 +00003937bool
3938CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3939 SourceLocation Loc,
3940 const char *startSpec,
3941 unsigned specifierLen,
3942 const char *csStart,
3943 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00003944 bool keepGoing = true;
3945 if (argIndex < NumDataArgs) {
3946 // Consider the argument coverered, even though the specifier doesn't
3947 // make sense.
3948 CoveredArgs.set(argIndex);
3949 }
3950 else {
3951 // If argIndex exceeds the number of data arguments we
3952 // don't issue a warning because that is just a cascade of warnings (and
3953 // they may have intended '%%' anyway). We don't want to continue processing
3954 // the format string after this point, however, as we will like just get
3955 // gibberish when trying to match arguments.
3956 keepGoing = false;
3957 }
3958
Richard Trieu03cf7b72011-10-28 00:41:25 +00003959 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3960 << StringRef(csStart, csLen),
3961 Loc, /*IsStringLocation*/true,
3962 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003963
3964 return keepGoing;
3965}
3966
Richard Trieu03cf7b72011-10-28 00:41:25 +00003967void
3968CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3969 const char *startSpec,
3970 unsigned specifierLen) {
3971 EmitFormatDiagnostic(
3972 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3973 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3974}
3975
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003976bool
3977CheckFormatHandler::CheckNumArgs(
3978 const analyze_format_string::FormatSpecifier &FS,
3979 const analyze_format_string::ConversionSpecifier &CS,
3980 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3981
3982 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003983 PartialDiagnostic PDiag = FS.usesPositionalArg()
3984 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3985 << (argIndex+1) << NumDataArgs)
3986 : S.PDiag(diag::warn_printf_insufficient_data_args);
3987 EmitFormatDiagnostic(
3988 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3989 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003990
3991 // Since more arguments than conversion tokens are given, by extension
3992 // all arguments are covered, so mark this as so.
3993 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003994 return false;
3995 }
3996 return true;
3997}
3998
Richard Trieu03cf7b72011-10-28 00:41:25 +00003999template<typename Range>
4000void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4001 SourceLocation Loc,
4002 bool IsStringLocation,
4003 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004004 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004005 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004006 Loc, IsStringLocation, StringRange, FixIt);
4007}
4008
4009/// \brief If the format string is not within the funcion call, emit a note
4010/// so that the function call and string are in diagnostic messages.
4011///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004012/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004013/// call and only one diagnostic message will be produced. Otherwise, an
4014/// extra note will be emitted pointing to location of the format string.
4015///
4016/// \param ArgumentExpr the expression that is passed as the format string
4017/// argument in the function call. Used for getting locations when two
4018/// diagnostics are emitted.
4019///
4020/// \param PDiag the callee should already have provided any strings for the
4021/// diagnostic message. This function only adds locations and fixits
4022/// to diagnostics.
4023///
4024/// \param Loc primary location for diagnostic. If two diagnostics are
4025/// required, one will be at Loc and a new SourceLocation will be created for
4026/// the other one.
4027///
4028/// \param IsStringLocation if true, Loc points to the format string should be
4029/// used for the note. Otherwise, Loc points to the argument list and will
4030/// be used with PDiag.
4031///
4032/// \param StringRange some or all of the string to highlight. This is
4033/// templated so it can accept either a CharSourceRange or a SourceRange.
4034///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004035/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004036template<typename Range>
4037void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
4038 const Expr *ArgumentExpr,
4039 PartialDiagnostic PDiag,
4040 SourceLocation Loc,
4041 bool IsStringLocation,
4042 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004043 ArrayRef<FixItHint> FixIt) {
4044 if (InFunctionCall) {
4045 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4046 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004047 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004048 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004049 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4050 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004051
4052 const Sema::SemaDiagnosticBuilder &Note =
4053 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4054 diag::note_format_string_defined);
4055
4056 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004057 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004058 }
4059}
4060
Ted Kremenek02087932010-07-16 02:11:22 +00004061//===--- CHECK: Printf format string checking ------------------------------===//
4062
4063namespace {
4064class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004065 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004066
Ted Kremenek02087932010-07-16 02:11:22 +00004067public:
4068 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4069 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004070 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004071 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004072 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004073 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004074 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004075 llvm::SmallBitVector &CheckedVarArgs,
4076 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004077 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4078 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004079 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4080 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004081 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004082 {}
4083
Ted Kremenek02087932010-07-16 02:11:22 +00004084 bool HandleInvalidPrintfConversionSpecifier(
4085 const analyze_printf::PrintfSpecifier &FS,
4086 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004087 unsigned specifierLen) override;
4088
Ted Kremenek02087932010-07-16 02:11:22 +00004089 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4090 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004091 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004092 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4093 const char *StartSpecifier,
4094 unsigned SpecifierLen,
4095 const Expr *E);
4096
Ted Kremenek02087932010-07-16 02:11:22 +00004097 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4098 const char *startSpecifier, unsigned specifierLen);
4099 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4100 const analyze_printf::OptionalAmount &Amt,
4101 unsigned type,
4102 const char *startSpecifier, unsigned specifierLen);
4103 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4104 const analyze_printf::OptionalFlag &flag,
4105 const char *startSpecifier, unsigned specifierLen);
4106 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4107 const analyze_printf::OptionalFlag &ignoredFlag,
4108 const analyze_printf::OptionalFlag &flag,
4109 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004110 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004111 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004112
4113 void HandleEmptyObjCModifierFlag(const char *startFlag,
4114 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004115
Ted Kremenek2b417712015-07-02 05:39:16 +00004116 void HandleInvalidObjCModifierFlag(const char *startFlag,
4117 unsigned flagLen) override;
4118
4119 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4120 const char *flagsEnd,
4121 const char *conversionPosition)
4122 override;
4123};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004124} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004125
4126bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4127 const analyze_printf::PrintfSpecifier &FS,
4128 const char *startSpecifier,
4129 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004130 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004131 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004132
Ted Kremenekce815422010-07-19 21:25:57 +00004133 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4134 getLocationOfByte(CS.getStart()),
4135 startSpecifier, specifierLen,
4136 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004137}
4138
Ted Kremenek02087932010-07-16 02:11:22 +00004139bool CheckPrintfHandler::HandleAmount(
4140 const analyze_format_string::OptionalAmount &Amt,
4141 unsigned k, const char *startSpecifier,
4142 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004143 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004144 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004145 unsigned argIndex = Amt.getArgIndex();
4146 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004147 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4148 << k,
4149 getLocationOfByte(Amt.getStart()),
4150 /*IsStringLocation*/true,
4151 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004152 // Don't do any more checking. We will just emit
4153 // spurious errors.
4154 return false;
4155 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004156
Ted Kremenek5739de72010-01-29 01:06:55 +00004157 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004158 // Although not in conformance with C99, we also allow the argument to be
4159 // an 'unsigned int' as that is a reasonably safe case. GCC also
4160 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004161 CoveredArgs.set(argIndex);
4162 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004163 if (!Arg)
4164 return false;
4165
Ted Kremenek5739de72010-01-29 01:06:55 +00004166 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004167
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004168 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4169 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004170
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004171 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004172 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004173 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004174 << T << Arg->getSourceRange(),
4175 getLocationOfByte(Amt.getStart()),
4176 /*IsStringLocation*/true,
4177 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004178 // Don't do any more checking. We will just emit
4179 // spurious errors.
4180 return false;
4181 }
4182 }
4183 }
4184 return true;
4185}
Ted Kremenek5739de72010-01-29 01:06:55 +00004186
Tom Careb49ec692010-06-17 19:00:27 +00004187void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004188 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004189 const analyze_printf::OptionalAmount &Amt,
4190 unsigned type,
4191 const char *startSpecifier,
4192 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004193 const analyze_printf::PrintfConversionSpecifier &CS =
4194 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004195
Richard Trieu03cf7b72011-10-28 00:41:25 +00004196 FixItHint fixit =
4197 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4198 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4199 Amt.getConstantLength()))
4200 : FixItHint();
4201
4202 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4203 << type << CS.toString(),
4204 getLocationOfByte(Amt.getStart()),
4205 /*IsStringLocation*/true,
4206 getSpecifierRange(startSpecifier, specifierLen),
4207 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004208}
4209
Ted Kremenek02087932010-07-16 02:11:22 +00004210void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004211 const analyze_printf::OptionalFlag &flag,
4212 const char *startSpecifier,
4213 unsigned specifierLen) {
4214 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004215 const analyze_printf::PrintfConversionSpecifier &CS =
4216 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004217 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4218 << flag.toString() << CS.toString(),
4219 getLocationOfByte(flag.getPosition()),
4220 /*IsStringLocation*/true,
4221 getSpecifierRange(startSpecifier, specifierLen),
4222 FixItHint::CreateRemoval(
4223 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004224}
4225
4226void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004227 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004228 const analyze_printf::OptionalFlag &ignoredFlag,
4229 const analyze_printf::OptionalFlag &flag,
4230 const char *startSpecifier,
4231 unsigned specifierLen) {
4232 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004233 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4234 << ignoredFlag.toString() << flag.toString(),
4235 getLocationOfByte(ignoredFlag.getPosition()),
4236 /*IsStringLocation*/true,
4237 getSpecifierRange(startSpecifier, specifierLen),
4238 FixItHint::CreateRemoval(
4239 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004240}
4241
Ted Kremenek2b417712015-07-02 05:39:16 +00004242// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4243// bool IsStringLocation, Range StringRange,
4244// ArrayRef<FixItHint> Fixit = None);
4245
4246void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4247 unsigned flagLen) {
4248 // Warn about an empty flag.
4249 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4250 getLocationOfByte(startFlag),
4251 /*IsStringLocation*/true,
4252 getSpecifierRange(startFlag, flagLen));
4253}
4254
4255void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4256 unsigned flagLen) {
4257 // Warn about an invalid flag.
4258 auto Range = getSpecifierRange(startFlag, flagLen);
4259 StringRef flag(startFlag, flagLen);
4260 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4261 getLocationOfByte(startFlag),
4262 /*IsStringLocation*/true,
4263 Range, FixItHint::CreateRemoval(Range));
4264}
4265
4266void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4267 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4268 // Warn about using '[...]' without a '@' conversion.
4269 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4270 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4271 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4272 getLocationOfByte(conversionPosition),
4273 /*IsStringLocation*/true,
4274 Range, FixItHint::CreateRemoval(Range));
4275}
4276
Richard Smith55ce3522012-06-25 20:30:08 +00004277// Determines if the specified is a C++ class or struct containing
4278// a member with the specified name and kind (e.g. a CXXMethodDecl named
4279// "c_str()").
4280template<typename MemberKind>
4281static llvm::SmallPtrSet<MemberKind*, 1>
4282CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4283 const RecordType *RT = Ty->getAs<RecordType>();
4284 llvm::SmallPtrSet<MemberKind*, 1> Results;
4285
4286 if (!RT)
4287 return Results;
4288 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004289 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004290 return Results;
4291
Alp Tokerb6cc5922014-05-03 03:45:55 +00004292 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004293 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004294 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004295
4296 // We just need to include all members of the right kind turned up by the
4297 // filter, at this point.
4298 if (S.LookupQualifiedName(R, RT->getDecl()))
4299 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4300 NamedDecl *decl = (*I)->getUnderlyingDecl();
4301 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4302 Results.insert(FK);
4303 }
4304 return Results;
4305}
4306
Richard Smith2868a732014-02-28 01:36:39 +00004307/// Check if we could call '.c_str()' on an object.
4308///
4309/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4310/// allow the call, or if it would be ambiguous).
4311bool Sema::hasCStrMethod(const Expr *E) {
4312 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4313 MethodSet Results =
4314 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4315 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4316 MI != ME; ++MI)
4317 if ((*MI)->getMinRequiredArguments() == 0)
4318 return true;
4319 return false;
4320}
4321
Richard Smith55ce3522012-06-25 20:30:08 +00004322// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004323// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004324// Returns true when a c_str() conversion method is found.
4325bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004326 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004327 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4328
4329 MethodSet Results =
4330 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4331
4332 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4333 MI != ME; ++MI) {
4334 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004335 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004336 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004337 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004338 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004339 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4340 << "c_str()"
4341 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4342 return true;
4343 }
4344 }
4345
4346 return false;
4347}
4348
Ted Kremenekab278de2010-01-28 23:39:18 +00004349bool
Ted Kremenek02087932010-07-16 02:11:22 +00004350CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004351 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004352 const char *startSpecifier,
4353 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004354 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004355 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004356 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004357
Ted Kremenek6cd69422010-07-19 22:01:06 +00004358 if (FS.consumesDataArgument()) {
4359 if (atFirstArg) {
4360 atFirstArg = false;
4361 usesPositionalArgs = FS.usesPositionalArg();
4362 }
4363 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004364 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4365 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004366 return false;
4367 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004368 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004369
Ted Kremenekd1668192010-02-27 01:41:03 +00004370 // First check if the field width, precision, and conversion specifier
4371 // have matching data arguments.
4372 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4373 startSpecifier, specifierLen)) {
4374 return false;
4375 }
4376
4377 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4378 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004379 return false;
4380 }
4381
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004382 if (!CS.consumesDataArgument()) {
4383 // FIXME: Technically specifying a precision or field width here
4384 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004385 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004386 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004387
Ted Kremenek4a49d982010-02-26 19:18:41 +00004388 // Consume the argument.
4389 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004390 if (argIndex < NumDataArgs) {
4391 // The check to see if the argIndex is valid will come later.
4392 // We set the bit here because we may exit early from this
4393 // function if we encounter some other error.
4394 CoveredArgs.set(argIndex);
4395 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004396
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004397 // FreeBSD kernel extensions.
4398 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4399 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4400 // We need at least two arguments.
4401 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4402 return false;
4403
4404 // Claim the second argument.
4405 CoveredArgs.set(argIndex + 1);
4406
4407 // Type check the first argument (int for %b, pointer for %D)
4408 const Expr *Ex = getDataArg(argIndex);
4409 const analyze_printf::ArgType &AT =
4410 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4411 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4412 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4413 EmitFormatDiagnostic(
4414 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4415 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4416 << false << Ex->getSourceRange(),
4417 Ex->getLocStart(), /*IsStringLocation*/false,
4418 getSpecifierRange(startSpecifier, specifierLen));
4419
4420 // Type check the second argument (char * for both %b and %D)
4421 Ex = getDataArg(argIndex + 1);
4422 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4423 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4424 EmitFormatDiagnostic(
4425 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4426 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4427 << false << Ex->getSourceRange(),
4428 Ex->getLocStart(), /*IsStringLocation*/false,
4429 getSpecifierRange(startSpecifier, specifierLen));
4430
4431 return true;
4432 }
4433
Ted Kremenek4a49d982010-02-26 19:18:41 +00004434 // Check for using an Objective-C specific conversion specifier
4435 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004436 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004437 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4438 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004439 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004440
Tom Careb49ec692010-06-17 19:00:27 +00004441 // Check for invalid use of field width
4442 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004443 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004444 startSpecifier, specifierLen);
4445 }
4446
4447 // Check for invalid use of precision
4448 if (!FS.hasValidPrecision()) {
4449 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4450 startSpecifier, specifierLen);
4451 }
4452
4453 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004454 if (!FS.hasValidThousandsGroupingPrefix())
4455 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004456 if (!FS.hasValidLeadingZeros())
4457 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4458 if (!FS.hasValidPlusPrefix())
4459 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004460 if (!FS.hasValidSpacePrefix())
4461 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004462 if (!FS.hasValidAlternativeForm())
4463 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4464 if (!FS.hasValidLeftJustified())
4465 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4466
4467 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004468 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4469 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4470 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004471 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4472 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4473 startSpecifier, specifierLen);
4474
4475 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004476 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004477 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4478 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004479 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004480 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004481 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004482 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4483 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004484
Jordan Rose92303592012-09-08 04:00:03 +00004485 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4486 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4487
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004488 // The remaining checks depend on the data arguments.
4489 if (HasVAListArg)
4490 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004491
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004492 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004493 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004494
Jordan Rose58bbe422012-07-19 18:10:08 +00004495 const Expr *Arg = getDataArg(argIndex);
4496 if (!Arg)
4497 return true;
4498
4499 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004500}
4501
Jordan Roseaee34382012-09-05 22:56:26 +00004502static bool requiresParensToAddCast(const Expr *E) {
4503 // FIXME: We should have a general way to reason about operator
4504 // precedence and whether parens are actually needed here.
4505 // Take care of a few common cases where they aren't.
4506 const Expr *Inside = E->IgnoreImpCasts();
4507 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4508 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4509
4510 switch (Inside->getStmtClass()) {
4511 case Stmt::ArraySubscriptExprClass:
4512 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004513 case Stmt::CharacterLiteralClass:
4514 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004515 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004516 case Stmt::FloatingLiteralClass:
4517 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004518 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004519 case Stmt::ObjCArrayLiteralClass:
4520 case Stmt::ObjCBoolLiteralExprClass:
4521 case Stmt::ObjCBoxedExprClass:
4522 case Stmt::ObjCDictionaryLiteralClass:
4523 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004524 case Stmt::ObjCIvarRefExprClass:
4525 case Stmt::ObjCMessageExprClass:
4526 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004527 case Stmt::ObjCStringLiteralClass:
4528 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004529 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004530 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004531 case Stmt::UnaryOperatorClass:
4532 return false;
4533 default:
4534 return true;
4535 }
4536}
4537
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004538static std::pair<QualType, StringRef>
4539shouldNotPrintDirectly(const ASTContext &Context,
4540 QualType IntendedTy,
4541 const Expr *E) {
4542 // Use a 'while' to peel off layers of typedefs.
4543 QualType TyTy = IntendedTy;
4544 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4545 StringRef Name = UserTy->getDecl()->getName();
4546 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4547 .Case("NSInteger", Context.LongTy)
4548 .Case("NSUInteger", Context.UnsignedLongTy)
4549 .Case("SInt32", Context.IntTy)
4550 .Case("UInt32", Context.UnsignedIntTy)
4551 .Default(QualType());
4552
4553 if (!CastTy.isNull())
4554 return std::make_pair(CastTy, Name);
4555
4556 TyTy = UserTy->desugar();
4557 }
4558
4559 // Strip parens if necessary.
4560 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4561 return shouldNotPrintDirectly(Context,
4562 PE->getSubExpr()->getType(),
4563 PE->getSubExpr());
4564
4565 // If this is a conditional expression, then its result type is constructed
4566 // via usual arithmetic conversions and thus there might be no necessary
4567 // typedef sugar there. Recurse to operands to check for NSInteger &
4568 // Co. usage condition.
4569 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4570 QualType TrueTy, FalseTy;
4571 StringRef TrueName, FalseName;
4572
4573 std::tie(TrueTy, TrueName) =
4574 shouldNotPrintDirectly(Context,
4575 CO->getTrueExpr()->getType(),
4576 CO->getTrueExpr());
4577 std::tie(FalseTy, FalseName) =
4578 shouldNotPrintDirectly(Context,
4579 CO->getFalseExpr()->getType(),
4580 CO->getFalseExpr());
4581
4582 if (TrueTy == FalseTy)
4583 return std::make_pair(TrueTy, TrueName);
4584 else if (TrueTy.isNull())
4585 return std::make_pair(FalseTy, FalseName);
4586 else if (FalseTy.isNull())
4587 return std::make_pair(TrueTy, TrueName);
4588 }
4589
4590 return std::make_pair(QualType(), StringRef());
4591}
4592
Richard Smith55ce3522012-06-25 20:30:08 +00004593bool
4594CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4595 const char *StartSpecifier,
4596 unsigned SpecifierLen,
4597 const Expr *E) {
4598 using namespace analyze_format_string;
4599 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004600 // Now type check the data expression that matches the
4601 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004602 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4603 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004604 if (!AT.isValid())
4605 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004606
Jordan Rose598ec092012-12-05 18:44:40 +00004607 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004608 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4609 ExprTy = TET->getUnderlyingExpr()->getType();
4610 }
4611
Seth Cantrellb4802962015-03-04 03:12:10 +00004612 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4613
4614 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004615 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004616 }
Jordan Rose98709982012-06-04 22:48:57 +00004617
Jordan Rose22b74712012-09-05 22:56:19 +00004618 // Look through argument promotions for our error message's reported type.
4619 // This includes the integral and floating promotions, but excludes array
4620 // and function pointer decay; seeing that an argument intended to be a
4621 // string has type 'char [6]' is probably more confusing than 'char *'.
4622 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4623 if (ICE->getCastKind() == CK_IntegralCast ||
4624 ICE->getCastKind() == CK_FloatingCast) {
4625 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004626 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004627
4628 // Check if we didn't match because of an implicit cast from a 'char'
4629 // or 'short' to an 'int'. This is done because printf is a varargs
4630 // function.
4631 if (ICE->getType() == S.Context.IntTy ||
4632 ICE->getType() == S.Context.UnsignedIntTy) {
4633 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004634 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004635 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004636 }
Jordan Rose98709982012-06-04 22:48:57 +00004637 }
Jordan Rose598ec092012-12-05 18:44:40 +00004638 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4639 // Special case for 'a', which has type 'int' in C.
4640 // Note, however, that we do /not/ want to treat multibyte constants like
4641 // 'MooV' as characters! This form is deprecated but still exists.
4642 if (ExprTy == S.Context.IntTy)
4643 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4644 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004645 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004646
Jordan Rosebc53ed12014-05-31 04:12:14 +00004647 // Look through enums to their underlying type.
4648 bool IsEnum = false;
4649 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4650 ExprTy = EnumTy->getDecl()->getIntegerType();
4651 IsEnum = true;
4652 }
4653
Jordan Rose0e5badd2012-12-05 18:44:49 +00004654 // %C in an Objective-C context prints a unichar, not a wchar_t.
4655 // If the argument is an integer of some kind, believe the %C and suggest
4656 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004657 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004658 if (ObjCContext &&
4659 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4660 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4661 !ExprTy->isCharType()) {
4662 // 'unichar' is defined as a typedef of unsigned short, but we should
4663 // prefer using the typedef if it is visible.
4664 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004665
4666 // While we are here, check if the value is an IntegerLiteral that happens
4667 // to be within the valid range.
4668 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4669 const llvm::APInt &V = IL->getValue();
4670 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4671 return true;
4672 }
4673
Jordan Rose0e5badd2012-12-05 18:44:49 +00004674 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4675 Sema::LookupOrdinaryName);
4676 if (S.LookupName(Result, S.getCurScope())) {
4677 NamedDecl *ND = Result.getFoundDecl();
4678 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4679 if (TD->getUnderlyingType() == IntendedTy)
4680 IntendedTy = S.Context.getTypedefType(TD);
4681 }
4682 }
4683 }
4684
4685 // Special-case some of Darwin's platform-independence types by suggesting
4686 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004687 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004688 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004689 QualType CastTy;
4690 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4691 if (!CastTy.isNull()) {
4692 IntendedTy = CastTy;
4693 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004694 }
4695 }
4696
Jordan Rose22b74712012-09-05 22:56:19 +00004697 // We may be able to offer a FixItHint if it is a supported type.
4698 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004699 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004700 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004701
Jordan Rose22b74712012-09-05 22:56:19 +00004702 if (success) {
4703 // Get the fix string from the fixed format specifier
4704 SmallString<16> buf;
4705 llvm::raw_svector_ostream os(buf);
4706 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004707
Jordan Roseaee34382012-09-05 22:56:26 +00004708 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4709
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004710 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004711 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4712 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4713 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4714 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004715 // In this case, the specifier is wrong and should be changed to match
4716 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004717 EmitFormatDiagnostic(S.PDiag(diag)
4718 << AT.getRepresentativeTypeName(S.Context)
4719 << IntendedTy << IsEnum << E->getSourceRange(),
4720 E->getLocStart(),
4721 /*IsStringLocation*/ false, SpecRange,
4722 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004723 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004724 // The canonical type for formatting this value is different from the
4725 // actual type of the expression. (This occurs, for example, with Darwin's
4726 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4727 // should be printed as 'long' for 64-bit compatibility.)
4728 // Rather than emitting a normal format/argument mismatch, we want to
4729 // add a cast to the recommended type (and correct the format string
4730 // if necessary).
4731 SmallString<16> CastBuf;
4732 llvm::raw_svector_ostream CastFix(CastBuf);
4733 CastFix << "(";
4734 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4735 CastFix << ")";
4736
4737 SmallVector<FixItHint,4> Hints;
4738 if (!AT.matchesType(S.Context, IntendedTy))
4739 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4740
4741 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4742 // If there's already a cast present, just replace it.
4743 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4744 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4745
4746 } else if (!requiresParensToAddCast(E)) {
4747 // If the expression has high enough precedence,
4748 // just write the C-style cast.
4749 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4750 CastFix.str()));
4751 } else {
4752 // Otherwise, add parens around the expression as well as the cast.
4753 CastFix << "(";
4754 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4755 CastFix.str()));
4756
Alp Tokerb6cc5922014-05-03 03:45:55 +00004757 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004758 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4759 }
4760
Jordan Rose0e5badd2012-12-05 18:44:49 +00004761 if (ShouldNotPrintDirectly) {
4762 // The expression has a type that should not be printed directly.
4763 // We extract the name from the typedef because we don't want to show
4764 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004765 StringRef Name;
4766 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4767 Name = TypedefTy->getDecl()->getName();
4768 else
4769 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004770 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004771 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004772 << E->getSourceRange(),
4773 E->getLocStart(), /*IsStringLocation=*/false,
4774 SpecRange, Hints);
4775 } else {
4776 // In this case, the expression could be printed using a different
4777 // specifier, but we've decided that the specifier is probably correct
4778 // and we should cast instead. Just use the normal warning message.
4779 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004780 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4781 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004782 << E->getSourceRange(),
4783 E->getLocStart(), /*IsStringLocation*/false,
4784 SpecRange, Hints);
4785 }
Jordan Roseaee34382012-09-05 22:56:26 +00004786 }
Jordan Rose22b74712012-09-05 22:56:19 +00004787 } else {
4788 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4789 SpecifierLen);
4790 // Since the warning for passing non-POD types to variadic functions
4791 // was deferred until now, we emit a warning for non-POD
4792 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004793 switch (S.isValidVarArgType(ExprTy)) {
4794 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004795 case Sema::VAK_ValidInCXX11: {
4796 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4797 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4798 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4799 }
Richard Smithd7293d72013-08-05 18:49:43 +00004800
Seth Cantrellb4802962015-03-04 03:12:10 +00004801 EmitFormatDiagnostic(
4802 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4803 << IsEnum << CSR << E->getSourceRange(),
4804 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4805 break;
4806 }
Richard Smithd7293d72013-08-05 18:49:43 +00004807 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004808 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004809 EmitFormatDiagnostic(
4810 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004811 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004812 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004813 << CallType
4814 << AT.getRepresentativeTypeName(S.Context)
4815 << CSR
4816 << E->getSourceRange(),
4817 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004818 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004819 break;
4820
4821 case Sema::VAK_Invalid:
4822 if (ExprTy->isObjCObjectType())
4823 EmitFormatDiagnostic(
4824 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4825 << S.getLangOpts().CPlusPlus11
4826 << ExprTy
4827 << CallType
4828 << AT.getRepresentativeTypeName(S.Context)
4829 << CSR
4830 << E->getSourceRange(),
4831 E->getLocStart(), /*IsStringLocation*/false, CSR);
4832 else
4833 // FIXME: If this is an initializer list, suggest removing the braces
4834 // or inserting a cast to the target type.
4835 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4836 << isa<InitListExpr>(E) << ExprTy << CallType
4837 << AT.getRepresentativeTypeName(S.Context)
4838 << E->getSourceRange();
4839 break;
4840 }
4841
4842 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4843 "format string specifier index out of range");
4844 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004845 }
4846
Ted Kremenekab278de2010-01-28 23:39:18 +00004847 return true;
4848}
4849
Ted Kremenek02087932010-07-16 02:11:22 +00004850//===--- CHECK: Scanf format string checking ------------------------------===//
4851
4852namespace {
4853class CheckScanfHandler : public CheckFormatHandler {
4854public:
4855 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4856 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004857 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004858 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004859 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004860 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004861 llvm::SmallBitVector &CheckedVarArgs,
4862 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004863 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4864 numDataArgs, beg, hasVAListArg,
4865 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004866 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004867 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004868
4869 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4870 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004871 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004872
4873 bool HandleInvalidScanfConversionSpecifier(
4874 const analyze_scanf::ScanfSpecifier &FS,
4875 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004876 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004877
Craig Toppere14c0f82014-03-12 04:55:44 +00004878 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004879};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004880} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004881
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004882void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4883 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004884 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4885 getLocationOfByte(end), /*IsStringLocation*/true,
4886 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004887}
4888
Ted Kremenekce815422010-07-19 21:25:57 +00004889bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4890 const analyze_scanf::ScanfSpecifier &FS,
4891 const char *startSpecifier,
4892 unsigned specifierLen) {
4893
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004894 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004895 FS.getConversionSpecifier();
4896
4897 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4898 getLocationOfByte(CS.getStart()),
4899 startSpecifier, specifierLen,
4900 CS.getStart(), CS.getLength());
4901}
4902
Ted Kremenek02087932010-07-16 02:11:22 +00004903bool CheckScanfHandler::HandleScanfSpecifier(
4904 const analyze_scanf::ScanfSpecifier &FS,
4905 const char *startSpecifier,
4906 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00004907 using namespace analyze_scanf;
4908 using namespace analyze_format_string;
4909
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004910 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004911
Ted Kremenek6cd69422010-07-19 22:01:06 +00004912 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4913 // be used to decide if we are using positional arguments consistently.
4914 if (FS.consumesDataArgument()) {
4915 if (atFirstArg) {
4916 atFirstArg = false;
4917 usesPositionalArgs = FS.usesPositionalArg();
4918 }
4919 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004920 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4921 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004922 return false;
4923 }
Ted Kremenek02087932010-07-16 02:11:22 +00004924 }
4925
4926 // Check if the field with is non-zero.
4927 const OptionalAmount &Amt = FS.getFieldWidth();
4928 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4929 if (Amt.getConstantAmount() == 0) {
4930 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4931 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004932 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4933 getLocationOfByte(Amt.getStart()),
4934 /*IsStringLocation*/true, R,
4935 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004936 }
4937 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004938
Ted Kremenek02087932010-07-16 02:11:22 +00004939 if (!FS.consumesDataArgument()) {
4940 // FIXME: Technically specifying a precision or field width here
4941 // makes no sense. Worth issuing a warning at some point.
4942 return true;
4943 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004944
Ted Kremenek02087932010-07-16 02:11:22 +00004945 // Consume the argument.
4946 unsigned argIndex = FS.getArgIndex();
4947 if (argIndex < NumDataArgs) {
4948 // The check to see if the argIndex is valid will come later.
4949 // We set the bit here because we may exit early from this
4950 // function if we encounter some other error.
4951 CoveredArgs.set(argIndex);
4952 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004953
Ted Kremenek4407ea42010-07-20 20:04:47 +00004954 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004955 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004956 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4957 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004958 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004959 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004960 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004961 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4962 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004963
Jordan Rose92303592012-09-08 04:00:03 +00004964 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4965 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4966
Ted Kremenek02087932010-07-16 02:11:22 +00004967 // The remaining checks depend on the data arguments.
4968 if (HasVAListArg)
4969 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004970
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004971 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004972 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004973
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004974 // Check that the argument type matches the format specifier.
4975 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004976 if (!Ex)
4977 return true;
4978
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004979 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004980
4981 if (!AT.isValid()) {
4982 return true;
4983 }
4984
Seth Cantrellb4802962015-03-04 03:12:10 +00004985 analyze_format_string::ArgType::MatchKind match =
4986 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004987 if (match == analyze_format_string::ArgType::Match) {
4988 return true;
4989 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004990
Seth Cantrell79340072015-03-04 05:58:08 +00004991 ScanfSpecifier fixedFS = FS;
4992 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4993 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004994
Seth Cantrell79340072015-03-04 05:58:08 +00004995 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4996 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4997 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4998 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004999
Seth Cantrell79340072015-03-04 05:58:08 +00005000 if (success) {
5001 // Get the fix string from the fixed format specifier.
5002 SmallString<128> buf;
5003 llvm::raw_svector_ostream os(buf);
5004 fixedFS.toString(os);
5005
5006 EmitFormatDiagnostic(
5007 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5008 << Ex->getType() << false << Ex->getSourceRange(),
5009 Ex->getLocStart(),
5010 /*IsStringLocation*/ false,
5011 getSpecifierRange(startSpecifier, specifierLen),
5012 FixItHint::CreateReplacement(
5013 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5014 } else {
5015 EmitFormatDiagnostic(S.PDiag(diag)
5016 << AT.getRepresentativeTypeName(S.Context)
5017 << Ex->getType() << false << Ex->getSourceRange(),
5018 Ex->getLocStart(),
5019 /*IsStringLocation*/ false,
5020 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005021 }
5022
Ted Kremenek02087932010-07-16 02:11:22 +00005023 return true;
5024}
5025
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005026static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5027 const Expr *OrigFormatExpr,
5028 ArrayRef<const Expr *> Args,
5029 bool HasVAListArg, unsigned format_idx,
5030 unsigned firstDataArg,
5031 Sema::FormatStringType Type,
5032 bool inFunctionCall,
5033 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005034 llvm::SmallBitVector &CheckedVarArgs,
5035 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005036 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005037 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005038 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005039 S, inFunctionCall, Args[format_idx],
5040 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005041 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005042 return;
5043 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005044
Ted Kremenekab278de2010-01-28 23:39:18 +00005045 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005046 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005047 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005048 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005049 const ConstantArrayType *T =
5050 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005051 assert(T && "String literal not of constant array type!");
5052 size_t TypeSize = T->getSize().getZExtValue();
5053 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005054 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005055
5056 // Emit a warning if the string literal is truncated and does not contain an
5057 // embedded null character.
5058 if (TypeSize <= StrRef.size() &&
5059 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5060 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005061 S, inFunctionCall, Args[format_idx],
5062 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005063 FExpr->getLocStart(),
5064 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5065 return;
5066 }
5067
Ted Kremenekab278de2010-01-28 23:39:18 +00005068 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005069 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005070 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005071 S, inFunctionCall, Args[format_idx],
5072 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005073 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005074 return;
5075 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005076
5077 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5078 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5079 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5080 numDataArgs, (Type == Sema::FST_NSString ||
5081 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005082 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005083 inFunctionCall, CallType, CheckedVarArgs,
5084 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005085
Hans Wennborg23926bd2011-12-15 10:25:47 +00005086 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005087 S.getLangOpts(),
5088 S.Context.getTargetInfo(),
5089 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005090 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005091 } else if (Type == Sema::FST_Scanf) {
5092 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005093 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005094 inFunctionCall, CallType, CheckedVarArgs,
5095 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005096
Hans Wennborg23926bd2011-12-15 10:25:47 +00005097 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005098 S.getLangOpts(),
5099 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005100 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005101 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005102}
5103
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005104bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5105 // Str - The format string. NOTE: this is NOT null-terminated!
5106 StringRef StrRef = FExpr->getString();
5107 const char *Str = StrRef.data();
5108 // Account for cases where the string literal is truncated in a declaration.
5109 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5110 assert(T && "String literal not of constant array type!");
5111 size_t TypeSize = T->getSize().getZExtValue();
5112 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5113 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5114 getLangOpts(),
5115 Context.getTargetInfo());
5116}
5117
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005118//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5119
5120// Returns the related absolute value function that is larger, of 0 if one
5121// does not exist.
5122static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5123 switch (AbsFunction) {
5124 default:
5125 return 0;
5126
5127 case Builtin::BI__builtin_abs:
5128 return Builtin::BI__builtin_labs;
5129 case Builtin::BI__builtin_labs:
5130 return Builtin::BI__builtin_llabs;
5131 case Builtin::BI__builtin_llabs:
5132 return 0;
5133
5134 case Builtin::BI__builtin_fabsf:
5135 return Builtin::BI__builtin_fabs;
5136 case Builtin::BI__builtin_fabs:
5137 return Builtin::BI__builtin_fabsl;
5138 case Builtin::BI__builtin_fabsl:
5139 return 0;
5140
5141 case Builtin::BI__builtin_cabsf:
5142 return Builtin::BI__builtin_cabs;
5143 case Builtin::BI__builtin_cabs:
5144 return Builtin::BI__builtin_cabsl;
5145 case Builtin::BI__builtin_cabsl:
5146 return 0;
5147
5148 case Builtin::BIabs:
5149 return Builtin::BIlabs;
5150 case Builtin::BIlabs:
5151 return Builtin::BIllabs;
5152 case Builtin::BIllabs:
5153 return 0;
5154
5155 case Builtin::BIfabsf:
5156 return Builtin::BIfabs;
5157 case Builtin::BIfabs:
5158 return Builtin::BIfabsl;
5159 case Builtin::BIfabsl:
5160 return 0;
5161
5162 case Builtin::BIcabsf:
5163 return Builtin::BIcabs;
5164 case Builtin::BIcabs:
5165 return Builtin::BIcabsl;
5166 case Builtin::BIcabsl:
5167 return 0;
5168 }
5169}
5170
5171// Returns the argument type of the absolute value function.
5172static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5173 unsigned AbsType) {
5174 if (AbsType == 0)
5175 return QualType();
5176
5177 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5178 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5179 if (Error != ASTContext::GE_None)
5180 return QualType();
5181
5182 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5183 if (!FT)
5184 return QualType();
5185
5186 if (FT->getNumParams() != 1)
5187 return QualType();
5188
5189 return FT->getParamType(0);
5190}
5191
5192// Returns the best absolute value function, or zero, based on type and
5193// current absolute value function.
5194static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5195 unsigned AbsFunctionKind) {
5196 unsigned BestKind = 0;
5197 uint64_t ArgSize = Context.getTypeSize(ArgType);
5198 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5199 Kind = getLargerAbsoluteValueFunction(Kind)) {
5200 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5201 if (Context.getTypeSize(ParamType) >= ArgSize) {
5202 if (BestKind == 0)
5203 BestKind = Kind;
5204 else if (Context.hasSameType(ParamType, ArgType)) {
5205 BestKind = Kind;
5206 break;
5207 }
5208 }
5209 }
5210 return BestKind;
5211}
5212
5213enum AbsoluteValueKind {
5214 AVK_Integer,
5215 AVK_Floating,
5216 AVK_Complex
5217};
5218
5219static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5220 if (T->isIntegralOrEnumerationType())
5221 return AVK_Integer;
5222 if (T->isRealFloatingType())
5223 return AVK_Floating;
5224 if (T->isAnyComplexType())
5225 return AVK_Complex;
5226
5227 llvm_unreachable("Type not integer, floating, or complex");
5228}
5229
5230// Changes the absolute value function to a different type. Preserves whether
5231// the function is a builtin.
5232static unsigned changeAbsFunction(unsigned AbsKind,
5233 AbsoluteValueKind ValueKind) {
5234 switch (ValueKind) {
5235 case AVK_Integer:
5236 switch (AbsKind) {
5237 default:
5238 return 0;
5239 case Builtin::BI__builtin_fabsf:
5240 case Builtin::BI__builtin_fabs:
5241 case Builtin::BI__builtin_fabsl:
5242 case Builtin::BI__builtin_cabsf:
5243 case Builtin::BI__builtin_cabs:
5244 case Builtin::BI__builtin_cabsl:
5245 return Builtin::BI__builtin_abs;
5246 case Builtin::BIfabsf:
5247 case Builtin::BIfabs:
5248 case Builtin::BIfabsl:
5249 case Builtin::BIcabsf:
5250 case Builtin::BIcabs:
5251 case Builtin::BIcabsl:
5252 return Builtin::BIabs;
5253 }
5254 case AVK_Floating:
5255 switch (AbsKind) {
5256 default:
5257 return 0;
5258 case Builtin::BI__builtin_abs:
5259 case Builtin::BI__builtin_labs:
5260 case Builtin::BI__builtin_llabs:
5261 case Builtin::BI__builtin_cabsf:
5262 case Builtin::BI__builtin_cabs:
5263 case Builtin::BI__builtin_cabsl:
5264 return Builtin::BI__builtin_fabsf;
5265 case Builtin::BIabs:
5266 case Builtin::BIlabs:
5267 case Builtin::BIllabs:
5268 case Builtin::BIcabsf:
5269 case Builtin::BIcabs:
5270 case Builtin::BIcabsl:
5271 return Builtin::BIfabsf;
5272 }
5273 case AVK_Complex:
5274 switch (AbsKind) {
5275 default:
5276 return 0;
5277 case Builtin::BI__builtin_abs:
5278 case Builtin::BI__builtin_labs:
5279 case Builtin::BI__builtin_llabs:
5280 case Builtin::BI__builtin_fabsf:
5281 case Builtin::BI__builtin_fabs:
5282 case Builtin::BI__builtin_fabsl:
5283 return Builtin::BI__builtin_cabsf;
5284 case Builtin::BIabs:
5285 case Builtin::BIlabs:
5286 case Builtin::BIllabs:
5287 case Builtin::BIfabsf:
5288 case Builtin::BIfabs:
5289 case Builtin::BIfabsl:
5290 return Builtin::BIcabsf;
5291 }
5292 }
5293 llvm_unreachable("Unable to convert function");
5294}
5295
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005296static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005297 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5298 if (!FnInfo)
5299 return 0;
5300
5301 switch (FDecl->getBuiltinID()) {
5302 default:
5303 return 0;
5304 case Builtin::BI__builtin_abs:
5305 case Builtin::BI__builtin_fabs:
5306 case Builtin::BI__builtin_fabsf:
5307 case Builtin::BI__builtin_fabsl:
5308 case Builtin::BI__builtin_labs:
5309 case Builtin::BI__builtin_llabs:
5310 case Builtin::BI__builtin_cabs:
5311 case Builtin::BI__builtin_cabsf:
5312 case Builtin::BI__builtin_cabsl:
5313 case Builtin::BIabs:
5314 case Builtin::BIlabs:
5315 case Builtin::BIllabs:
5316 case Builtin::BIfabs:
5317 case Builtin::BIfabsf:
5318 case Builtin::BIfabsl:
5319 case Builtin::BIcabs:
5320 case Builtin::BIcabsf:
5321 case Builtin::BIcabsl:
5322 return FDecl->getBuiltinID();
5323 }
5324 llvm_unreachable("Unknown Builtin type");
5325}
5326
5327// If the replacement is valid, emit a note with replacement function.
5328// Additionally, suggest including the proper header if not already included.
5329static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005330 unsigned AbsKind, QualType ArgType) {
5331 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005332 const char *HeaderName = nullptr;
5333 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005334 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5335 FunctionName = "std::abs";
5336 if (ArgType->isIntegralOrEnumerationType()) {
5337 HeaderName = "cstdlib";
5338 } else if (ArgType->isRealFloatingType()) {
5339 HeaderName = "cmath";
5340 } else {
5341 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005342 }
Richard Trieubeffb832014-04-15 23:47:53 +00005343
5344 // Lookup all std::abs
5345 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005346 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005347 R.suppressDiagnostics();
5348 S.LookupQualifiedName(R, Std);
5349
5350 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005351 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005352 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5353 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5354 } else {
5355 FDecl = dyn_cast<FunctionDecl>(I);
5356 }
5357 if (!FDecl)
5358 continue;
5359
5360 // Found std::abs(), check that they are the right ones.
5361 if (FDecl->getNumParams() != 1)
5362 continue;
5363
5364 // Check that the parameter type can handle the argument.
5365 QualType ParamType = FDecl->getParamDecl(0)->getType();
5366 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5367 S.Context.getTypeSize(ArgType) <=
5368 S.Context.getTypeSize(ParamType)) {
5369 // Found a function, don't need the header hint.
5370 EmitHeaderHint = false;
5371 break;
5372 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005373 }
Richard Trieubeffb832014-04-15 23:47:53 +00005374 }
5375 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005376 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005377 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5378
5379 if (HeaderName) {
5380 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5381 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5382 R.suppressDiagnostics();
5383 S.LookupName(R, S.getCurScope());
5384
5385 if (R.isSingleResult()) {
5386 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5387 if (FD && FD->getBuiltinID() == AbsKind) {
5388 EmitHeaderHint = false;
5389 } else {
5390 return;
5391 }
5392 } else if (!R.empty()) {
5393 return;
5394 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005395 }
5396 }
5397
5398 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005399 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005400
Richard Trieubeffb832014-04-15 23:47:53 +00005401 if (!HeaderName)
5402 return;
5403
5404 if (!EmitHeaderHint)
5405 return;
5406
Alp Toker5d96e0a2014-07-11 20:53:51 +00005407 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5408 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005409}
5410
5411static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5412 if (!FDecl)
5413 return false;
5414
5415 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5416 return false;
5417
5418 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5419
5420 while (ND && ND->isInlineNamespace()) {
5421 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005422 }
Richard Trieubeffb832014-04-15 23:47:53 +00005423
5424 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5425 return false;
5426
5427 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5428 return false;
5429
5430 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005431}
5432
5433// Warn when using the wrong abs() function.
5434void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5435 const FunctionDecl *FDecl,
5436 IdentifierInfo *FnInfo) {
5437 if (Call->getNumArgs() != 1)
5438 return;
5439
5440 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005441 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5442 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005443 return;
5444
5445 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5446 QualType ParamType = Call->getArg(0)->getType();
5447
Alp Toker5d96e0a2014-07-11 20:53:51 +00005448 // Unsigned types cannot be negative. Suggest removing the absolute value
5449 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005450 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005451 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005452 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005453 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5454 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005455 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005456 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5457 return;
5458 }
5459
David Majnemer7f77eb92015-11-15 03:04:34 +00005460 // Taking the absolute value of a pointer is very suspicious, they probably
5461 // wanted to index into an array, dereference a pointer, call a function, etc.
5462 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5463 unsigned DiagType = 0;
5464 if (ArgType->isFunctionType())
5465 DiagType = 1;
5466 else if (ArgType->isArrayType())
5467 DiagType = 2;
5468
5469 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5470 return;
5471 }
5472
Richard Trieubeffb832014-04-15 23:47:53 +00005473 // std::abs has overloads which prevent most of the absolute value problems
5474 // from occurring.
5475 if (IsStdAbs)
5476 return;
5477
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005478 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5479 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5480
5481 // The argument and parameter are the same kind. Check if they are the right
5482 // size.
5483 if (ArgValueKind == ParamValueKind) {
5484 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5485 return;
5486
5487 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5488 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5489 << FDecl << ArgType << ParamType;
5490
5491 if (NewAbsKind == 0)
5492 return;
5493
5494 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005495 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005496 return;
5497 }
5498
5499 // ArgValueKind != ParamValueKind
5500 // The wrong type of absolute value function was used. Attempt to find the
5501 // proper one.
5502 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5503 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5504 if (NewAbsKind == 0)
5505 return;
5506
5507 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5508 << FDecl << ParamValueKind << ArgValueKind;
5509
5510 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005511 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005512}
5513
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005514//===--- CHECK: Standard memory functions ---------------------------------===//
5515
Nico Weber0e6daef2013-12-26 23:38:39 +00005516/// \brief Takes the expression passed to the size_t parameter of functions
5517/// such as memcmp, strncat, etc and warns if it's a comparison.
5518///
5519/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5520static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5521 IdentifierInfo *FnName,
5522 SourceLocation FnLoc,
5523 SourceLocation RParenLoc) {
5524 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5525 if (!Size)
5526 return false;
5527
5528 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5529 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5530 return false;
5531
Nico Weber0e6daef2013-12-26 23:38:39 +00005532 SourceRange SizeRange = Size->getSourceRange();
5533 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5534 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005535 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005536 << FnName << FixItHint::CreateInsertion(
5537 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005538 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005539 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005540 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005541 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5542 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005543
5544 return true;
5545}
5546
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005547/// \brief Determine whether the given type is or contains a dynamic class type
5548/// (e.g., whether it has a vtable).
5549static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5550 bool &IsContained) {
5551 // Look through array types while ignoring qualifiers.
5552 const Type *Ty = T->getBaseElementTypeUnsafe();
5553 IsContained = false;
5554
5555 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5556 RD = RD ? RD->getDefinition() : nullptr;
5557 if (!RD)
5558 return nullptr;
5559
5560 if (RD->isDynamicClass())
5561 return RD;
5562
5563 // Check all the fields. If any bases were dynamic, the class is dynamic.
5564 // It's impossible for a class to transitively contain itself by value, so
5565 // infinite recursion is impossible.
5566 for (auto *FD : RD->fields()) {
5567 bool SubContained;
5568 if (const CXXRecordDecl *ContainedRD =
5569 getContainedDynamicClass(FD->getType(), SubContained)) {
5570 IsContained = true;
5571 return ContainedRD;
5572 }
5573 }
5574
5575 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005576}
5577
Chandler Carruth889ed862011-06-21 23:04:20 +00005578/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005579/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005580static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005581 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005582 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5583 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5584 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005585
Craig Topperc3ec1492014-05-26 06:22:03 +00005586 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005587}
5588
Chandler Carruth889ed862011-06-21 23:04:20 +00005589/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005590static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005591 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5592 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5593 if (SizeOf->getKind() == clang::UETT_SizeOf)
5594 return SizeOf->getTypeOfArgument();
5595
5596 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005597}
5598
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005599/// \brief Check for dangerous or invalid arguments to memset().
5600///
Chandler Carruthac687262011-06-03 06:23:57 +00005601/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005602/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5603/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005604///
5605/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005606void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005607 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005608 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005609 assert(BId != 0);
5610
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005611 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005612 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005613 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005614 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005615 return;
5616
Anna Zaks22122702012-01-17 00:37:07 +00005617 unsigned LastArg = (BId == Builtin::BImemset ||
5618 BId == Builtin::BIstrndup ? 1 : 2);
5619 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005620 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005621
Nico Weber0e6daef2013-12-26 23:38:39 +00005622 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5623 Call->getLocStart(), Call->getRParenLoc()))
5624 return;
5625
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005626 // We have special checking when the length is a sizeof expression.
5627 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5628 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5629 llvm::FoldingSetNodeID SizeOfArgID;
5630
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005631 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5632 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005633 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005634
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005635 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005636 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005637 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005638 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005639
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005640 // Never warn about void type pointers. This can be used to suppress
5641 // false positives.
5642 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005643 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005644
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005645 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5646 // actually comparing the expressions for equality. Because computing the
5647 // expression IDs can be expensive, we only do this if the diagnostic is
5648 // enabled.
5649 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005650 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5651 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005652 // We only compute IDs for expressions if the warning is enabled, and
5653 // cache the sizeof arg's ID.
5654 if (SizeOfArgID == llvm::FoldingSetNodeID())
5655 SizeOfArg->Profile(SizeOfArgID, Context, true);
5656 llvm::FoldingSetNodeID DestID;
5657 Dest->Profile(DestID, Context, true);
5658 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005659 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5660 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005661 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005662 StringRef ReadableName = FnName->getName();
5663
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005664 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005665 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005666 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005667 if (!PointeeTy->isIncompleteType() &&
5668 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005669 ActionIdx = 2; // If the pointee's size is sizeof(char),
5670 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005671
5672 // If the function is defined as a builtin macro, do not show macro
5673 // expansion.
5674 SourceLocation SL = SizeOfArg->getExprLoc();
5675 SourceRange DSR = Dest->getSourceRange();
5676 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005677 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005678
5679 if (SM.isMacroArgExpansion(SL)) {
5680 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5681 SL = SM.getSpellingLoc(SL);
5682 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5683 SM.getSpellingLoc(DSR.getEnd()));
5684 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5685 SM.getSpellingLoc(SSR.getEnd()));
5686 }
5687
Anna Zaksd08d9152012-05-30 23:14:52 +00005688 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005689 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005690 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005691 << PointeeTy
5692 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005693 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005694 << SSR);
5695 DiagRuntimeBehavior(SL, SizeOfArg,
5696 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5697 << ActionIdx
5698 << SSR);
5699
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005700 break;
5701 }
5702 }
5703
5704 // Also check for cases where the sizeof argument is the exact same
5705 // type as the memory argument, and where it points to a user-defined
5706 // record type.
5707 if (SizeOfArgTy != QualType()) {
5708 if (PointeeTy->isRecordType() &&
5709 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5710 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5711 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5712 << FnName << SizeOfArgTy << ArgIdx
5713 << PointeeTy << Dest->getSourceRange()
5714 << LenExpr->getSourceRange());
5715 break;
5716 }
Nico Weberc5e73862011-06-14 16:14:58 +00005717 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005718 } else if (DestTy->isArrayType()) {
5719 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005720 }
Nico Weberc5e73862011-06-14 16:14:58 +00005721
Nico Weberc44b35e2015-03-21 17:37:46 +00005722 if (PointeeTy == QualType())
5723 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005724
Nico Weberc44b35e2015-03-21 17:37:46 +00005725 // Always complain about dynamic classes.
5726 bool IsContained;
5727 if (const CXXRecordDecl *ContainedRD =
5728 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005729
Nico Weberc44b35e2015-03-21 17:37:46 +00005730 unsigned OperationType = 0;
5731 // "overwritten" if we're warning about the destination for any call
5732 // but memcmp; otherwise a verb appropriate to the call.
5733 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5734 if (BId == Builtin::BImemcpy)
5735 OperationType = 1;
5736 else if(BId == Builtin::BImemmove)
5737 OperationType = 2;
5738 else if (BId == Builtin::BImemcmp)
5739 OperationType = 3;
5740 }
5741
John McCall31168b02011-06-15 23:02:42 +00005742 DiagRuntimeBehavior(
5743 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005744 PDiag(diag::warn_dyn_class_memaccess)
5745 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5746 << FnName << IsContained << ContainedRD << OperationType
5747 << Call->getCallee()->getSourceRange());
5748 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5749 BId != Builtin::BImemset)
5750 DiagRuntimeBehavior(
5751 Dest->getExprLoc(), Dest,
5752 PDiag(diag::warn_arc_object_memaccess)
5753 << ArgIdx << FnName << PointeeTy
5754 << Call->getCallee()->getSourceRange());
5755 else
5756 continue;
5757
5758 DiagRuntimeBehavior(
5759 Dest->getExprLoc(), Dest,
5760 PDiag(diag::note_bad_memaccess_silence)
5761 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5762 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005763 }
5764}
5765
Ted Kremenek6865f772011-08-18 20:55:45 +00005766// A little helper routine: ignore addition and subtraction of integer literals.
5767// This intentionally does not ignore all integer constant expressions because
5768// we don't want to remove sizeof().
5769static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5770 Ex = Ex->IgnoreParenCasts();
5771
5772 for (;;) {
5773 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5774 if (!BO || !BO->isAdditiveOp())
5775 break;
5776
5777 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5778 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5779
5780 if (isa<IntegerLiteral>(RHS))
5781 Ex = LHS;
5782 else if (isa<IntegerLiteral>(LHS))
5783 Ex = RHS;
5784 else
5785 break;
5786 }
5787
5788 return Ex;
5789}
5790
Anna Zaks13b08572012-08-08 21:42:23 +00005791static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5792 ASTContext &Context) {
5793 // Only handle constant-sized or VLAs, but not flexible members.
5794 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5795 // Only issue the FIXIT for arrays of size > 1.
5796 if (CAT->getSize().getSExtValue() <= 1)
5797 return false;
5798 } else if (!Ty->isVariableArrayType()) {
5799 return false;
5800 }
5801 return true;
5802}
5803
Ted Kremenek6865f772011-08-18 20:55:45 +00005804// Warn if the user has made the 'size' argument to strlcpy or strlcat
5805// be the size of the source, instead of the destination.
5806void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5807 IdentifierInfo *FnName) {
5808
5809 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005810 unsigned NumArgs = Call->getNumArgs();
5811 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005812 return;
5813
5814 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5815 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005816 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005817
5818 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5819 Call->getLocStart(), Call->getRParenLoc()))
5820 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005821
5822 // Look for 'strlcpy(dst, x, sizeof(x))'
5823 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5824 CompareWithSrc = Ex;
5825 else {
5826 // Look for 'strlcpy(dst, x, strlen(x))'
5827 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005828 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5829 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005830 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5831 }
5832 }
5833
5834 if (!CompareWithSrc)
5835 return;
5836
5837 // Determine if the argument to sizeof/strlen is equal to the source
5838 // argument. In principle there's all kinds of things you could do
5839 // here, for instance creating an == expression and evaluating it with
5840 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5841 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5842 if (!SrcArgDRE)
5843 return;
5844
5845 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5846 if (!CompareWithSrcDRE ||
5847 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5848 return;
5849
5850 const Expr *OriginalSizeArg = Call->getArg(2);
5851 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5852 << OriginalSizeArg->getSourceRange() << FnName;
5853
5854 // Output a FIXIT hint if the destination is an array (rather than a
5855 // pointer to an array). This could be enhanced to handle some
5856 // pointers if we know the actual size, like if DstArg is 'array+2'
5857 // we could say 'sizeof(array)-2'.
5858 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005859 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005860 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005861
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005862 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005863 llvm::raw_svector_ostream OS(sizeString);
5864 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005865 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005866 OS << ")";
5867
5868 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5869 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5870 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005871}
5872
Anna Zaks314cd092012-02-01 19:08:57 +00005873/// Check if two expressions refer to the same declaration.
5874static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5875 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5876 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5877 return D1->getDecl() == D2->getDecl();
5878 return false;
5879}
5880
5881static const Expr *getStrlenExprArg(const Expr *E) {
5882 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5883 const FunctionDecl *FD = CE->getDirectCallee();
5884 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005885 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005886 return CE->getArg(0)->IgnoreParenCasts();
5887 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005888 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005889}
5890
5891// Warn on anti-patterns as the 'size' argument to strncat.
5892// The correct size argument should look like following:
5893// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5894void Sema::CheckStrncatArguments(const CallExpr *CE,
5895 IdentifierInfo *FnName) {
5896 // Don't crash if the user has the wrong number of arguments.
5897 if (CE->getNumArgs() < 3)
5898 return;
5899 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5900 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5901 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5902
Nico Weber0e6daef2013-12-26 23:38:39 +00005903 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5904 CE->getRParenLoc()))
5905 return;
5906
Anna Zaks314cd092012-02-01 19:08:57 +00005907 // Identify common expressions, which are wrongly used as the size argument
5908 // to strncat and may lead to buffer overflows.
5909 unsigned PatternType = 0;
5910 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5911 // - sizeof(dst)
5912 if (referToTheSameDecl(SizeOfArg, DstArg))
5913 PatternType = 1;
5914 // - sizeof(src)
5915 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5916 PatternType = 2;
5917 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5918 if (BE->getOpcode() == BO_Sub) {
5919 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5920 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5921 // - sizeof(dst) - strlen(dst)
5922 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5923 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5924 PatternType = 1;
5925 // - sizeof(src) - (anything)
5926 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5927 PatternType = 2;
5928 }
5929 }
5930
5931 if (PatternType == 0)
5932 return;
5933
Anna Zaks5069aa32012-02-03 01:27:37 +00005934 // Generate the diagnostic.
5935 SourceLocation SL = LenArg->getLocStart();
5936 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005937 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005938
5939 // If the function is defined as a builtin macro, do not show macro expansion.
5940 if (SM.isMacroArgExpansion(SL)) {
5941 SL = SM.getSpellingLoc(SL);
5942 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5943 SM.getSpellingLoc(SR.getEnd()));
5944 }
5945
Anna Zaks13b08572012-08-08 21:42:23 +00005946 // Check if the destination is an array (rather than a pointer to an array).
5947 QualType DstTy = DstArg->getType();
5948 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5949 Context);
5950 if (!isKnownSizeArray) {
5951 if (PatternType == 1)
5952 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5953 else
5954 Diag(SL, diag::warn_strncat_src_size) << SR;
5955 return;
5956 }
5957
Anna Zaks314cd092012-02-01 19:08:57 +00005958 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005959 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005960 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005961 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005962
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005963 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005964 llvm::raw_svector_ostream OS(sizeString);
5965 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005966 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005967 OS << ") - ";
5968 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005969 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005970 OS << ") - 1";
5971
Anna Zaks5069aa32012-02-03 01:27:37 +00005972 Diag(SL, diag::note_strncat_wrong_size)
5973 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005974}
5975
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005976//===--- CHECK: Return Address of Stack Variable --------------------------===//
5977
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005978static const Expr *EvalVal(const Expr *E,
5979 SmallVectorImpl<const DeclRefExpr *> &refVars,
5980 const Decl *ParentDecl);
5981static const Expr *EvalAddr(const Expr *E,
5982 SmallVectorImpl<const DeclRefExpr *> &refVars,
5983 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005984
5985/// CheckReturnStackAddr - Check if a return statement returns the address
5986/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005987static void
5988CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5989 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005990
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005991 const Expr *stackE = nullptr;
5992 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005993
5994 // Perform checking for returned stack addresses, local blocks,
5995 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005996 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005997 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005998 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005999 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006000 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006001 }
6002
Craig Topperc3ec1492014-05-26 06:22:03 +00006003 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006004 return; // Nothing suspicious was found.
6005
6006 SourceLocation diagLoc;
6007 SourceRange diagRange;
6008 if (refVars.empty()) {
6009 diagLoc = stackE->getLocStart();
6010 diagRange = stackE->getSourceRange();
6011 } else {
6012 // We followed through a reference variable. 'stackE' contains the
6013 // problematic expression but we will warn at the return statement pointing
6014 // at the reference variable. We will later display the "trail" of
6015 // reference variables using notes.
6016 diagLoc = refVars[0]->getLocStart();
6017 diagRange = refVars[0]->getSourceRange();
6018 }
6019
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006020 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6021 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006022 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006023 << DR->getDecl()->getDeclName() << diagRange;
6024 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006025 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006026 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006027 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006028 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00006029 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6030 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006031 }
6032
6033 // Display the "trail" of reference variables that we followed until we
6034 // found the problematic expression using notes.
6035 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006036 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006037 // If this var binds to another reference var, show the range of the next
6038 // var, otherwise the var binds to the problematic expression, in which case
6039 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006040 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6041 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006042 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6043 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006044 }
6045}
6046
6047/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6048/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006049/// to a location on the stack, a local block, an address of a label, or a
6050/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006051/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006052/// encounter a subexpression that (1) clearly does not lead to one of the
6053/// above problematic expressions (2) is something we cannot determine leads to
6054/// a problematic expression based on such local checking.
6055///
6056/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6057/// the expression that they point to. Such variables are added to the
6058/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006059///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006060/// EvalAddr processes expressions that are pointers that are used as
6061/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006062/// At the base case of the recursion is a check for the above problematic
6063/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006064///
6065/// This implementation handles:
6066///
6067/// * pointer-to-pointer casts
6068/// * implicit conversions from array references to pointers
6069/// * taking the address of fields
6070/// * arbitrary interplay between "&" and "*" operators
6071/// * pointer arithmetic from an address of a stack variable
6072/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006073static const Expr *EvalAddr(const Expr *E,
6074 SmallVectorImpl<const DeclRefExpr *> &refVars,
6075 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006076 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006077 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006078
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006079 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006080 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006081 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006082 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006083 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006084
Peter Collingbourne91147592011-04-15 00:35:48 +00006085 E = E->IgnoreParens();
6086
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006087 // Our "symbolic interpreter" is just a dispatch off the currently
6088 // viewed AST node. We then recursively traverse the AST by calling
6089 // EvalAddr and EvalVal appropriately.
6090 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006091 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006092 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006093
Richard Smith40f08eb2014-01-30 22:05:38 +00006094 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006095 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006096 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006097
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006098 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006099 // If this is a reference variable, follow through to the expression that
6100 // it points to.
6101 if (V->hasLocalStorage() &&
6102 V->getType()->isReferenceType() && V->hasInit()) {
6103 // Add the reference variable to the "trail".
6104 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006105 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006106 }
6107
Craig Topperc3ec1492014-05-26 06:22:03 +00006108 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006109 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006110
Chris Lattner934edb22007-12-28 05:31:15 +00006111 case Stmt::UnaryOperatorClass: {
6112 // The only unary operator that make sense to handle here
6113 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006114 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006115
John McCalle3027922010-08-25 11:45:40 +00006116 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006117 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006118 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006119 }
Mike Stump11289f42009-09-09 15:08:12 +00006120
Chris Lattner934edb22007-12-28 05:31:15 +00006121 case Stmt::BinaryOperatorClass: {
6122 // Handle pointer arithmetic. All other binary operators are not valid
6123 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006124 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006125 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006126
John McCalle3027922010-08-25 11:45:40 +00006127 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006128 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006129
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006130 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006131
6132 // Determine which argument is the real pointer base. It could be
6133 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006134 if (!Base->getType()->isPointerType())
6135 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006136
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006137 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006138 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006139 }
Steve Naroff2752a172008-09-10 19:17:48 +00006140
Chris Lattner934edb22007-12-28 05:31:15 +00006141 // For conditional operators we need to see if either the LHS or RHS are
6142 // valid DeclRefExpr*s. If one of them is valid, we return it.
6143 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006144 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006145
Chris Lattner934edb22007-12-28 05:31:15 +00006146 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006147 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006148 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006149 // In C++, we can have a throw-expression, which has 'void' type.
6150 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006151 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006152 return LHS;
6153 }
Chris Lattner934edb22007-12-28 05:31:15 +00006154
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006155 // In C++, we can have a throw-expression, which has 'void' type.
6156 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006157 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006158
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006159 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006160 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006161
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006162 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006163 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006164 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006165 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006166
6167 case Stmt::AddrLabelExprClass:
6168 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006169
John McCall28fc7092011-11-10 05:35:25 +00006170 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006171 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6172 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006173
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006174 // For casts, we need to handle conversions from arrays to
6175 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006176 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006177 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006178 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006179 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006180 case Stmt::CXXStaticCastExprClass:
6181 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006182 case Stmt::CXXConstCastExprClass:
6183 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006184 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006185 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006186 case CK_LValueToRValue:
6187 case CK_NoOp:
6188 case CK_BaseToDerived:
6189 case CK_DerivedToBase:
6190 case CK_UncheckedDerivedToBase:
6191 case CK_Dynamic:
6192 case CK_CPointerToObjCPointerCast:
6193 case CK_BlockPointerToObjCPointerCast:
6194 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006195 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006196
6197 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006198 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006199
Richard Trieudadefde2014-07-02 04:39:38 +00006200 case CK_BitCast:
6201 if (SubExpr->getType()->isAnyPointerType() ||
6202 SubExpr->getType()->isBlockPointerType() ||
6203 SubExpr->getType()->isObjCQualifiedIdType())
6204 return EvalAddr(SubExpr, refVars, ParentDecl);
6205 else
6206 return nullptr;
6207
Eli Friedman8195ad72012-02-23 23:04:32 +00006208 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006209 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006210 }
Chris Lattner934edb22007-12-28 05:31:15 +00006211 }
Mike Stump11289f42009-09-09 15:08:12 +00006212
Douglas Gregorfe314812011-06-21 17:03:29 +00006213 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006214 if (const Expr *Result =
6215 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6216 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006217 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006218 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006219
Chris Lattner934edb22007-12-28 05:31:15 +00006220 // Everything else: we simply don't reason about them.
6221 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006222 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006223 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006224}
Mike Stump11289f42009-09-09 15:08:12 +00006225
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006226/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6227/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006228static const Expr *EvalVal(const Expr *E,
6229 SmallVectorImpl<const DeclRefExpr *> &refVars,
6230 const Decl *ParentDecl) {
6231 do {
6232 // We should only be called for evaluating non-pointer expressions, or
6233 // expressions with a pointer type that are not used as references but
6234 // instead
6235 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006236
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006237 // Our "symbolic interpreter" is just a dispatch off the currently
6238 // viewed AST node. We then recursively traverse the AST by calling
6239 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006240
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006241 E = E->IgnoreParens();
6242 switch (E->getStmtClass()) {
6243 case Stmt::ImplicitCastExprClass: {
6244 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6245 if (IE->getValueKind() == VK_LValue) {
6246 E = IE->getSubExpr();
6247 continue;
6248 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006249 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006250 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006251
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006252 case Stmt::ExprWithCleanupsClass:
6253 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6254 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006255
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006256 case Stmt::DeclRefExprClass: {
6257 // When we hit a DeclRefExpr we are looking at code that refers to a
6258 // variable's name. If it's not a reference variable we check if it has
6259 // local storage within the function, and if so, return the expression.
6260 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6261
6262 // If we leave the immediate function, the lifetime isn't about to end.
6263 if (DR->refersToEnclosingVariableOrCapture())
6264 return nullptr;
6265
6266 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6267 // Check if it refers to itself, e.g. "int& i = i;".
6268 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006269 return DR;
6270
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006271 if (V->hasLocalStorage()) {
6272 if (!V->getType()->isReferenceType())
6273 return DR;
6274
6275 // Reference variable, follow through to the expression that
6276 // it points to.
6277 if (V->hasInit()) {
6278 // Add the reference variable to the "trail".
6279 refVars.push_back(DR);
6280 return EvalVal(V->getInit(), refVars, V);
6281 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006282 }
6283 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006284
6285 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006286 }
Mike Stump11289f42009-09-09 15:08:12 +00006287
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006288 case Stmt::UnaryOperatorClass: {
6289 // The only unary operator that make sense to handle here
6290 // is Deref. All others don't resolve to a "name." This includes
6291 // handling all sorts of rvalues passed to a unary operator.
6292 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006293
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006294 if (U->getOpcode() == UO_Deref)
6295 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006296
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006297 return nullptr;
6298 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006299
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006300 case Stmt::ArraySubscriptExprClass: {
6301 // Array subscripts are potential references to data on the stack. We
6302 // retrieve the DeclRefExpr* for the array variable if it indeed
6303 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006304 const auto *ASE = cast<ArraySubscriptExpr>(E);
6305 if (ASE->isTypeDependent())
6306 return nullptr;
6307 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006308 }
Mike Stump11289f42009-09-09 15:08:12 +00006309
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006310 case Stmt::OMPArraySectionExprClass: {
6311 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6312 ParentDecl);
6313 }
Mike Stump11289f42009-09-09 15:08:12 +00006314
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006315 case Stmt::ConditionalOperatorClass: {
6316 // For conditional operators we need to see if either the LHS or RHS are
6317 // non-NULL Expr's. If one is non-NULL, we return it.
6318 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006319
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006320 // Handle the GNU extension for missing LHS.
6321 if (const Expr *LHSExpr = C->getLHS()) {
6322 // In C++, we can have a throw-expression, which has 'void' type.
6323 if (!LHSExpr->getType()->isVoidType())
6324 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6325 return LHS;
6326 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006327
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006328 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006329 if (C->getRHS()->getType()->isVoidType())
6330 return nullptr;
6331
6332 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006333 }
6334
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006335 // Accesses to members are potential references to data on the stack.
6336 case Stmt::MemberExprClass: {
6337 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006338
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006339 // Check for indirect access. We only want direct field accesses.
6340 if (M->isArrow())
6341 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006342
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006343 // Check whether the member type is itself a reference, in which case
6344 // we're not going to refer to the member, but to what the member refers
6345 // to.
6346 if (M->getMemberDecl()->getType()->isReferenceType())
6347 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006348
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006349 return EvalVal(M->getBase(), refVars, ParentDecl);
6350 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006351
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006352 case Stmt::MaterializeTemporaryExprClass:
6353 if (const Expr *Result =
6354 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6355 refVars, ParentDecl))
6356 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006357 return E;
6358
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006359 default:
6360 // Check that we don't return or take the address of a reference to a
6361 // temporary. This is only useful in C++.
6362 if (!E->isTypeDependent() && E->isRValue())
6363 return E;
6364
6365 // Everything else: we simply don't reason about them.
6366 return nullptr;
6367 }
6368 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006369}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006370
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006371void
6372Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6373 SourceLocation ReturnLoc,
6374 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006375 const AttrVec *Attrs,
6376 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006377 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6378
6379 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006380 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6381 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006382 CheckNonNullExpr(*this, RetValExp))
6383 Diag(ReturnLoc, diag::warn_null_ret)
6384 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006385
6386 // C++11 [basic.stc.dynamic.allocation]p4:
6387 // If an allocation function declared with a non-throwing
6388 // exception-specification fails to allocate storage, it shall return
6389 // a null pointer. Any other allocation function that fails to allocate
6390 // storage shall indicate failure only by throwing an exception [...]
6391 if (FD) {
6392 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6393 if (Op == OO_New || Op == OO_Array_New) {
6394 const FunctionProtoType *Proto
6395 = FD->getType()->castAs<FunctionProtoType>();
6396 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6397 CheckNonNullExpr(*this, RetValExp))
6398 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6399 << FD << getLangOpts().CPlusPlus11;
6400 }
6401 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006402}
6403
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006404//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6405
6406/// Check for comparisons of floating point operands using != and ==.
6407/// Issue a warning if these are no self-comparisons, as they are not likely
6408/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006409void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006410 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6411 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006412
6413 // Special case: check for x == x (which is OK).
6414 // Do not emit warnings for such cases.
6415 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6416 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6417 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006418 return;
Mike Stump11289f42009-09-09 15:08:12 +00006419
Ted Kremenekeda40e22007-11-29 00:59:04 +00006420 // Special case: check for comparisons against literals that can be exactly
6421 // represented by APFloat. In such cases, do not emit a warning. This
6422 // is a heuristic: often comparison against such literals are used to
6423 // detect if a value in a variable has not changed. This clearly can
6424 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006425 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6426 if (FLL->isExact())
6427 return;
6428 } else
6429 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6430 if (FLR->isExact())
6431 return;
Mike Stump11289f42009-09-09 15:08:12 +00006432
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006433 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006434 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006435 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006436 return;
Mike Stump11289f42009-09-09 15:08:12 +00006437
David Blaikie1f4ff152012-07-16 20:47:22 +00006438 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006439 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006440 return;
Mike Stump11289f42009-09-09 15:08:12 +00006441
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006442 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006443 Diag(Loc, diag::warn_floatingpoint_eq)
6444 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006445}
John McCallca01b222010-01-04 23:21:16 +00006446
John McCall70aa5392010-01-06 05:24:50 +00006447//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6448//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006449
John McCall70aa5392010-01-06 05:24:50 +00006450namespace {
John McCallca01b222010-01-04 23:21:16 +00006451
John McCall70aa5392010-01-06 05:24:50 +00006452/// Structure recording the 'active' range of an integer-valued
6453/// expression.
6454struct IntRange {
6455 /// The number of bits active in the int.
6456 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006457
John McCall70aa5392010-01-06 05:24:50 +00006458 /// True if the int is known not to have negative values.
6459 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006460
John McCall70aa5392010-01-06 05:24:50 +00006461 IntRange(unsigned Width, bool NonNegative)
6462 : Width(Width), NonNegative(NonNegative)
6463 {}
John McCallca01b222010-01-04 23:21:16 +00006464
John McCall817d4af2010-11-10 23:38:19 +00006465 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006466 static IntRange forBoolType() {
6467 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006468 }
6469
John McCall817d4af2010-11-10 23:38:19 +00006470 /// Returns the range of an opaque value of the given integral type.
6471 static IntRange forValueOfType(ASTContext &C, QualType T) {
6472 return forValueOfCanonicalType(C,
6473 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006474 }
6475
John McCall817d4af2010-11-10 23:38:19 +00006476 /// Returns the range of an opaque value of a canonical integral type.
6477 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006478 assert(T->isCanonicalUnqualified());
6479
6480 if (const VectorType *VT = dyn_cast<VectorType>(T))
6481 T = VT->getElementType().getTypePtr();
6482 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6483 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006484 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6485 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006486
David Majnemer6a426652013-06-07 22:07:20 +00006487 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006488 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006489 EnumDecl *Enum = ET->getDecl();
6490 if (!Enum->isCompleteDefinition())
6491 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006492
David Majnemer6a426652013-06-07 22:07:20 +00006493 unsigned NumPositive = Enum->getNumPositiveBits();
6494 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006495
David Majnemer6a426652013-06-07 22:07:20 +00006496 if (NumNegative == 0)
6497 return IntRange(NumPositive, true/*NonNegative*/);
6498 else
6499 return IntRange(std::max(NumPositive + 1, NumNegative),
6500 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006501 }
John McCall70aa5392010-01-06 05:24:50 +00006502
6503 const BuiltinType *BT = cast<BuiltinType>(T);
6504 assert(BT->isInteger());
6505
6506 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6507 }
6508
John McCall817d4af2010-11-10 23:38:19 +00006509 /// Returns the "target" range of a canonical integral type, i.e.
6510 /// the range of values expressible in the type.
6511 ///
6512 /// This matches forValueOfCanonicalType except that enums have the
6513 /// full range of their type, not the range of their enumerators.
6514 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6515 assert(T->isCanonicalUnqualified());
6516
6517 if (const VectorType *VT = dyn_cast<VectorType>(T))
6518 T = VT->getElementType().getTypePtr();
6519 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6520 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006521 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6522 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006523 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006524 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006525
6526 const BuiltinType *BT = cast<BuiltinType>(T);
6527 assert(BT->isInteger());
6528
6529 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6530 }
6531
6532 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006533 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006534 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006535 L.NonNegative && R.NonNegative);
6536 }
6537
John McCall817d4af2010-11-10 23:38:19 +00006538 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006539 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006540 return IntRange(std::min(L.Width, R.Width),
6541 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006542 }
6543};
6544
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006545IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006546 if (value.isSigned() && value.isNegative())
6547 return IntRange(value.getMinSignedBits(), false);
6548
6549 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006550 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006551
6552 // isNonNegative() just checks the sign bit without considering
6553 // signedness.
6554 return IntRange(value.getActiveBits(), true);
6555}
6556
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006557IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6558 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006559 if (result.isInt())
6560 return GetValueRange(C, result.getInt(), MaxWidth);
6561
6562 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006563 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6564 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6565 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6566 R = IntRange::join(R, El);
6567 }
John McCall70aa5392010-01-06 05:24:50 +00006568 return R;
6569 }
6570
6571 if (result.isComplexInt()) {
6572 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6573 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6574 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006575 }
6576
6577 // This can happen with lossless casts to intptr_t of "based" lvalues.
6578 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006579 // FIXME: The only reason we need to pass the type in here is to get
6580 // the sign right on this one case. It would be nice if APValue
6581 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006582 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006583 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006584}
John McCall70aa5392010-01-06 05:24:50 +00006585
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006586QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006587 QualType Ty = E->getType();
6588 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6589 Ty = AtomicRHS->getValueType();
6590 return Ty;
6591}
6592
John McCall70aa5392010-01-06 05:24:50 +00006593/// Pseudo-evaluate the given integer expression, estimating the
6594/// range of values it might take.
6595///
6596/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006597IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006598 E = E->IgnoreParens();
6599
6600 // Try a full evaluation first.
6601 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006602 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006603 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006604
6605 // I think we only want to look through implicit casts here; if the
6606 // user has an explicit widening cast, we should treat the value as
6607 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006608 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006609 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006610 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6611
Eli Friedmane6d33952013-07-08 20:20:06 +00006612 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006613
George Burgess IVdf1ed002016-01-13 01:52:39 +00006614 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6615 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00006616
John McCall70aa5392010-01-06 05:24:50 +00006617 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006618 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006619 return OutputTypeRange;
6620
6621 IntRange SubRange
6622 = GetExprRange(C, CE->getSubExpr(),
6623 std::min(MaxWidth, OutputTypeRange.Width));
6624
6625 // Bail out if the subexpr's range is as wide as the cast type.
6626 if (SubRange.Width >= OutputTypeRange.Width)
6627 return OutputTypeRange;
6628
6629 // Otherwise, we take the smaller width, and we're non-negative if
6630 // either the output type or the subexpr is.
6631 return IntRange(SubRange.Width,
6632 SubRange.NonNegative || OutputTypeRange.NonNegative);
6633 }
6634
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006635 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006636 // If we can fold the condition, just take that operand.
6637 bool CondResult;
6638 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6639 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6640 : CO->getFalseExpr(),
6641 MaxWidth);
6642
6643 // Otherwise, conservatively merge.
6644 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6645 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6646 return IntRange::join(L, R);
6647 }
6648
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006649 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006650 switch (BO->getOpcode()) {
6651
6652 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006653 case BO_LAnd:
6654 case BO_LOr:
6655 case BO_LT:
6656 case BO_GT:
6657 case BO_LE:
6658 case BO_GE:
6659 case BO_EQ:
6660 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006661 return IntRange::forBoolType();
6662
John McCallc3688382011-07-13 06:35:24 +00006663 // The type of the assignments is the type of the LHS, so the RHS
6664 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006665 case BO_MulAssign:
6666 case BO_DivAssign:
6667 case BO_RemAssign:
6668 case BO_AddAssign:
6669 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006670 case BO_XorAssign:
6671 case BO_OrAssign:
6672 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006673 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006674
John McCallc3688382011-07-13 06:35:24 +00006675 // Simple assignments just pass through the RHS, which will have
6676 // been coerced to the LHS type.
6677 case BO_Assign:
6678 // TODO: bitfields?
6679 return GetExprRange(C, BO->getRHS(), MaxWidth);
6680
John McCall70aa5392010-01-06 05:24:50 +00006681 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006682 case BO_PtrMemD:
6683 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006684 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006685
John McCall2ce81ad2010-01-06 22:07:33 +00006686 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006687 case BO_And:
6688 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006689 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6690 GetExprRange(C, BO->getRHS(), MaxWidth));
6691
John McCall70aa5392010-01-06 05:24:50 +00006692 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006693 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006694 // ...except that we want to treat '1 << (blah)' as logically
6695 // positive. It's an important idiom.
6696 if (IntegerLiteral *I
6697 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6698 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006699 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006700 return IntRange(R.Width, /*NonNegative*/ true);
6701 }
6702 }
6703 // fallthrough
6704
John McCalle3027922010-08-25 11:45:40 +00006705 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006706 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006707
John McCall2ce81ad2010-01-06 22:07:33 +00006708 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006709 case BO_Shr:
6710 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006711 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6712
6713 // If the shift amount is a positive constant, drop the width by
6714 // that much.
6715 llvm::APSInt shift;
6716 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6717 shift.isNonNegative()) {
6718 unsigned zext = shift.getZExtValue();
6719 if (zext >= L.Width)
6720 L.Width = (L.NonNegative ? 0 : 1);
6721 else
6722 L.Width -= zext;
6723 }
6724
6725 return L;
6726 }
6727
6728 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006729 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006730 return GetExprRange(C, BO->getRHS(), MaxWidth);
6731
John McCall2ce81ad2010-01-06 22:07:33 +00006732 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006733 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006734 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006735 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006736 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006737
John McCall51431812011-07-14 22:39:48 +00006738 // The width of a division result is mostly determined by the size
6739 // of the LHS.
6740 case BO_Div: {
6741 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006742 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006743 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6744
6745 // If the divisor is constant, use that.
6746 llvm::APSInt divisor;
6747 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6748 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6749 if (log2 >= L.Width)
6750 L.Width = (L.NonNegative ? 0 : 1);
6751 else
6752 L.Width = std::min(L.Width - log2, MaxWidth);
6753 return L;
6754 }
6755
6756 // Otherwise, just use the LHS's width.
6757 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6758 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6759 }
6760
6761 // The result of a remainder can't be larger than the result of
6762 // either side.
6763 case BO_Rem: {
6764 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006765 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006766 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6767 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6768
6769 IntRange meet = IntRange::meet(L, R);
6770 meet.Width = std::min(meet.Width, MaxWidth);
6771 return meet;
6772 }
6773
6774 // The default behavior is okay for these.
6775 case BO_Mul:
6776 case BO_Add:
6777 case BO_Xor:
6778 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006779 break;
6780 }
6781
John McCall51431812011-07-14 22:39:48 +00006782 // The default case is to treat the operation as if it were closed
6783 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006784 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6785 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6786 return IntRange::join(L, R);
6787 }
6788
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006789 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006790 switch (UO->getOpcode()) {
6791 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006792 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006793 return IntRange::forBoolType();
6794
6795 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006796 case UO_Deref:
6797 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006798 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006799
6800 default:
6801 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6802 }
6803 }
6804
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006805 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006806 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6807
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006808 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006809 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006810 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006811
Eli Friedmane6d33952013-07-08 20:20:06 +00006812 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006813}
John McCall263a48b2010-01-04 23:31:57 +00006814
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006815IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006816 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006817}
6818
John McCall263a48b2010-01-04 23:31:57 +00006819/// Checks whether the given value, which currently has the given
6820/// source semantics, has the same value when coerced through the
6821/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006822bool IsSameFloatAfterCast(const llvm::APFloat &value,
6823 const llvm::fltSemantics &Src,
6824 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006825 llvm::APFloat truncated = value;
6826
6827 bool ignored;
6828 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6829 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6830
6831 return truncated.bitwiseIsEqual(value);
6832}
6833
6834/// Checks whether the given value, which currently has the given
6835/// source semantics, has the same value when coerced through the
6836/// target semantics.
6837///
6838/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006839bool IsSameFloatAfterCast(const APValue &value,
6840 const llvm::fltSemantics &Src,
6841 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006842 if (value.isFloat())
6843 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6844
6845 if (value.isVector()) {
6846 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6847 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6848 return false;
6849 return true;
6850 }
6851
6852 assert(value.isComplexFloat());
6853 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6854 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6855}
6856
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006857void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006858
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006859bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00006860 // Suppress cases where we are comparing against an enum constant.
6861 if (const DeclRefExpr *DR =
6862 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6863 if (isa<EnumConstantDecl>(DR->getDecl()))
6864 return false;
6865
6866 // Suppress cases where the '0' value is expanded from a macro.
6867 if (E->getLocStart().isMacroID())
6868 return false;
6869
John McCallcc7e5bf2010-05-06 08:58:33 +00006870 llvm::APSInt Value;
6871 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6872}
6873
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006874bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00006875 // Strip off implicit integral promotions.
6876 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006877 if (ICE->getCastKind() != CK_IntegralCast &&
6878 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006879 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006880 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006881 }
6882
6883 return E->getType()->isEnumeralType();
6884}
6885
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006886void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006887 // Disable warning in template instantiations.
6888 if (!S.ActiveTemplateInstantiations.empty())
6889 return;
6890
John McCalle3027922010-08-25 11:45:40 +00006891 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006892 if (E->isValueDependent())
6893 return;
6894
John McCalle3027922010-08-25 11:45:40 +00006895 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006896 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006897 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006898 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006899 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006900 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006901 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006902 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006903 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006904 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006905 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006906 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006907 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006908 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006909 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006910 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6911 }
6912}
6913
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006914void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
6915 Expr *Constant, Expr *Other,
6916 llvm::APSInt Value,
6917 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006918 // Disable warning in template instantiations.
6919 if (!S.ActiveTemplateInstantiations.empty())
6920 return;
6921
Richard Trieu0f097742014-04-04 04:13:47 +00006922 // TODO: Investigate using GetExprRange() to get tighter bounds
6923 // on the bit ranges.
6924 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006925 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006926 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006927 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6928 unsigned OtherWidth = OtherRange.Width;
6929
6930 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6931
Richard Trieu560910c2012-11-14 22:50:24 +00006932 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006933 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006934 return;
6935
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006936 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006937 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006938
Richard Trieu0f097742014-04-04 04:13:47 +00006939 // Used for diagnostic printout.
6940 enum {
6941 LiteralConstant = 0,
6942 CXXBoolLiteralTrue,
6943 CXXBoolLiteralFalse
6944 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006945
Richard Trieu0f097742014-04-04 04:13:47 +00006946 if (!OtherIsBooleanType) {
6947 QualType ConstantT = Constant->getType();
6948 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006949
Richard Trieu0f097742014-04-04 04:13:47 +00006950 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6951 return;
6952 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6953 "comparison with non-integer type");
6954
6955 bool ConstantSigned = ConstantT->isSignedIntegerType();
6956 bool CommonSigned = CommonT->isSignedIntegerType();
6957
6958 bool EqualityOnly = false;
6959
6960 if (CommonSigned) {
6961 // The common type is signed, therefore no signed to unsigned conversion.
6962 if (!OtherRange.NonNegative) {
6963 // Check that the constant is representable in type OtherT.
6964 if (ConstantSigned) {
6965 if (OtherWidth >= Value.getMinSignedBits())
6966 return;
6967 } else { // !ConstantSigned
6968 if (OtherWidth >= Value.getActiveBits() + 1)
6969 return;
6970 }
6971 } else { // !OtherSigned
6972 // Check that the constant is representable in type OtherT.
6973 // Negative values are out of range.
6974 if (ConstantSigned) {
6975 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6976 return;
6977 } else { // !ConstantSigned
6978 if (OtherWidth >= Value.getActiveBits())
6979 return;
6980 }
Richard Trieu560910c2012-11-14 22:50:24 +00006981 }
Richard Trieu0f097742014-04-04 04:13:47 +00006982 } else { // !CommonSigned
6983 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006984 if (OtherWidth >= Value.getActiveBits())
6985 return;
Craig Toppercf360162014-06-18 05:13:11 +00006986 } else { // OtherSigned
6987 assert(!ConstantSigned &&
6988 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006989 // Check to see if the constant is representable in OtherT.
6990 if (OtherWidth > Value.getActiveBits())
6991 return;
6992 // Check to see if the constant is equivalent to a negative value
6993 // cast to CommonT.
6994 if (S.Context.getIntWidth(ConstantT) ==
6995 S.Context.getIntWidth(CommonT) &&
6996 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6997 return;
6998 // The constant value rests between values that OtherT can represent
6999 // after conversion. Relational comparison still works, but equality
7000 // comparisons will be tautological.
7001 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007002 }
7003 }
Richard Trieu0f097742014-04-04 04:13:47 +00007004
7005 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7006
7007 if (op == BO_EQ || op == BO_NE) {
7008 IsTrue = op == BO_NE;
7009 } else if (EqualityOnly) {
7010 return;
7011 } else if (RhsConstant) {
7012 if (op == BO_GT || op == BO_GE)
7013 IsTrue = !PositiveConstant;
7014 else // op == BO_LT || op == BO_LE
7015 IsTrue = PositiveConstant;
7016 } else {
7017 if (op == BO_LT || op == BO_LE)
7018 IsTrue = !PositiveConstant;
7019 else // op == BO_GT || op == BO_GE
7020 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007021 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007022 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007023 // Other isKnownToHaveBooleanValue
7024 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7025 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7026 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7027
7028 static const struct LinkedConditions {
7029 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7030 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7031 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7032 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7033 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7034 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7035
7036 } TruthTable = {
7037 // Constant on LHS. | Constant on RHS. |
7038 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7039 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7040 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7041 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7042 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7043 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7044 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7045 };
7046
7047 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7048
7049 enum ConstantValue ConstVal = Zero;
7050 if (Value.isUnsigned() || Value.isNonNegative()) {
7051 if (Value == 0) {
7052 LiteralOrBoolConstant =
7053 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7054 ConstVal = Zero;
7055 } else if (Value == 1) {
7056 LiteralOrBoolConstant =
7057 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7058 ConstVal = One;
7059 } else {
7060 LiteralOrBoolConstant = LiteralConstant;
7061 ConstVal = GT_One;
7062 }
7063 } else {
7064 ConstVal = LT_Zero;
7065 }
7066
7067 CompareBoolWithConstantResult CmpRes;
7068
7069 switch (op) {
7070 case BO_LT:
7071 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7072 break;
7073 case BO_GT:
7074 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7075 break;
7076 case BO_LE:
7077 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7078 break;
7079 case BO_GE:
7080 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7081 break;
7082 case BO_EQ:
7083 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7084 break;
7085 case BO_NE:
7086 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7087 break;
7088 default:
7089 CmpRes = Unkwn;
7090 break;
7091 }
7092
7093 if (CmpRes == AFals) {
7094 IsTrue = false;
7095 } else if (CmpRes == ATrue) {
7096 IsTrue = true;
7097 } else {
7098 return;
7099 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007100 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007101
7102 // If this is a comparison to an enum constant, include that
7103 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007104 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007105 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7106 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7107
7108 SmallString<64> PrettySourceValue;
7109 llvm::raw_svector_ostream OS(PrettySourceValue);
7110 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007111 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007112 else
7113 OS << Value;
7114
Richard Trieu0f097742014-04-04 04:13:47 +00007115 S.DiagRuntimeBehavior(
7116 E->getOperatorLoc(), E,
7117 S.PDiag(diag::warn_out_of_range_compare)
7118 << OS.str() << LiteralOrBoolConstant
7119 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7120 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007121}
7122
John McCallcc7e5bf2010-05-06 08:58:33 +00007123/// Analyze the operands of the given comparison. Implements the
7124/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007125void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007126 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7127 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007128}
John McCall263a48b2010-01-04 23:31:57 +00007129
John McCallca01b222010-01-04 23:21:16 +00007130/// \brief Implements -Wsign-compare.
7131///
Richard Trieu82402a02011-09-15 21:56:47 +00007132/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007133void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007134 // The type the comparison is being performed in.
7135 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007136
7137 // Only analyze comparison operators where both sides have been converted to
7138 // the same type.
7139 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7140 return AnalyzeImpConvsInComparison(S, E);
7141
7142 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007143 if (E->isValueDependent())
7144 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007145
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007146 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7147 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007148
7149 bool IsComparisonConstant = false;
7150
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007151 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007152 // of 'true' or 'false'.
7153 if (T->isIntegralType(S.Context)) {
7154 llvm::APSInt RHSValue;
7155 bool IsRHSIntegralLiteral =
7156 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7157 llvm::APSInt LHSValue;
7158 bool IsLHSIntegralLiteral =
7159 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7160 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7161 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7162 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7163 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7164 else
7165 IsComparisonConstant =
7166 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007167 } else if (!T->hasUnsignedIntegerRepresentation())
7168 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007169
John McCallcc7e5bf2010-05-06 08:58:33 +00007170 // We don't do anything special if this isn't an unsigned integral
7171 // comparison: we're only interested in integral comparisons, and
7172 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007173 //
7174 // We also don't care about value-dependent expressions or expressions
7175 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007176 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007177 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007178
John McCallcc7e5bf2010-05-06 08:58:33 +00007179 // Check to see if one of the (unmodified) operands is of different
7180 // signedness.
7181 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007182 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7183 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007184 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007185 signedOperand = LHS;
7186 unsignedOperand = RHS;
7187 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7188 signedOperand = RHS;
7189 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007190 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007191 CheckTrivialUnsignedComparison(S, E);
7192 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007193 }
7194
John McCallcc7e5bf2010-05-06 08:58:33 +00007195 // Otherwise, calculate the effective range of the signed operand.
7196 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007197
John McCallcc7e5bf2010-05-06 08:58:33 +00007198 // Go ahead and analyze implicit conversions in the operands. Note
7199 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007200 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7201 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007202
John McCallcc7e5bf2010-05-06 08:58:33 +00007203 // If the signed range is non-negative, -Wsign-compare won't fire,
7204 // but we should still check for comparisons which are always true
7205 // or false.
7206 if (signedRange.NonNegative)
7207 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007208
7209 // For (in)equality comparisons, if the unsigned operand is a
7210 // constant which cannot collide with a overflowed signed operand,
7211 // then reinterpreting the signed operand as unsigned will not
7212 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007213 if (E->isEqualityOp()) {
7214 unsigned comparisonWidth = S.Context.getIntWidth(T);
7215 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007216
John McCallcc7e5bf2010-05-06 08:58:33 +00007217 // We should never be unable to prove that the unsigned operand is
7218 // non-negative.
7219 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7220
7221 if (unsignedRange.Width < comparisonWidth)
7222 return;
7223 }
7224
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007225 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7226 S.PDiag(diag::warn_mixed_sign_comparison)
7227 << LHS->getType() << RHS->getType()
7228 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007229}
7230
John McCall1f425642010-11-11 03:21:53 +00007231/// Analyzes an attempt to assign the given value to a bitfield.
7232///
7233/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007234bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7235 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007236 assert(Bitfield->isBitField());
7237 if (Bitfield->isInvalidDecl())
7238 return false;
7239
John McCalldeebbcf2010-11-11 05:33:51 +00007240 // White-list bool bitfields.
7241 if (Bitfield->getType()->isBooleanType())
7242 return false;
7243
Douglas Gregor789adec2011-02-04 13:09:01 +00007244 // Ignore value- or type-dependent expressions.
7245 if (Bitfield->getBitWidth()->isValueDependent() ||
7246 Bitfield->getBitWidth()->isTypeDependent() ||
7247 Init->isValueDependent() ||
7248 Init->isTypeDependent())
7249 return false;
7250
John McCall1f425642010-11-11 03:21:53 +00007251 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7252
Richard Smith5fab0c92011-12-28 19:48:30 +00007253 llvm::APSInt Value;
7254 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007255 return false;
7256
John McCall1f425642010-11-11 03:21:53 +00007257 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007258 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007259
7260 if (OriginalWidth <= FieldWidth)
7261 return false;
7262
Eli Friedmanc267a322012-01-26 23:11:39 +00007263 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007264 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007265 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007266
Eli Friedmanc267a322012-01-26 23:11:39 +00007267 // Check whether the stored value is equal to the original value.
7268 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007269 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007270 return false;
7271
Eli Friedmanc267a322012-01-26 23:11:39 +00007272 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007273 // therefore don't strictly fit into a signed bitfield of width 1.
7274 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007275 return false;
7276
John McCall1f425642010-11-11 03:21:53 +00007277 std::string PrettyValue = Value.toString(10);
7278 std::string PrettyTrunc = TruncatedValue.toString(10);
7279
7280 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7281 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7282 << Init->getSourceRange();
7283
7284 return true;
7285}
7286
John McCalld2a53122010-11-09 23:24:47 +00007287/// Analyze the given simple or compound assignment for warning-worthy
7288/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007289void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007290 // Just recurse on the LHS.
7291 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7292
7293 // We want to recurse on the RHS as normal unless we're assigning to
7294 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007295 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007296 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007297 E->getOperatorLoc())) {
7298 // Recurse, ignoring any implicit conversions on the RHS.
7299 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7300 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007301 }
7302 }
7303
7304 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7305}
7306
John McCall263a48b2010-01-04 23:31:57 +00007307/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007308void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7309 SourceLocation CContext, unsigned diag,
7310 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007311 if (pruneControlFlow) {
7312 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7313 S.PDiag(diag)
7314 << SourceType << T << E->getSourceRange()
7315 << SourceRange(CContext));
7316 return;
7317 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007318 S.Diag(E->getExprLoc(), diag)
7319 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7320}
7321
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007322/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007323void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7324 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007325 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007326}
7327
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007328/// Diagnose an implicit cast from a literal expression. Does not warn when the
7329/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00007330void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
7331 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007332 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00007333 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007334 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007335 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7336 T->hasUnsignedIntegerRepresentation());
7337 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00007338 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007339 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00007340 return;
7341
Eli Friedman07185912013-08-29 23:44:43 +00007342 // FIXME: Force the precision of the source value down so we don't print
7343 // digits which are usually useless (we don't really care here if we
7344 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7345 // would automatically print the shortest representation, but it's a bit
7346 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007347 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007348 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7349 precision = (precision * 59 + 195) / 196;
7350 Value.toString(PrettySourceValue, precision);
7351
David Blaikie9b88cc02012-05-15 17:18:27 +00007352 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00007353 if (T->isSpecificBuiltinType(BuiltinType::Bool))
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007354 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007355 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007356 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007357
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007358 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00007359 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
7360 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00007361}
7362
John McCall18a2c2c2010-11-09 22:22:12 +00007363std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7364 if (!Range.Width) return "0";
7365
7366 llvm::APSInt ValueInRange = Value;
7367 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007368 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007369 return ValueInRange.toString(10);
7370}
7371
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007372bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007373 if (!isa<ImplicitCastExpr>(Ex))
7374 return false;
7375
7376 Expr *InnerE = Ex->IgnoreParenImpCasts();
7377 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7378 const Type *Source =
7379 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7380 if (Target->isDependentType())
7381 return false;
7382
7383 const BuiltinType *FloatCandidateBT =
7384 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7385 const Type *BoolCandidateType = ToBool ? Target : Source;
7386
7387 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7388 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7389}
7390
7391void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7392 SourceLocation CC) {
7393 unsigned NumArgs = TheCall->getNumArgs();
7394 for (unsigned i = 0; i < NumArgs; ++i) {
7395 Expr *CurrA = TheCall->getArg(i);
7396 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7397 continue;
7398
7399 bool IsSwapped = ((i > 0) &&
7400 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7401 IsSwapped |= ((i < (NumArgs - 1)) &&
7402 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7403 if (IsSwapped) {
7404 // Warn on this floating-point to bool conversion.
7405 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7406 CurrA->getType(), CC,
7407 diag::warn_impcast_floating_point_to_bool);
7408 }
7409 }
7410}
7411
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007412void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007413 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7414 E->getExprLoc()))
7415 return;
7416
Richard Trieu09d6b802016-01-08 23:35:06 +00007417 // Don't warn on functions which have return type nullptr_t.
7418 if (isa<CallExpr>(E))
7419 return;
7420
Richard Trieu5b993502014-10-15 03:42:06 +00007421 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7422 const Expr::NullPointerConstantKind NullKind =
7423 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7424 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7425 return;
7426
7427 // Return if target type is a safe conversion.
7428 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7429 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7430 return;
7431
7432 SourceLocation Loc = E->getSourceRange().getBegin();
7433
Richard Trieu0a5e1662016-02-13 00:58:53 +00007434 // Venture through the macro stacks to get to the source of macro arguments.
7435 // The new location is a better location than the complete location that was
7436 // passed in.
7437 while (S.SourceMgr.isMacroArgExpansion(Loc))
7438 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
7439
7440 while (S.SourceMgr.isMacroArgExpansion(CC))
7441 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
7442
Richard Trieu5b993502014-10-15 03:42:06 +00007443 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00007444 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
7445 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7446 Loc, S.SourceMgr, S.getLangOpts());
7447 if (MacroName == "NULL")
7448 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00007449 }
7450
7451 // Only warn if the null and context location are in the same macro expansion.
7452 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7453 return;
7454
7455 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7456 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7457 << FixItHint::CreateReplacement(Loc,
7458 S.getFixItZeroLiteralForType(T, Loc));
7459}
7460
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007461void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7462 ObjCArrayLiteral *ArrayLiteral);
7463void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7464 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00007465
7466/// Check a single element within a collection literal against the
7467/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007468void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7469 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007470 // Skip a bitcast to 'id' or qualified 'id'.
7471 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7472 if (ICE->getCastKind() == CK_BitCast &&
7473 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7474 Element = ICE->getSubExpr();
7475 }
7476
7477 QualType ElementType = Element->getType();
7478 ExprResult ElementResult(Element);
7479 if (ElementType->getAs<ObjCObjectPointerType>() &&
7480 S.CheckSingleAssignmentConstraints(TargetElementType,
7481 ElementResult,
7482 false, false)
7483 != Sema::Compatible) {
7484 S.Diag(Element->getLocStart(),
7485 diag::warn_objc_collection_literal_element)
7486 << ElementType << ElementKind << TargetElementType
7487 << Element->getSourceRange();
7488 }
7489
7490 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7491 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7492 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7493 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7494}
7495
7496/// Check an Objective-C array literal being converted to the given
7497/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007498void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7499 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007500 if (!S.NSArrayDecl)
7501 return;
7502
7503 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7504 if (!TargetObjCPtr)
7505 return;
7506
7507 if (TargetObjCPtr->isUnspecialized() ||
7508 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7509 != S.NSArrayDecl->getCanonicalDecl())
7510 return;
7511
7512 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7513 if (TypeArgs.size() != 1)
7514 return;
7515
7516 QualType TargetElementType = TypeArgs[0];
7517 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7518 checkObjCCollectionLiteralElement(S, TargetElementType,
7519 ArrayLiteral->getElement(I),
7520 0);
7521 }
7522}
7523
7524/// Check an Objective-C dictionary literal being converted to the given
7525/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007526void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7527 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007528 if (!S.NSDictionaryDecl)
7529 return;
7530
7531 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7532 if (!TargetObjCPtr)
7533 return;
7534
7535 if (TargetObjCPtr->isUnspecialized() ||
7536 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7537 != S.NSDictionaryDecl->getCanonicalDecl())
7538 return;
7539
7540 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7541 if (TypeArgs.size() != 2)
7542 return;
7543
7544 QualType TargetKeyType = TypeArgs[0];
7545 QualType TargetObjectType = TypeArgs[1];
7546 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7547 auto Element = DictionaryLiteral->getKeyValueElement(I);
7548 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7549 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7550 }
7551}
7552
Richard Trieufc404c72016-02-05 23:02:38 +00007553// Helper function to filter out cases for constant width constant conversion.
7554// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007555bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7556 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00007557 // If initializing from a constant, and the constant starts with '0',
7558 // then it is a binary, octal, or hexadecimal. Allow these constants
7559 // to fill all the bits, even if there is a sign change.
7560 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7561 const char FirstLiteralCharacter =
7562 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7563 if (FirstLiteralCharacter == '0')
7564 return false;
7565 }
7566
7567 // If the CC location points to a '{', and the type is char, then assume
7568 // assume it is an array initialization.
7569 if (CC.isValid() && T->isCharType()) {
7570 const char FirstContextCharacter =
7571 S.getSourceManager().getCharacterData(CC)[0];
7572 if (FirstContextCharacter == '{')
7573 return false;
7574 }
7575
7576 return true;
7577}
7578
John McCallcc7e5bf2010-05-06 08:58:33 +00007579void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007580 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007581 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007582
John McCallcc7e5bf2010-05-06 08:58:33 +00007583 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7584 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7585 if (Source == Target) return;
7586 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007587
Chandler Carruthc22845a2011-07-26 05:40:03 +00007588 // If the conversion context location is invalid don't complain. We also
7589 // don't want to emit a warning if the issue occurs from the expansion of
7590 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7591 // delay this check as long as possible. Once we detect we are in that
7592 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007593 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007594 return;
7595
Richard Trieu021baa32011-09-23 20:10:00 +00007596 // Diagnose implicit casts to bool.
7597 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7598 if (isa<StringLiteral>(E))
7599 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007600 // and expressions, for instance, assert(0 && "error here"), are
7601 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007602 return DiagnoseImpCast(S, E, T, CC,
7603 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007604 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7605 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7606 // This covers the literal expressions that evaluate to Objective-C
7607 // objects.
7608 return DiagnoseImpCast(S, E, T, CC,
7609 diag::warn_impcast_objective_c_literal_to_bool);
7610 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007611 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7612 // Warn on pointer to bool conversion that is always true.
7613 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7614 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007615 }
Richard Trieu021baa32011-09-23 20:10:00 +00007616 }
John McCall263a48b2010-01-04 23:31:57 +00007617
Douglas Gregor5054cb02015-07-07 03:58:22 +00007618 // Check implicit casts from Objective-C collection literals to specialized
7619 // collection types, e.g., NSArray<NSString *> *.
7620 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7621 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7622 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7623 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7624
John McCall263a48b2010-01-04 23:31:57 +00007625 // Strip vector types.
7626 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007627 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007628 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007629 return;
John McCallacf0ee52010-10-08 02:01:28 +00007630 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007631 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007632
7633 // If the vector cast is cast between two vectors of the same size, it is
7634 // a bitcast, not a conversion.
7635 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7636 return;
John McCall263a48b2010-01-04 23:31:57 +00007637
7638 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7639 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7640 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007641 if (auto VecTy = dyn_cast<VectorType>(Target))
7642 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007643
7644 // Strip complex types.
7645 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007646 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007647 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007648 return;
7649
John McCallacf0ee52010-10-08 02:01:28 +00007650 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007651 }
John McCall263a48b2010-01-04 23:31:57 +00007652
7653 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7654 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7655 }
7656
7657 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7658 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7659
7660 // If the source is floating point...
7661 if (SourceBT && SourceBT->isFloatingPoint()) {
7662 // ...and the target is floating point...
7663 if (TargetBT && TargetBT->isFloatingPoint()) {
7664 // ...then warn if we're dropping FP rank.
7665
7666 // Builtin FP kinds are ordered by increasing FP rank.
7667 if (SourceBT->getKind() > TargetBT->getKind()) {
7668 // Don't warn about float constants that are precisely
7669 // representable in the target type.
7670 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007671 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007672 // Value might be a float, a float vector, or a float complex.
7673 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007674 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7675 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007676 return;
7677 }
7678
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007679 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007680 return;
7681
John McCallacf0ee52010-10-08 02:01:28 +00007682 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007683 }
7684 // ... or possibly if we're increasing rank, too
7685 else if (TargetBT->getKind() > SourceBT->getKind()) {
7686 if (S.SourceMgr.isInSystemMacro(CC))
7687 return;
7688
7689 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007690 }
7691 return;
7692 }
7693
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007694 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007695 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007696 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007697 return;
7698
Chandler Carruth22c7a792011-02-17 11:05:49 +00007699 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007700 // We also want to warn on, e.g., "int i = -1.234"
7701 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7702 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7703 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7704
Chandler Carruth016ef402011-04-10 08:36:24 +00007705 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7706 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007707 } else {
7708 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7709 }
7710 }
John McCall263a48b2010-01-04 23:31:57 +00007711
Richard Smith54894fd2015-12-30 01:06:52 +00007712 // Detect the case where a call result is converted from floating-point to
7713 // to bool, and the final argument to the call is converted from bool, to
7714 // discover this typo:
7715 //
7716 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
7717 //
7718 // FIXME: This is an incredibly special case; is there some more general
7719 // way to detect this class of misplaced-parentheses bug?
7720 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007721 // Check last argument of function call to see if it is an
7722 // implicit cast from a type matching the type the result
7723 // is being cast to.
7724 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00007725 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007726 Expr *LastA = CEx->getArg(NumArgs - 1);
7727 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00007728 if (isa<ImplicitCastExpr>(LastA) &&
7729 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007730 // Warn on this floating-point to bool conversion
7731 DiagnoseImpCast(S, E, T, CC,
7732 diag::warn_impcast_floating_point_to_bool);
7733 }
7734 }
7735 }
John McCall263a48b2010-01-04 23:31:57 +00007736 return;
7737 }
7738
Richard Trieu5b993502014-10-15 03:42:06 +00007739 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007740
David Blaikie9366d2b2012-06-19 21:19:06 +00007741 if (!Source->isIntegerType() || !Target->isIntegerType())
7742 return;
7743
David Blaikie7555b6a2012-05-15 16:56:36 +00007744 // TODO: remove this early return once the false positives for constant->bool
7745 // in templates, macros, etc, are reduced or removed.
7746 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7747 return;
7748
John McCallcc7e5bf2010-05-06 08:58:33 +00007749 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007750 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007751
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007752 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007753 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007754 // TODO: this should happen for bitfield stores, too.
7755 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00007756 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007757 if (S.SourceMgr.isInSystemMacro(CC))
7758 return;
7759
John McCall18a2c2c2010-11-09 22:22:12 +00007760 std::string PrettySourceValue = Value.toString(10);
7761 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007762
Ted Kremenek33ba9952011-10-22 02:37:33 +00007763 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7764 S.PDiag(diag::warn_impcast_integer_precision_constant)
7765 << PrettySourceValue << PrettyTargetValue
7766 << E->getType() << T << E->getSourceRange()
7767 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007768 return;
7769 }
7770
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007771 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7772 if (S.SourceMgr.isInSystemMacro(CC))
7773 return;
7774
David Blaikie9455da02012-04-12 22:40:54 +00007775 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007776 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7777 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007778 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007779 }
7780
Richard Trieudcb55572016-01-29 23:51:16 +00007781 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
7782 SourceRange.NonNegative && Source->isSignedIntegerType()) {
7783 // Warn when doing a signed to signed conversion, warn if the positive
7784 // source value is exactly the width of the target type, which will
7785 // cause a negative value to be stored.
7786
7787 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00007788 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
7789 !S.SourceMgr.isInSystemMacro(CC)) {
7790 if (isSameWidthConstantConversion(S, E, T, CC)) {
7791 std::string PrettySourceValue = Value.toString(10);
7792 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00007793
Richard Trieufc404c72016-02-05 23:02:38 +00007794 S.DiagRuntimeBehavior(
7795 E->getExprLoc(), E,
7796 S.PDiag(diag::warn_impcast_integer_precision_constant)
7797 << PrettySourceValue << PrettyTargetValue << E->getType() << T
7798 << E->getSourceRange() << clang::SourceRange(CC));
7799 return;
Richard Trieudcb55572016-01-29 23:51:16 +00007800 }
7801 }
Richard Trieufc404c72016-02-05 23:02:38 +00007802
Richard Trieudcb55572016-01-29 23:51:16 +00007803 // Fall through for non-constants to give a sign conversion warning.
7804 }
7805
John McCallcc7e5bf2010-05-06 08:58:33 +00007806 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7807 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7808 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007809 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007810 return;
7811
John McCallcc7e5bf2010-05-06 08:58:33 +00007812 unsigned DiagID = diag::warn_impcast_integer_sign;
7813
7814 // Traditionally, gcc has warned about this under -Wsign-compare.
7815 // We also want to warn about it in -Wconversion.
7816 // So if -Wconversion is off, use a completely identical diagnostic
7817 // in the sign-compare group.
7818 // The conditional-checking code will
7819 if (ICContext) {
7820 DiagID = diag::warn_impcast_integer_sign_conditional;
7821 *ICContext = true;
7822 }
7823
John McCallacf0ee52010-10-08 02:01:28 +00007824 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007825 }
7826
Douglas Gregora78f1932011-02-22 02:45:07 +00007827 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007828 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7829 // type, to give us better diagnostics.
7830 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007831 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007832 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7833 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7834 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7835 SourceType = S.Context.getTypeDeclType(Enum);
7836 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7837 }
7838 }
7839
Douglas Gregora78f1932011-02-22 02:45:07 +00007840 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7841 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007842 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7843 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007844 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007845 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007846 return;
7847
Douglas Gregor364f7db2011-03-12 00:14:31 +00007848 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007849 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007850 }
John McCall263a48b2010-01-04 23:31:57 +00007851}
7852
David Blaikie18e9ac72012-05-15 21:57:38 +00007853void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7854 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007855
7856void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007857 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007858 E = E->IgnoreParenImpCasts();
7859
7860 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007861 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007862
John McCallacf0ee52010-10-08 02:01:28 +00007863 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007864 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007865 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007866}
7867
David Blaikie18e9ac72012-05-15 21:57:38 +00007868void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7869 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007870 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007871
7872 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007873 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7874 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007875
7876 // If -Wconversion would have warned about either of the candidates
7877 // for a signedness conversion to the context type...
7878 if (!Suspicious) return;
7879
7880 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007881 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007882 return;
7883
John McCallcc7e5bf2010-05-06 08:58:33 +00007884 // ...then check whether it would have warned about either of the
7885 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007886 if (E->getType() == T) return;
7887
7888 Suspicious = false;
7889 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7890 E->getType(), CC, &Suspicious);
7891 if (!Suspicious)
7892 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007893 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007894}
7895
Richard Trieu65724892014-11-15 06:37:39 +00007896/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7897/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007898void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00007899 if (S.getLangOpts().Bool)
7900 return;
7901 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7902}
7903
John McCallcc7e5bf2010-05-06 08:58:33 +00007904/// AnalyzeImplicitConversions - Find and report any interesting
7905/// implicit conversions in the given expression. There are a couple
7906/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007907void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007908 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007909 Expr *E = OrigE->IgnoreParenImpCasts();
7910
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007911 if (E->isTypeDependent() || E->isValueDependent())
7912 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007913
John McCallcc7e5bf2010-05-06 08:58:33 +00007914 // For conditional operators, we analyze the arguments as if they
7915 // were being fed directly into the output.
7916 if (isa<ConditionalOperator>(E)) {
7917 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007918 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007919 return;
7920 }
7921
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007922 // Check implicit argument conversions for function calls.
7923 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7924 CheckImplicitArgumentConversions(S, Call, CC);
7925
John McCallcc7e5bf2010-05-06 08:58:33 +00007926 // Go ahead and check any implicit conversions we might have skipped.
7927 // The non-canonical typecheck is just an optimization;
7928 // CheckImplicitConversion will filter out dead implicit conversions.
7929 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007930 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007931
7932 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00007933
7934 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
7935 // The bound subexpressions in a PseudoObjectExpr are not reachable
7936 // as transitive children.
7937 // FIXME: Use a more uniform representation for this.
7938 for (auto *SE : POE->semantics())
7939 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
7940 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007941 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00007942
John McCallcc7e5bf2010-05-06 08:58:33 +00007943 // Skip past explicit casts.
7944 if (isa<ExplicitCastExpr>(E)) {
7945 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007946 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007947 }
7948
John McCalld2a53122010-11-09 23:24:47 +00007949 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7950 // Do a somewhat different check with comparison operators.
7951 if (BO->isComparisonOp())
7952 return AnalyzeComparison(S, BO);
7953
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007954 // And with simple assignments.
7955 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007956 return AnalyzeAssignment(S, BO);
7957 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007958
7959 // These break the otherwise-useful invariant below. Fortunately,
7960 // we don't really need to recurse into them, because any internal
7961 // expressions should have been analyzed already when they were
7962 // built into statements.
7963 if (isa<StmtExpr>(E)) return;
7964
7965 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007966 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007967
7968 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007969 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007970 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007971 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007972 for (Stmt *SubStmt : E->children()) {
7973 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007974 if (!ChildExpr)
7975 continue;
7976
Richard Trieu955231d2014-01-25 01:10:35 +00007977 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007978 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007979 // Ignore checking string literals that are in logical and operators.
7980 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007981 continue;
7982 AnalyzeImplicitConversions(S, ChildExpr, CC);
7983 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007984
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007985 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007986 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7987 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007988 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007989
7990 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7991 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007992 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007993 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007994
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007995 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7996 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007997 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007998}
7999
8000} // end anonymous namespace
8001
Richard Trieuc1888e02014-06-28 23:25:37 +00008002// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8003// Returns true when emitting a warning about taking the address of a reference.
8004static bool CheckForReference(Sema &SemaRef, const Expr *E,
8005 PartialDiagnostic PD) {
8006 E = E->IgnoreParenImpCasts();
8007
8008 const FunctionDecl *FD = nullptr;
8009
8010 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8011 if (!DRE->getDecl()->getType()->isReferenceType())
8012 return false;
8013 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8014 if (!M->getMemberDecl()->getType()->isReferenceType())
8015 return false;
8016 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008017 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008018 return false;
8019 FD = Call->getDirectCallee();
8020 } else {
8021 return false;
8022 }
8023
8024 SemaRef.Diag(E->getExprLoc(), PD);
8025
8026 // If possible, point to location of function.
8027 if (FD) {
8028 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8029 }
8030
8031 return true;
8032}
8033
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008034// Returns true if the SourceLocation is expanded from any macro body.
8035// Returns false if the SourceLocation is invalid, is from not in a macro
8036// expansion, or is from expanded from a top-level macro argument.
8037static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8038 if (Loc.isInvalid())
8039 return false;
8040
8041 while (Loc.isMacroID()) {
8042 if (SM.isMacroBodyExpansion(Loc))
8043 return true;
8044 Loc = SM.getImmediateMacroCallerLoc(Loc);
8045 }
8046
8047 return false;
8048}
8049
Richard Trieu3bb8b562014-02-26 02:36:06 +00008050/// \brief Diagnose pointers that are always non-null.
8051/// \param E the expression containing the pointer
8052/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8053/// compared to a null pointer
8054/// \param IsEqual True when the comparison is equal to a null pointer
8055/// \param Range Extra SourceRange to highlight in the diagnostic
8056void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8057 Expr::NullPointerConstantKind NullKind,
8058 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008059 if (!E)
8060 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008061
8062 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008063 if (E->getExprLoc().isMacroID()) {
8064 const SourceManager &SM = getSourceManager();
8065 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8066 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008067 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008068 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008069 E = E->IgnoreImpCasts();
8070
8071 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8072
Richard Trieuf7432752014-06-06 21:39:26 +00008073 if (isa<CXXThisExpr>(E)) {
8074 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8075 : diag::warn_this_bool_conversion;
8076 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8077 return;
8078 }
8079
Richard Trieu3bb8b562014-02-26 02:36:06 +00008080 bool IsAddressOf = false;
8081
8082 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8083 if (UO->getOpcode() != UO_AddrOf)
8084 return;
8085 IsAddressOf = true;
8086 E = UO->getSubExpr();
8087 }
8088
Richard Trieuc1888e02014-06-28 23:25:37 +00008089 if (IsAddressOf) {
8090 unsigned DiagID = IsCompare
8091 ? diag::warn_address_of_reference_null_compare
8092 : diag::warn_address_of_reference_bool_conversion;
8093 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8094 << IsEqual;
8095 if (CheckForReference(*this, E, PD)) {
8096 return;
8097 }
8098 }
8099
George Burgess IV850269a2015-12-08 22:02:00 +00008100 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
8101 std::string Str;
8102 llvm::raw_string_ostream S(Str);
8103 E->printPretty(S, nullptr, getPrintingPolicy());
8104 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8105 : diag::warn_cast_nonnull_to_bool;
8106 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8107 << E->getSourceRange() << Range << IsEqual;
8108 };
8109
8110 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8111 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8112 if (auto *Callee = Call->getDirectCallee()) {
8113 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
8114 ComplainAboutNonnullParamOrCall(false);
8115 return;
8116 }
8117 }
8118 }
8119
Richard Trieu3bb8b562014-02-26 02:36:06 +00008120 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008121 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008122 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8123 D = R->getDecl();
8124 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8125 D = M->getMemberDecl();
8126 }
8127
8128 // Weak Decls can be null.
8129 if (!D || D->isWeak())
8130 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008131
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008132 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008133 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8134 if (getCurFunction() &&
8135 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8136 if (PV->hasAttr<NonNullAttr>()) {
8137 ComplainAboutNonnullParamOrCall(true);
8138 return;
8139 }
8140
8141 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8142 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
8143 assert(ParamIter != FD->param_end());
8144 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8145
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008146 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8147 if (!NonNull->args_size()) {
George Burgess IV850269a2015-12-08 22:02:00 +00008148 ComplainAboutNonnullParamOrCall(true);
8149 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008150 }
George Burgess IV850269a2015-12-08 22:02:00 +00008151
8152 for (unsigned ArgNo : NonNull->args()) {
8153 if (ArgNo == ParamNo) {
8154 ComplainAboutNonnullParamOrCall(true);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008155 return;
8156 }
George Burgess IV850269a2015-12-08 22:02:00 +00008157 }
8158 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008159 }
8160 }
George Burgess IV850269a2015-12-08 22:02:00 +00008161 }
8162
Richard Trieu3bb8b562014-02-26 02:36:06 +00008163 QualType T = D->getType();
8164 const bool IsArray = T->isArrayType();
8165 const bool IsFunction = T->isFunctionType();
8166
Richard Trieuc1888e02014-06-28 23:25:37 +00008167 // Address of function is used to silence the function warning.
8168 if (IsAddressOf && IsFunction) {
8169 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008170 }
8171
8172 // Found nothing.
8173 if (!IsAddressOf && !IsFunction && !IsArray)
8174 return;
8175
8176 // Pretty print the expression for the diagnostic.
8177 std::string Str;
8178 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008179 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008180
8181 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8182 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008183 enum {
8184 AddressOf,
8185 FunctionPointer,
8186 ArrayPointer
8187 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008188 if (IsAddressOf)
8189 DiagType = AddressOf;
8190 else if (IsFunction)
8191 DiagType = FunctionPointer;
8192 else if (IsArray)
8193 DiagType = ArrayPointer;
8194 else
8195 llvm_unreachable("Could not determine diagnostic.");
8196 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8197 << Range << IsEqual;
8198
8199 if (!IsFunction)
8200 return;
8201
8202 // Suggest '&' to silence the function warning.
8203 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8204 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8205
8206 // Check to see if '()' fixit should be emitted.
8207 QualType ReturnType;
8208 UnresolvedSet<4> NonTemplateOverloads;
8209 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8210 if (ReturnType.isNull())
8211 return;
8212
8213 if (IsCompare) {
8214 // There are two cases here. If there is null constant, the only suggest
8215 // for a pointer return type. If the null is 0, then suggest if the return
8216 // type is a pointer or an integer type.
8217 if (!ReturnType->isPointerType()) {
8218 if (NullKind == Expr::NPCK_ZeroExpression ||
8219 NullKind == Expr::NPCK_ZeroLiteral) {
8220 if (!ReturnType->isIntegerType())
8221 return;
8222 } else {
8223 return;
8224 }
8225 }
8226 } else { // !IsCompare
8227 // For function to bool, only suggest if the function pointer has bool
8228 // return type.
8229 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8230 return;
8231 }
8232 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008233 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008234}
8235
John McCallcc7e5bf2010-05-06 08:58:33 +00008236/// Diagnoses "dangerous" implicit conversions within the given
8237/// expression (which is a full expression). Implements -Wconversion
8238/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008239///
8240/// \param CC the "context" location of the implicit conversion, i.e.
8241/// the most location of the syntactic entity requiring the implicit
8242/// conversion
8243void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008244 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008245 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008246 return;
8247
8248 // Don't diagnose for value- or type-dependent expressions.
8249 if (E->isTypeDependent() || E->isValueDependent())
8250 return;
8251
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008252 // Check for array bounds violations in cases where the check isn't triggered
8253 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8254 // ArraySubscriptExpr is on the RHS of a variable initialization.
8255 CheckArrayAccess(E);
8256
John McCallacf0ee52010-10-08 02:01:28 +00008257 // This is not the right CC for (e.g.) a variable initialization.
8258 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008259}
8260
Richard Trieu65724892014-11-15 06:37:39 +00008261/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8262/// Input argument E is a logical expression.
8263void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8264 ::CheckBoolLikeConversion(*this, E, CC);
8265}
8266
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008267/// Diagnose when expression is an integer constant expression and its evaluation
8268/// results in integer overflow
8269void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008270 // Use a work list to deal with nested struct initializers.
8271 SmallVector<Expr *, 2> Exprs(1, E);
8272
8273 do {
8274 Expr *E = Exprs.pop_back_val();
8275
8276 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8277 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8278 continue;
8279 }
8280
8281 if (auto InitList = dyn_cast<InitListExpr>(E))
8282 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8283 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008284}
8285
Richard Smithc406cb72013-01-17 01:17:56 +00008286namespace {
8287/// \brief Visitor for expressions which looks for unsequenced operations on the
8288/// same object.
8289class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008290 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8291
Richard Smithc406cb72013-01-17 01:17:56 +00008292 /// \brief A tree of sequenced regions within an expression. Two regions are
8293 /// unsequenced if one is an ancestor or a descendent of the other. When we
8294 /// finish processing an expression with sequencing, such as a comma
8295 /// expression, we fold its tree nodes into its parent, since they are
8296 /// unsequenced with respect to nodes we will visit later.
8297 class SequenceTree {
8298 struct Value {
8299 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8300 unsigned Parent : 31;
8301 bool Merged : 1;
8302 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008303 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008304
8305 public:
8306 /// \brief A region within an expression which may be sequenced with respect
8307 /// to some other region.
8308 class Seq {
8309 explicit Seq(unsigned N) : Index(N) {}
8310 unsigned Index;
8311 friend class SequenceTree;
8312 public:
8313 Seq() : Index(0) {}
8314 };
8315
8316 SequenceTree() { Values.push_back(Value(0)); }
8317 Seq root() const { return Seq(0); }
8318
8319 /// \brief Create a new sequence of operations, which is an unsequenced
8320 /// subset of \p Parent. This sequence of operations is sequenced with
8321 /// respect to other children of \p Parent.
8322 Seq allocate(Seq Parent) {
8323 Values.push_back(Value(Parent.Index));
8324 return Seq(Values.size() - 1);
8325 }
8326
8327 /// \brief Merge a sequence of operations into its parent.
8328 void merge(Seq S) {
8329 Values[S.Index].Merged = true;
8330 }
8331
8332 /// \brief Determine whether two operations are unsequenced. This operation
8333 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8334 /// should have been merged into its parent as appropriate.
8335 bool isUnsequenced(Seq Cur, Seq Old) {
8336 unsigned C = representative(Cur.Index);
8337 unsigned Target = representative(Old.Index);
8338 while (C >= Target) {
8339 if (C == Target)
8340 return true;
8341 C = Values[C].Parent;
8342 }
8343 return false;
8344 }
8345
8346 private:
8347 /// \brief Pick a representative for a sequence.
8348 unsigned representative(unsigned K) {
8349 if (Values[K].Merged)
8350 // Perform path compression as we go.
8351 return Values[K].Parent = representative(Values[K].Parent);
8352 return K;
8353 }
8354 };
8355
8356 /// An object for which we can track unsequenced uses.
8357 typedef NamedDecl *Object;
8358
8359 /// Different flavors of object usage which we track. We only track the
8360 /// least-sequenced usage of each kind.
8361 enum UsageKind {
8362 /// A read of an object. Multiple unsequenced reads are OK.
8363 UK_Use,
8364 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008365 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008366 UK_ModAsValue,
8367 /// A modification of an object which is not sequenced before the value
8368 /// computation of the expression, such as n++.
8369 UK_ModAsSideEffect,
8370
8371 UK_Count = UK_ModAsSideEffect + 1
8372 };
8373
8374 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008375 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008376 Expr *Use;
8377 SequenceTree::Seq Seq;
8378 };
8379
8380 struct UsageInfo {
8381 UsageInfo() : Diagnosed(false) {}
8382 Usage Uses[UK_Count];
8383 /// Have we issued a diagnostic for this variable already?
8384 bool Diagnosed;
8385 };
8386 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8387
8388 Sema &SemaRef;
8389 /// Sequenced regions within the expression.
8390 SequenceTree Tree;
8391 /// Declaration modifications and references which we have seen.
8392 UsageInfoMap UsageMap;
8393 /// The region we are currently within.
8394 SequenceTree::Seq Region;
8395 /// Filled in with declarations which were modified as a side-effect
8396 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008397 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008398 /// Expressions to check later. We defer checking these to reduce
8399 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008400 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008401
8402 /// RAII object wrapping the visitation of a sequenced subexpression of an
8403 /// expression. At the end of this process, the side-effects of the evaluation
8404 /// become sequenced with respect to the value computation of the result, so
8405 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8406 /// UK_ModAsValue.
8407 struct SequencedSubexpression {
8408 SequencedSubexpression(SequenceChecker &Self)
8409 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8410 Self.ModAsSideEffect = &ModAsSideEffect;
8411 }
8412 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00008413 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8414 MI != ME; ++MI) {
8415 UsageInfo &U = Self.UsageMap[MI->first];
8416 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8417 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8418 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00008419 }
8420 Self.ModAsSideEffect = OldModAsSideEffect;
8421 }
8422
8423 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008424 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8425 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008426 };
8427
Richard Smith40238f02013-06-20 22:21:56 +00008428 /// RAII object wrapping the visitation of a subexpression which we might
8429 /// choose to evaluate as a constant. If any subexpression is evaluated and
8430 /// found to be non-constant, this allows us to suppress the evaluation of
8431 /// the outer expression.
8432 class EvaluationTracker {
8433 public:
8434 EvaluationTracker(SequenceChecker &Self)
8435 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8436 Self.EvalTracker = this;
8437 }
8438 ~EvaluationTracker() {
8439 Self.EvalTracker = Prev;
8440 if (Prev)
8441 Prev->EvalOK &= EvalOK;
8442 }
8443
8444 bool evaluate(const Expr *E, bool &Result) {
8445 if (!EvalOK || E->isValueDependent())
8446 return false;
8447 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8448 return EvalOK;
8449 }
8450
8451 private:
8452 SequenceChecker &Self;
8453 EvaluationTracker *Prev;
8454 bool EvalOK;
8455 } *EvalTracker;
8456
Richard Smithc406cb72013-01-17 01:17:56 +00008457 /// \brief Find the object which is produced by the specified expression,
8458 /// if any.
8459 Object getObject(Expr *E, bool Mod) const {
8460 E = E->IgnoreParenCasts();
8461 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8462 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8463 return getObject(UO->getSubExpr(), Mod);
8464 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8465 if (BO->getOpcode() == BO_Comma)
8466 return getObject(BO->getRHS(), Mod);
8467 if (Mod && BO->isAssignmentOp())
8468 return getObject(BO->getLHS(), Mod);
8469 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8470 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8471 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8472 return ME->getMemberDecl();
8473 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8474 // FIXME: If this is a reference, map through to its value.
8475 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008476 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008477 }
8478
8479 /// \brief Note that an object was modified or used by an expression.
8480 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8481 Usage &U = UI.Uses[UK];
8482 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8483 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8484 ModAsSideEffect->push_back(std::make_pair(O, U));
8485 U.Use = Ref;
8486 U.Seq = Region;
8487 }
8488 }
8489 /// \brief Check whether a modification or use conflicts with a prior usage.
8490 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8491 bool IsModMod) {
8492 if (UI.Diagnosed)
8493 return;
8494
8495 const Usage &U = UI.Uses[OtherKind];
8496 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8497 return;
8498
8499 Expr *Mod = U.Use;
8500 Expr *ModOrUse = Ref;
8501 if (OtherKind == UK_Use)
8502 std::swap(Mod, ModOrUse);
8503
8504 SemaRef.Diag(Mod->getExprLoc(),
8505 IsModMod ? diag::warn_unsequenced_mod_mod
8506 : diag::warn_unsequenced_mod_use)
8507 << O << SourceRange(ModOrUse->getExprLoc());
8508 UI.Diagnosed = true;
8509 }
8510
8511 void notePreUse(Object O, Expr *Use) {
8512 UsageInfo &U = UsageMap[O];
8513 // Uses conflict with other modifications.
8514 checkUsage(O, U, Use, UK_ModAsValue, false);
8515 }
8516 void notePostUse(Object O, Expr *Use) {
8517 UsageInfo &U = UsageMap[O];
8518 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8519 addUsage(U, O, Use, UK_Use);
8520 }
8521
8522 void notePreMod(Object O, Expr *Mod) {
8523 UsageInfo &U = UsageMap[O];
8524 // Modifications conflict with other modifications and with uses.
8525 checkUsage(O, U, Mod, UK_ModAsValue, true);
8526 checkUsage(O, U, Mod, UK_Use, false);
8527 }
8528 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8529 UsageInfo &U = UsageMap[O];
8530 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8531 addUsage(U, O, Use, UK);
8532 }
8533
8534public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008535 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008536 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8537 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008538 Visit(E);
8539 }
8540
8541 void VisitStmt(Stmt *S) {
8542 // Skip all statements which aren't expressions for now.
8543 }
8544
8545 void VisitExpr(Expr *E) {
8546 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008547 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008548 }
8549
8550 void VisitCastExpr(CastExpr *E) {
8551 Object O = Object();
8552 if (E->getCastKind() == CK_LValueToRValue)
8553 O = getObject(E->getSubExpr(), false);
8554
8555 if (O)
8556 notePreUse(O, E);
8557 VisitExpr(E);
8558 if (O)
8559 notePostUse(O, E);
8560 }
8561
8562 void VisitBinComma(BinaryOperator *BO) {
8563 // C++11 [expr.comma]p1:
8564 // Every value computation and side effect associated with the left
8565 // expression is sequenced before every value computation and side
8566 // effect associated with the right expression.
8567 SequenceTree::Seq LHS = Tree.allocate(Region);
8568 SequenceTree::Seq RHS = Tree.allocate(Region);
8569 SequenceTree::Seq OldRegion = Region;
8570
8571 {
8572 SequencedSubexpression SeqLHS(*this);
8573 Region = LHS;
8574 Visit(BO->getLHS());
8575 }
8576
8577 Region = RHS;
8578 Visit(BO->getRHS());
8579
8580 Region = OldRegion;
8581
8582 // Forget that LHS and RHS are sequenced. They are both unsequenced
8583 // with respect to other stuff.
8584 Tree.merge(LHS);
8585 Tree.merge(RHS);
8586 }
8587
8588 void VisitBinAssign(BinaryOperator *BO) {
8589 // The modification is sequenced after the value computation of the LHS
8590 // and RHS, so check it before inspecting the operands and update the
8591 // map afterwards.
8592 Object O = getObject(BO->getLHS(), true);
8593 if (!O)
8594 return VisitExpr(BO);
8595
8596 notePreMod(O, BO);
8597
8598 // C++11 [expr.ass]p7:
8599 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8600 // only once.
8601 //
8602 // Therefore, for a compound assignment operator, O is considered used
8603 // everywhere except within the evaluation of E1 itself.
8604 if (isa<CompoundAssignOperator>(BO))
8605 notePreUse(O, BO);
8606
8607 Visit(BO->getLHS());
8608
8609 if (isa<CompoundAssignOperator>(BO))
8610 notePostUse(O, BO);
8611
8612 Visit(BO->getRHS());
8613
Richard Smith83e37bee2013-06-26 23:16:51 +00008614 // C++11 [expr.ass]p1:
8615 // the assignment is sequenced [...] before the value computation of the
8616 // assignment expression.
8617 // C11 6.5.16/3 has no such rule.
8618 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8619 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008620 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008621
Richard Smithc406cb72013-01-17 01:17:56 +00008622 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8623 VisitBinAssign(CAO);
8624 }
8625
8626 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8627 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8628 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8629 Object O = getObject(UO->getSubExpr(), true);
8630 if (!O)
8631 return VisitExpr(UO);
8632
8633 notePreMod(O, UO);
8634 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008635 // C++11 [expr.pre.incr]p1:
8636 // the expression ++x is equivalent to x+=1
8637 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8638 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008639 }
8640
8641 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8642 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8643 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8644 Object O = getObject(UO->getSubExpr(), true);
8645 if (!O)
8646 return VisitExpr(UO);
8647
8648 notePreMod(O, UO);
8649 Visit(UO->getSubExpr());
8650 notePostMod(O, UO, UK_ModAsSideEffect);
8651 }
8652
8653 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8654 void VisitBinLOr(BinaryOperator *BO) {
8655 // The side-effects of the LHS of an '&&' are sequenced before the
8656 // value computation of the RHS, and hence before the value computation
8657 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8658 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008659 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008660 {
8661 SequencedSubexpression Sequenced(*this);
8662 Visit(BO->getLHS());
8663 }
8664
8665 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008666 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008667 if (!Result)
8668 Visit(BO->getRHS());
8669 } else {
8670 // Check for unsequenced operations in the RHS, treating it as an
8671 // entirely separate evaluation.
8672 //
8673 // FIXME: If there are operations in the RHS which are unsequenced
8674 // with respect to operations outside the RHS, and those operations
8675 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008676 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008677 }
Richard Smithc406cb72013-01-17 01:17:56 +00008678 }
8679 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008680 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008681 {
8682 SequencedSubexpression Sequenced(*this);
8683 Visit(BO->getLHS());
8684 }
8685
8686 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008687 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008688 if (Result)
8689 Visit(BO->getRHS());
8690 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008691 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008692 }
Richard Smithc406cb72013-01-17 01:17:56 +00008693 }
8694
8695 // Only visit the condition, unless we can be sure which subexpression will
8696 // be chosen.
8697 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008698 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008699 {
8700 SequencedSubexpression Sequenced(*this);
8701 Visit(CO->getCond());
8702 }
Richard Smithc406cb72013-01-17 01:17:56 +00008703
8704 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008705 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008706 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008707 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008708 WorkList.push_back(CO->getTrueExpr());
8709 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008710 }
Richard Smithc406cb72013-01-17 01:17:56 +00008711 }
8712
Richard Smithe3dbfe02013-06-30 10:40:20 +00008713 void VisitCallExpr(CallExpr *CE) {
8714 // C++11 [intro.execution]p15:
8715 // When calling a function [...], every value computation and side effect
8716 // associated with any argument expression, or with the postfix expression
8717 // designating the called function, is sequenced before execution of every
8718 // expression or statement in the body of the function [and thus before
8719 // the value computation of its result].
8720 SequencedSubexpression Sequenced(*this);
8721 Base::VisitCallExpr(CE);
8722
8723 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8724 }
8725
Richard Smithc406cb72013-01-17 01:17:56 +00008726 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008727 // This is a call, so all subexpressions are sequenced before the result.
8728 SequencedSubexpression Sequenced(*this);
8729
Richard Smithc406cb72013-01-17 01:17:56 +00008730 if (!CCE->isListInitialization())
8731 return VisitExpr(CCE);
8732
8733 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008734 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008735 SequenceTree::Seq Parent = Region;
8736 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8737 E = CCE->arg_end();
8738 I != E; ++I) {
8739 Region = Tree.allocate(Parent);
8740 Elts.push_back(Region);
8741 Visit(*I);
8742 }
8743
8744 // Forget that the initializers are sequenced.
8745 Region = Parent;
8746 for (unsigned I = 0; I < Elts.size(); ++I)
8747 Tree.merge(Elts[I]);
8748 }
8749
8750 void VisitInitListExpr(InitListExpr *ILE) {
8751 if (!SemaRef.getLangOpts().CPlusPlus11)
8752 return VisitExpr(ILE);
8753
8754 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008755 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008756 SequenceTree::Seq Parent = Region;
8757 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8758 Expr *E = ILE->getInit(I);
8759 if (!E) continue;
8760 Region = Tree.allocate(Parent);
8761 Elts.push_back(Region);
8762 Visit(E);
8763 }
8764
8765 // Forget that the initializers are sequenced.
8766 Region = Parent;
8767 for (unsigned I = 0; I < Elts.size(); ++I)
8768 Tree.merge(Elts[I]);
8769 }
8770};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008771} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00008772
8773void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008774 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008775 WorkList.push_back(E);
8776 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008777 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008778 SequenceChecker(*this, Item, WorkList);
8779 }
Richard Smithc406cb72013-01-17 01:17:56 +00008780}
8781
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008782void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8783 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008784 CheckImplicitConversions(E, CheckLoc);
8785 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008786 if (!IsConstexpr && !E->isValueDependent())
8787 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008788}
8789
John McCall1f425642010-11-11 03:21:53 +00008790void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8791 FieldDecl *BitField,
8792 Expr *Init) {
8793 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8794}
8795
David Majnemer61a5bbf2015-04-07 22:08:51 +00008796static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8797 SourceLocation Loc) {
8798 if (!PType->isVariablyModifiedType())
8799 return;
8800 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8801 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8802 return;
8803 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008804 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8805 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8806 return;
8807 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008808 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8809 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8810 return;
8811 }
8812
8813 const ArrayType *AT = S.Context.getAsArrayType(PType);
8814 if (!AT)
8815 return;
8816
8817 if (AT->getSizeModifier() != ArrayType::Star) {
8818 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8819 return;
8820 }
8821
8822 S.Diag(Loc, diag::err_array_star_in_function_definition);
8823}
8824
Mike Stump0c2ec772010-01-21 03:59:47 +00008825/// CheckParmsForFunctionDef - Check that the parameters of the given
8826/// function are appropriate for the definition of a function. This
8827/// takes care of any checks that cannot be performed on the
8828/// declaration itself, e.g., that the types of each of the function
8829/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008830bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8831 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008832 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008833 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008834 for (; P != PEnd; ++P) {
8835 ParmVarDecl *Param = *P;
8836
Mike Stump0c2ec772010-01-21 03:59:47 +00008837 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8838 // function declarator that is part of a function definition of
8839 // that function shall not have incomplete type.
8840 //
8841 // This is also C++ [dcl.fct]p6.
8842 if (!Param->isInvalidDecl() &&
8843 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008844 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008845 Param->setInvalidDecl();
8846 HasInvalidParm = true;
8847 }
8848
8849 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8850 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008851 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008852 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008853 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008854 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008855 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008856
8857 // C99 6.7.5.3p12:
8858 // If the function declarator is not part of a definition of that
8859 // function, parameters may have incomplete type and may use the [*]
8860 // notation in their sequences of declarator specifiers to specify
8861 // variable length array types.
8862 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008863 // FIXME: This diagnostic should point the '[*]' if source-location
8864 // information is added for it.
8865 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008866
8867 // MSVC destroys objects passed by value in the callee. Therefore a
8868 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008869 // object's destructor. However, we don't perform any direct access check
8870 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008871 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8872 .getCXXABI()
8873 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008874 if (!Param->isInvalidDecl()) {
8875 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8876 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8877 if (!ClassDecl->isInvalidDecl() &&
8878 !ClassDecl->hasIrrelevantDestructor() &&
8879 !ClassDecl->isDependentContext()) {
8880 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8881 MarkFunctionReferenced(Param->getLocation(), Destructor);
8882 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8883 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008884 }
8885 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008886 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008887
8888 // Parameters with the pass_object_size attribute only need to be marked
8889 // constant at function definitions. Because we lack information about
8890 // whether we're on a declaration or definition when we're instantiating the
8891 // attribute, we need to check for constness here.
8892 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
8893 if (!Param->getType().isConstQualified())
8894 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
8895 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00008896 }
8897
8898 return HasInvalidParm;
8899}
John McCall2b5c1b22010-08-12 21:44:57 +00008900
8901/// CheckCastAlign - Implements -Wcast-align, which warns when a
8902/// pointer cast increases the alignment requirements.
8903void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8904 // This is actually a lot of work to potentially be doing on every
8905 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008906 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008907 return;
8908
8909 // Ignore dependent types.
8910 if (T->isDependentType() || Op->getType()->isDependentType())
8911 return;
8912
8913 // Require that the destination be a pointer type.
8914 const PointerType *DestPtr = T->getAs<PointerType>();
8915 if (!DestPtr) return;
8916
8917 // If the destination has alignment 1, we're done.
8918 QualType DestPointee = DestPtr->getPointeeType();
8919 if (DestPointee->isIncompleteType()) return;
8920 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8921 if (DestAlign.isOne()) return;
8922
8923 // Require that the source be a pointer type.
8924 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8925 if (!SrcPtr) return;
8926 QualType SrcPointee = SrcPtr->getPointeeType();
8927
8928 // Whitelist casts from cv void*. We already implicitly
8929 // whitelisted casts to cv void*, since they have alignment 1.
8930 // Also whitelist casts involving incomplete types, which implicitly
8931 // includes 'void'.
8932 if (SrcPointee->isIncompleteType()) return;
8933
8934 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8935 if (SrcAlign >= DestAlign) return;
8936
8937 Diag(TRange.getBegin(), diag::warn_cast_align)
8938 << Op->getType() << T
8939 << static_cast<unsigned>(SrcAlign.getQuantity())
8940 << static_cast<unsigned>(DestAlign.getQuantity())
8941 << TRange << Op->getSourceRange();
8942}
8943
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008944static const Type* getElementType(const Expr *BaseExpr) {
8945 const Type* EltType = BaseExpr->getType().getTypePtr();
8946 if (EltType->isAnyPointerType())
8947 return EltType->getPointeeType().getTypePtr();
8948 else if (EltType->isArrayType())
8949 return EltType->getBaseElementTypeUnsafe();
8950 return EltType;
8951}
8952
Chandler Carruth28389f02011-08-05 09:10:50 +00008953/// \brief Check whether this array fits the idiom of a size-one tail padded
8954/// array member of a struct.
8955///
8956/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8957/// commonly used to emulate flexible arrays in C89 code.
8958static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8959 const NamedDecl *ND) {
8960 if (Size != 1 || !ND) return false;
8961
8962 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8963 if (!FD) return false;
8964
8965 // Don't consider sizes resulting from macro expansions or template argument
8966 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008967
8968 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008969 while (TInfo) {
8970 TypeLoc TL = TInfo->getTypeLoc();
8971 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008972 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8973 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008974 TInfo = TDL->getTypeSourceInfo();
8975 continue;
8976 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008977 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8978 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008979 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8980 return false;
8981 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008982 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008983 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008984
8985 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008986 if (!RD) return false;
8987 if (RD->isUnion()) return false;
8988 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8989 if (!CRD->isStandardLayout()) return false;
8990 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008991
Benjamin Kramer8c543672011-08-06 03:04:42 +00008992 // See if this is the last field decl in the record.
8993 const Decl *D = FD;
8994 while ((D = D->getNextDeclInContext()))
8995 if (isa<FieldDecl>(D))
8996 return false;
8997 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008998}
8999
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009000void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009001 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009002 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009003 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009004 if (IndexExpr->isValueDependent())
9005 return;
9006
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00009007 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009008 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009009 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009010 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009011 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009012 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009013
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009014 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009015 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009016 return;
Richard Smith13f67182011-12-16 19:31:14 +00009017 if (IndexNegated)
9018 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009019
Craig Topperc3ec1492014-05-26 06:22:03 +00009020 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009021 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9022 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009023 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009024 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009025
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009026 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009027 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009028 if (!size.isStrictlyPositive())
9029 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009030
9031 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00009032 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009033 // Make sure we're comparing apples to apples when comparing index to size
9034 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9035 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009036 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009037 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009038 if (ptrarith_typesize != array_typesize) {
9039 // There's a cast to a different size type involved
9040 uint64_t ratio = array_typesize / ptrarith_typesize;
9041 // TODO: Be smarter about handling cases where array_typesize is not a
9042 // multiple of ptrarith_typesize
9043 if (ptrarith_typesize * ratio == array_typesize)
9044 size *= llvm::APInt(size.getBitWidth(), ratio);
9045 }
9046 }
9047
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009048 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009049 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009050 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009051 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009052
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009053 // For array subscripting the index must be less than size, but for pointer
9054 // arithmetic also allow the index (offset) to be equal to size since
9055 // computing the next address after the end of the array is legal and
9056 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009057 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009058 return;
9059
9060 // Also don't warn for arrays of size 1 which are members of some
9061 // structure. These are often used to approximate flexible arrays in C89
9062 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009063 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009064 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009065
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009066 // Suppress the warning if the subscript expression (as identified by the
9067 // ']' location) and the index expression are both from macro expansions
9068 // within a system header.
9069 if (ASE) {
9070 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9071 ASE->getRBracketLoc());
9072 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9073 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9074 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009075 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009076 return;
9077 }
9078 }
9079
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009080 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009081 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009082 DiagID = diag::warn_array_index_exceeds_bounds;
9083
9084 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9085 PDiag(DiagID) << index.toString(10, true)
9086 << size.toString(10, true)
9087 << (unsigned)size.getLimitedValue(~0U)
9088 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009089 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009090 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009091 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009092 DiagID = diag::warn_ptr_arith_precedes_bounds;
9093 if (index.isNegative()) index = -index;
9094 }
9095
9096 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9097 PDiag(DiagID) << index.toString(10, true)
9098 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009099 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009100
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009101 if (!ND) {
9102 // Try harder to find a NamedDecl to point at in the note.
9103 while (const ArraySubscriptExpr *ASE =
9104 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9105 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9106 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9107 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9108 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9109 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9110 }
9111
Chandler Carruth1af88f12011-02-17 21:10:52 +00009112 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009113 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9114 PDiag(diag::note_array_index_out_of_bounds)
9115 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009116}
9117
Ted Kremenekdf26df72011-03-01 18:41:00 +00009118void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009119 int AllowOnePastEnd = 0;
9120 while (expr) {
9121 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009122 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009123 case Stmt::ArraySubscriptExprClass: {
9124 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009125 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009126 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009127 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009128 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009129 case Stmt::OMPArraySectionExprClass: {
9130 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9131 if (ASE->getLowerBound())
9132 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9133 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9134 return;
9135 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009136 case Stmt::UnaryOperatorClass: {
9137 // Only unwrap the * and & unary operators
9138 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9139 expr = UO->getSubExpr();
9140 switch (UO->getOpcode()) {
9141 case UO_AddrOf:
9142 AllowOnePastEnd++;
9143 break;
9144 case UO_Deref:
9145 AllowOnePastEnd--;
9146 break;
9147 default:
9148 return;
9149 }
9150 break;
9151 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009152 case Stmt::ConditionalOperatorClass: {
9153 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9154 if (const Expr *lhs = cond->getLHS())
9155 CheckArrayAccess(lhs);
9156 if (const Expr *rhs = cond->getRHS())
9157 CheckArrayAccess(rhs);
9158 return;
9159 }
9160 default:
9161 return;
9162 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009163 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009164}
John McCall31168b02011-06-15 23:02:42 +00009165
9166//===--- CHECK: Objective-C retain cycles ----------------------------------//
9167
9168namespace {
9169 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009170 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009171 VarDecl *Variable;
9172 SourceRange Range;
9173 SourceLocation Loc;
9174 bool Indirect;
9175
9176 void setLocsFrom(Expr *e) {
9177 Loc = e->getExprLoc();
9178 Range = e->getSourceRange();
9179 }
9180 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009181} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009182
9183/// Consider whether capturing the given variable can possibly lead to
9184/// a retain cycle.
9185static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009186 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009187 // lifetime. In MRR, it's captured strongly if the variable is
9188 // __block and has an appropriate type.
9189 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9190 return false;
9191
9192 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009193 if (ref)
9194 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009195 return true;
9196}
9197
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009198static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009199 while (true) {
9200 e = e->IgnoreParens();
9201 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9202 switch (cast->getCastKind()) {
9203 case CK_BitCast:
9204 case CK_LValueBitCast:
9205 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009206 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009207 e = cast->getSubExpr();
9208 continue;
9209
John McCall31168b02011-06-15 23:02:42 +00009210 default:
9211 return false;
9212 }
9213 }
9214
9215 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9216 ObjCIvarDecl *ivar = ref->getDecl();
9217 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9218 return false;
9219
9220 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009221 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009222 return false;
9223
9224 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9225 owner.Indirect = true;
9226 return true;
9227 }
9228
9229 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9230 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9231 if (!var) return false;
9232 return considerVariable(var, ref, owner);
9233 }
9234
John McCall31168b02011-06-15 23:02:42 +00009235 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9236 if (member->isArrow()) return false;
9237
9238 // Don't count this as an indirect ownership.
9239 e = member->getBase();
9240 continue;
9241 }
9242
John McCallfe96e0b2011-11-06 09:01:30 +00009243 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9244 // Only pay attention to pseudo-objects on property references.
9245 ObjCPropertyRefExpr *pre
9246 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9247 ->IgnoreParens());
9248 if (!pre) return false;
9249 if (pre->isImplicitProperty()) return false;
9250 ObjCPropertyDecl *property = pre->getExplicitProperty();
9251 if (!property->isRetaining() &&
9252 !(property->getPropertyIvarDecl() &&
9253 property->getPropertyIvarDecl()->getType()
9254 .getObjCLifetime() == Qualifiers::OCL_Strong))
9255 return false;
9256
9257 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009258 if (pre->isSuperReceiver()) {
9259 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9260 if (!owner.Variable)
9261 return false;
9262 owner.Loc = pre->getLocation();
9263 owner.Range = pre->getSourceRange();
9264 return true;
9265 }
John McCallfe96e0b2011-11-06 09:01:30 +00009266 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9267 ->getSourceExpr());
9268 continue;
9269 }
9270
John McCall31168b02011-06-15 23:02:42 +00009271 // Array ivars?
9272
9273 return false;
9274 }
9275}
9276
9277namespace {
9278 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9279 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9280 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009281 Context(Context), Variable(variable), Capturer(nullptr),
9282 VarWillBeReased(false) {}
9283 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009284 VarDecl *Variable;
9285 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009286 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009287
9288 void VisitDeclRefExpr(DeclRefExpr *ref) {
9289 if (ref->getDecl() == Variable && !Capturer)
9290 Capturer = ref;
9291 }
9292
John McCall31168b02011-06-15 23:02:42 +00009293 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9294 if (Capturer) return;
9295 Visit(ref->getBase());
9296 if (Capturer && ref->isFreeIvar())
9297 Capturer = ref;
9298 }
9299
9300 void VisitBlockExpr(BlockExpr *block) {
9301 // Look inside nested blocks
9302 if (block->getBlockDecl()->capturesVariable(Variable))
9303 Visit(block->getBlockDecl()->getBody());
9304 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009305
9306 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9307 if (Capturer) return;
9308 if (OVE->getSourceExpr())
9309 Visit(OVE->getSourceExpr());
9310 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009311 void VisitBinaryOperator(BinaryOperator *BinOp) {
9312 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9313 return;
9314 Expr *LHS = BinOp->getLHS();
9315 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9316 if (DRE->getDecl() != Variable)
9317 return;
9318 if (Expr *RHS = BinOp->getRHS()) {
9319 RHS = RHS->IgnoreParenCasts();
9320 llvm::APSInt Value;
9321 VarWillBeReased =
9322 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9323 }
9324 }
9325 }
John McCall31168b02011-06-15 23:02:42 +00009326 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009327} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009328
9329/// Check whether the given argument is a block which captures a
9330/// variable.
9331static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9332 assert(owner.Variable && owner.Loc.isValid());
9333
9334 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009335
9336 // Look through [^{...} copy] and Block_copy(^{...}).
9337 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9338 Selector Cmd = ME->getSelector();
9339 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9340 e = ME->getInstanceReceiver();
9341 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009342 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009343 e = e->IgnoreParenCasts();
9344 }
9345 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9346 if (CE->getNumArgs() == 1) {
9347 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009348 if (Fn) {
9349 const IdentifierInfo *FnI = Fn->getIdentifier();
9350 if (FnI && FnI->isStr("_Block_copy")) {
9351 e = CE->getArg(0)->IgnoreParenCasts();
9352 }
9353 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009354 }
9355 }
9356
John McCall31168b02011-06-15 23:02:42 +00009357 BlockExpr *block = dyn_cast<BlockExpr>(e);
9358 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009359 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009360
9361 FindCaptureVisitor visitor(S.Context, owner.Variable);
9362 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009363 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009364}
9365
9366static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9367 RetainCycleOwner &owner) {
9368 assert(capturer);
9369 assert(owner.Variable && owner.Loc.isValid());
9370
9371 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9372 << owner.Variable << capturer->getSourceRange();
9373 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9374 << owner.Indirect << owner.Range;
9375}
9376
9377/// Check for a keyword selector that starts with the word 'add' or
9378/// 'set'.
9379static bool isSetterLikeSelector(Selector sel) {
9380 if (sel.isUnarySelector()) return false;
9381
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009382 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009383 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009384 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009385 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009386 else if (str.startswith("add")) {
9387 // Specially whitelist 'addOperationWithBlock:'.
9388 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9389 return false;
9390 str = str.substr(3);
9391 }
John McCall31168b02011-06-15 23:02:42 +00009392 else
9393 return false;
9394
9395 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009396 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009397}
9398
Benjamin Kramer3a743452015-03-09 15:03:32 +00009399static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9400 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009401 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9402 Message->getReceiverInterface(),
9403 NSAPI::ClassId_NSMutableArray);
9404 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009405 return None;
9406 }
9407
9408 Selector Sel = Message->getSelector();
9409
9410 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9411 S.NSAPIObj->getNSArrayMethodKind(Sel);
9412 if (!MKOpt) {
9413 return None;
9414 }
9415
9416 NSAPI::NSArrayMethodKind MK = *MKOpt;
9417
9418 switch (MK) {
9419 case NSAPI::NSMutableArr_addObject:
9420 case NSAPI::NSMutableArr_insertObjectAtIndex:
9421 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9422 return 0;
9423 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9424 return 1;
9425
9426 default:
9427 return None;
9428 }
9429
9430 return None;
9431}
9432
9433static
9434Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9435 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009436 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9437 Message->getReceiverInterface(),
9438 NSAPI::ClassId_NSMutableDictionary);
9439 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009440 return None;
9441 }
9442
9443 Selector Sel = Message->getSelector();
9444
9445 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9446 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9447 if (!MKOpt) {
9448 return None;
9449 }
9450
9451 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9452
9453 switch (MK) {
9454 case NSAPI::NSMutableDict_setObjectForKey:
9455 case NSAPI::NSMutableDict_setValueForKey:
9456 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9457 return 0;
9458
9459 default:
9460 return None;
9461 }
9462
9463 return None;
9464}
9465
9466static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009467 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9468 Message->getReceiverInterface(),
9469 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009470
Alex Denisov5dfac812015-08-06 04:51:14 +00009471 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9472 Message->getReceiverInterface(),
9473 NSAPI::ClassId_NSMutableOrderedSet);
9474 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009475 return None;
9476 }
9477
9478 Selector Sel = Message->getSelector();
9479
9480 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9481 if (!MKOpt) {
9482 return None;
9483 }
9484
9485 NSAPI::NSSetMethodKind MK = *MKOpt;
9486
9487 switch (MK) {
9488 case NSAPI::NSMutableSet_addObject:
9489 case NSAPI::NSOrderedSet_setObjectAtIndex:
9490 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9491 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9492 return 0;
9493 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9494 return 1;
9495 }
9496
9497 return None;
9498}
9499
9500void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9501 if (!Message->isInstanceMessage()) {
9502 return;
9503 }
9504
9505 Optional<int> ArgOpt;
9506
9507 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9508 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9509 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9510 return;
9511 }
9512
9513 int ArgIndex = *ArgOpt;
9514
Alex Denisove1d882c2015-03-04 17:55:52 +00009515 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9516 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9517 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9518 }
9519
Alex Denisov5dfac812015-08-06 04:51:14 +00009520 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009521 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009522 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009523 Diag(Message->getSourceRange().getBegin(),
9524 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009525 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009526 }
9527 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009528 } else {
9529 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9530
9531 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9532 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9533 }
9534
9535 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9536 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9537 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9538 ValueDecl *Decl = ReceiverRE->getDecl();
9539 Diag(Message->getSourceRange().getBegin(),
9540 diag::warn_objc_circular_container)
9541 << Decl->getName() << Decl->getName();
9542 if (!ArgRE->isObjCSelfExpr()) {
9543 Diag(Decl->getLocation(),
9544 diag::note_objc_circular_container_declared_here)
9545 << Decl->getName();
9546 }
9547 }
9548 }
9549 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9550 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9551 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9552 ObjCIvarDecl *Decl = IvarRE->getDecl();
9553 Diag(Message->getSourceRange().getBegin(),
9554 diag::warn_objc_circular_container)
9555 << Decl->getName() << Decl->getName();
9556 Diag(Decl->getLocation(),
9557 diag::note_objc_circular_container_declared_here)
9558 << Decl->getName();
9559 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009560 }
9561 }
9562 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009563}
9564
John McCall31168b02011-06-15 23:02:42 +00009565/// Check a message send to see if it's likely to cause a retain cycle.
9566void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9567 // Only check instance methods whose selector looks like a setter.
9568 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9569 return;
9570
9571 // Try to find a variable that the receiver is strongly owned by.
9572 RetainCycleOwner owner;
9573 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009574 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009575 return;
9576 } else {
9577 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9578 owner.Variable = getCurMethodDecl()->getSelfDecl();
9579 owner.Loc = msg->getSuperLoc();
9580 owner.Range = msg->getSuperLoc();
9581 }
9582
9583 // Check whether the receiver is captured by any of the arguments.
9584 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9585 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9586 return diagnoseRetainCycle(*this, capturer, owner);
9587}
9588
9589/// Check a property assign to see if it's likely to cause a retain cycle.
9590void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9591 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009592 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009593 return;
9594
9595 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9596 diagnoseRetainCycle(*this, capturer, owner);
9597}
9598
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009599void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9600 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009601 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009602 return;
9603
9604 // Because we don't have an expression for the variable, we have to set the
9605 // location explicitly here.
9606 Owner.Loc = Var->getLocation();
9607 Owner.Range = Var->getSourceRange();
9608
9609 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9610 diagnoseRetainCycle(*this, Capturer, Owner);
9611}
9612
Ted Kremenek9304da92012-12-21 08:04:28 +00009613static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9614 Expr *RHS, bool isProperty) {
9615 // Check if RHS is an Objective-C object literal, which also can get
9616 // immediately zapped in a weak reference. Note that we explicitly
9617 // allow ObjCStringLiterals, since those are designed to never really die.
9618 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009619
Ted Kremenek64873352012-12-21 22:46:35 +00009620 // This enum needs to match with the 'select' in
9621 // warn_objc_arc_literal_assign (off-by-1).
9622 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9623 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9624 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009625
9626 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009627 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009628 << (isProperty ? 0 : 1)
9629 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009630
9631 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009632}
9633
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009634static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9635 Qualifiers::ObjCLifetime LT,
9636 Expr *RHS, bool isProperty) {
9637 // Strip off any implicit cast added to get to the one ARC-specific.
9638 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9639 if (cast->getCastKind() == CK_ARCConsumeObject) {
9640 S.Diag(Loc, diag::warn_arc_retained_assign)
9641 << (LT == Qualifiers::OCL_ExplicitNone)
9642 << (isProperty ? 0 : 1)
9643 << RHS->getSourceRange();
9644 return true;
9645 }
9646 RHS = cast->getSubExpr();
9647 }
9648
9649 if (LT == Qualifiers::OCL_Weak &&
9650 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9651 return true;
9652
9653 return false;
9654}
9655
Ted Kremenekb36234d2012-12-21 08:04:20 +00009656bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9657 QualType LHS, Expr *RHS) {
9658 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9659
9660 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9661 return false;
9662
9663 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9664 return true;
9665
9666 return false;
9667}
9668
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009669void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9670 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009671 QualType LHSType;
9672 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009673 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009674 ObjCPropertyRefExpr *PRE
9675 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9676 if (PRE && !PRE->isImplicitProperty()) {
9677 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9678 if (PD)
9679 LHSType = PD->getType();
9680 }
9681
9682 if (LHSType.isNull())
9683 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009684
9685 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9686
9687 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009688 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009689 getCurFunction()->markSafeWeakUse(LHS);
9690 }
9691
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009692 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9693 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009694
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009695 // FIXME. Check for other life times.
9696 if (LT != Qualifiers::OCL_None)
9697 return;
9698
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009699 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009700 if (PRE->isImplicitProperty())
9701 return;
9702 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9703 if (!PD)
9704 return;
9705
Bill Wendling44426052012-12-20 19:22:21 +00009706 unsigned Attributes = PD->getPropertyAttributes();
9707 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009708 // when 'assign' attribute was not explicitly specified
9709 // by user, ignore it and rely on property type itself
9710 // for lifetime info.
9711 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9712 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9713 LHSType->isObjCRetainableType())
9714 return;
9715
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009716 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009717 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009718 Diag(Loc, diag::warn_arc_retained_property_assign)
9719 << RHS->getSourceRange();
9720 return;
9721 }
9722 RHS = cast->getSubExpr();
9723 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009724 }
Bill Wendling44426052012-12-20 19:22:21 +00009725 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009726 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9727 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009728 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009729 }
9730}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009731
9732//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9733
9734namespace {
9735bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9736 SourceLocation StmtLoc,
9737 const NullStmt *Body) {
9738 // Do not warn if the body is a macro that expands to nothing, e.g:
9739 //
9740 // #define CALL(x)
9741 // if (condition)
9742 // CALL(0);
9743 //
9744 if (Body->hasLeadingEmptyMacro())
9745 return false;
9746
9747 // Get line numbers of statement and body.
9748 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009749 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009750 &StmtLineInvalid);
9751 if (StmtLineInvalid)
9752 return false;
9753
9754 bool BodyLineInvalid;
9755 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9756 &BodyLineInvalid);
9757 if (BodyLineInvalid)
9758 return false;
9759
9760 // Warn if null statement and body are on the same line.
9761 if (StmtLine != BodyLine)
9762 return false;
9763
9764 return true;
9765}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009766} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009767
9768void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9769 const Stmt *Body,
9770 unsigned DiagID) {
9771 // Since this is a syntactic check, don't emit diagnostic for template
9772 // instantiations, this just adds noise.
9773 if (CurrentInstantiationScope)
9774 return;
9775
9776 // The body should be a null statement.
9777 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9778 if (!NBody)
9779 return;
9780
9781 // Do the usual checks.
9782 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9783 return;
9784
9785 Diag(NBody->getSemiLoc(), DiagID);
9786 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9787}
9788
9789void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9790 const Stmt *PossibleBody) {
9791 assert(!CurrentInstantiationScope); // Ensured by caller
9792
9793 SourceLocation StmtLoc;
9794 const Stmt *Body;
9795 unsigned DiagID;
9796 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9797 StmtLoc = FS->getRParenLoc();
9798 Body = FS->getBody();
9799 DiagID = diag::warn_empty_for_body;
9800 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9801 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9802 Body = WS->getBody();
9803 DiagID = diag::warn_empty_while_body;
9804 } else
9805 return; // Neither `for' nor `while'.
9806
9807 // The body should be a null statement.
9808 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9809 if (!NBody)
9810 return;
9811
9812 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009813 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009814 return;
9815
9816 // Do the usual checks.
9817 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9818 return;
9819
9820 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9821 // noise level low, emit diagnostics only if for/while is followed by a
9822 // CompoundStmt, e.g.:
9823 // for (int i = 0; i < n; i++);
9824 // {
9825 // a(i);
9826 // }
9827 // or if for/while is followed by a statement with more indentation
9828 // than for/while itself:
9829 // for (int i = 0; i < n; i++);
9830 // a(i);
9831 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9832 if (!ProbableTypo) {
9833 bool BodyColInvalid;
9834 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9835 PossibleBody->getLocStart(),
9836 &BodyColInvalid);
9837 if (BodyColInvalid)
9838 return;
9839
9840 bool StmtColInvalid;
9841 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9842 S->getLocStart(),
9843 &StmtColInvalid);
9844 if (StmtColInvalid)
9845 return;
9846
9847 if (BodyCol > StmtCol)
9848 ProbableTypo = true;
9849 }
9850
9851 if (ProbableTypo) {
9852 Diag(NBody->getSemiLoc(), DiagID);
9853 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9854 }
9855}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009856
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009857//===--- CHECK: Warn on self move with std::move. -------------------------===//
9858
9859/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9860void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9861 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009862 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9863 return;
9864
9865 if (!ActiveTemplateInstantiations.empty())
9866 return;
9867
9868 // Strip parens and casts away.
9869 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9870 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9871
9872 // Check for a call expression
9873 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9874 if (!CE || CE->getNumArgs() != 1)
9875 return;
9876
9877 // Check for a call to std::move
9878 const FunctionDecl *FD = CE->getDirectCallee();
9879 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9880 !FD->getIdentifier()->isStr("move"))
9881 return;
9882
9883 // Get argument from std::move
9884 RHSExpr = CE->getArg(0);
9885
9886 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9887 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9888
9889 // Two DeclRefExpr's, check that the decls are the same.
9890 if (LHSDeclRef && RHSDeclRef) {
9891 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9892 return;
9893 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9894 RHSDeclRef->getDecl()->getCanonicalDecl())
9895 return;
9896
9897 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9898 << LHSExpr->getSourceRange()
9899 << RHSExpr->getSourceRange();
9900 return;
9901 }
9902
9903 // Member variables require a different approach to check for self moves.
9904 // MemberExpr's are the same if every nested MemberExpr refers to the same
9905 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9906 // the base Expr's are CXXThisExpr's.
9907 const Expr *LHSBase = LHSExpr;
9908 const Expr *RHSBase = RHSExpr;
9909 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9910 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9911 if (!LHSME || !RHSME)
9912 return;
9913
9914 while (LHSME && RHSME) {
9915 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9916 RHSME->getMemberDecl()->getCanonicalDecl())
9917 return;
9918
9919 LHSBase = LHSME->getBase();
9920 RHSBase = RHSME->getBase();
9921 LHSME = dyn_cast<MemberExpr>(LHSBase);
9922 RHSME = dyn_cast<MemberExpr>(RHSBase);
9923 }
9924
9925 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9926 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9927 if (LHSDeclRef && RHSDeclRef) {
9928 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9929 return;
9930 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9931 RHSDeclRef->getDecl()->getCanonicalDecl())
9932 return;
9933
9934 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9935 << LHSExpr->getSourceRange()
9936 << RHSExpr->getSourceRange();
9937 return;
9938 }
9939
9940 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9941 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9942 << LHSExpr->getSourceRange()
9943 << RHSExpr->getSourceRange();
9944}
9945
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009946//===--- Layout compatibility ----------------------------------------------//
9947
9948namespace {
9949
9950bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9951
9952/// \brief Check if two enumeration types are layout-compatible.
9953bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9954 // C++11 [dcl.enum] p8:
9955 // Two enumeration types are layout-compatible if they have the same
9956 // underlying type.
9957 return ED1->isComplete() && ED2->isComplete() &&
9958 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9959}
9960
9961/// \brief Check if two fields are layout-compatible.
9962bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9963 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9964 return false;
9965
9966 if (Field1->isBitField() != Field2->isBitField())
9967 return false;
9968
9969 if (Field1->isBitField()) {
9970 // Make sure that the bit-fields are the same length.
9971 unsigned Bits1 = Field1->getBitWidthValue(C);
9972 unsigned Bits2 = Field2->getBitWidthValue(C);
9973
9974 if (Bits1 != Bits2)
9975 return false;
9976 }
9977
9978 return true;
9979}
9980
9981/// \brief Check if two standard-layout structs are layout-compatible.
9982/// (C++11 [class.mem] p17)
9983bool isLayoutCompatibleStruct(ASTContext &C,
9984 RecordDecl *RD1,
9985 RecordDecl *RD2) {
9986 // If both records are C++ classes, check that base classes match.
9987 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9988 // If one of records is a CXXRecordDecl we are in C++ mode,
9989 // thus the other one is a CXXRecordDecl, too.
9990 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9991 // Check number of base classes.
9992 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9993 return false;
9994
9995 // Check the base classes.
9996 for (CXXRecordDecl::base_class_const_iterator
9997 Base1 = D1CXX->bases_begin(),
9998 BaseEnd1 = D1CXX->bases_end(),
9999 Base2 = D2CXX->bases_begin();
10000 Base1 != BaseEnd1;
10001 ++Base1, ++Base2) {
10002 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10003 return false;
10004 }
10005 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10006 // If only RD2 is a C++ class, it should have zero base classes.
10007 if (D2CXX->getNumBases() > 0)
10008 return false;
10009 }
10010
10011 // Check the fields.
10012 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10013 Field2End = RD2->field_end(),
10014 Field1 = RD1->field_begin(),
10015 Field1End = RD1->field_end();
10016 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10017 if (!isLayoutCompatible(C, *Field1, *Field2))
10018 return false;
10019 }
10020 if (Field1 != Field1End || Field2 != Field2End)
10021 return false;
10022
10023 return true;
10024}
10025
10026/// \brief Check if two standard-layout unions are layout-compatible.
10027/// (C++11 [class.mem] p18)
10028bool isLayoutCompatibleUnion(ASTContext &C,
10029 RecordDecl *RD1,
10030 RecordDecl *RD2) {
10031 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010032 for (auto *Field2 : RD2->fields())
10033 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010034
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010035 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010036 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10037 I = UnmatchedFields.begin(),
10038 E = UnmatchedFields.end();
10039
10040 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010041 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010042 bool Result = UnmatchedFields.erase(*I);
10043 (void) Result;
10044 assert(Result);
10045 break;
10046 }
10047 }
10048 if (I == E)
10049 return false;
10050 }
10051
10052 return UnmatchedFields.empty();
10053}
10054
10055bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10056 if (RD1->isUnion() != RD2->isUnion())
10057 return false;
10058
10059 if (RD1->isUnion())
10060 return isLayoutCompatibleUnion(C, RD1, RD2);
10061 else
10062 return isLayoutCompatibleStruct(C, RD1, RD2);
10063}
10064
10065/// \brief Check if two types are layout-compatible in C++11 sense.
10066bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10067 if (T1.isNull() || T2.isNull())
10068 return false;
10069
10070 // C++11 [basic.types] p11:
10071 // If two types T1 and T2 are the same type, then T1 and T2 are
10072 // layout-compatible types.
10073 if (C.hasSameType(T1, T2))
10074 return true;
10075
10076 T1 = T1.getCanonicalType().getUnqualifiedType();
10077 T2 = T2.getCanonicalType().getUnqualifiedType();
10078
10079 const Type::TypeClass TC1 = T1->getTypeClass();
10080 const Type::TypeClass TC2 = T2->getTypeClass();
10081
10082 if (TC1 != TC2)
10083 return false;
10084
10085 if (TC1 == Type::Enum) {
10086 return isLayoutCompatible(C,
10087 cast<EnumType>(T1)->getDecl(),
10088 cast<EnumType>(T2)->getDecl());
10089 } else if (TC1 == Type::Record) {
10090 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10091 return false;
10092
10093 return isLayoutCompatible(C,
10094 cast<RecordType>(T1)->getDecl(),
10095 cast<RecordType>(T2)->getDecl());
10096 }
10097
10098 return false;
10099}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010100} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010101
10102//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10103
10104namespace {
10105/// \brief Given a type tag expression find the type tag itself.
10106///
10107/// \param TypeExpr Type tag expression, as it appears in user's code.
10108///
10109/// \param VD Declaration of an identifier that appears in a type tag.
10110///
10111/// \param MagicValue Type tag magic value.
10112bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10113 const ValueDecl **VD, uint64_t *MagicValue) {
10114 while(true) {
10115 if (!TypeExpr)
10116 return false;
10117
10118 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10119
10120 switch (TypeExpr->getStmtClass()) {
10121 case Stmt::UnaryOperatorClass: {
10122 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10123 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10124 TypeExpr = UO->getSubExpr();
10125 continue;
10126 }
10127 return false;
10128 }
10129
10130 case Stmt::DeclRefExprClass: {
10131 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10132 *VD = DRE->getDecl();
10133 return true;
10134 }
10135
10136 case Stmt::IntegerLiteralClass: {
10137 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10138 llvm::APInt MagicValueAPInt = IL->getValue();
10139 if (MagicValueAPInt.getActiveBits() <= 64) {
10140 *MagicValue = MagicValueAPInt.getZExtValue();
10141 return true;
10142 } else
10143 return false;
10144 }
10145
10146 case Stmt::BinaryConditionalOperatorClass:
10147 case Stmt::ConditionalOperatorClass: {
10148 const AbstractConditionalOperator *ACO =
10149 cast<AbstractConditionalOperator>(TypeExpr);
10150 bool Result;
10151 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10152 if (Result)
10153 TypeExpr = ACO->getTrueExpr();
10154 else
10155 TypeExpr = ACO->getFalseExpr();
10156 continue;
10157 }
10158 return false;
10159 }
10160
10161 case Stmt::BinaryOperatorClass: {
10162 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10163 if (BO->getOpcode() == BO_Comma) {
10164 TypeExpr = BO->getRHS();
10165 continue;
10166 }
10167 return false;
10168 }
10169
10170 default:
10171 return false;
10172 }
10173 }
10174}
10175
10176/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10177///
10178/// \param TypeExpr Expression that specifies a type tag.
10179///
10180/// \param MagicValues Registered magic values.
10181///
10182/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10183/// kind.
10184///
10185/// \param TypeInfo Information about the corresponding C type.
10186///
10187/// \returns true if the corresponding C type was found.
10188bool GetMatchingCType(
10189 const IdentifierInfo *ArgumentKind,
10190 const Expr *TypeExpr, const ASTContext &Ctx,
10191 const llvm::DenseMap<Sema::TypeTagMagicValue,
10192 Sema::TypeTagData> *MagicValues,
10193 bool &FoundWrongKind,
10194 Sema::TypeTagData &TypeInfo) {
10195 FoundWrongKind = false;
10196
10197 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010198 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010199
10200 uint64_t MagicValue;
10201
10202 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10203 return false;
10204
10205 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010206 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010207 if (I->getArgumentKind() != ArgumentKind) {
10208 FoundWrongKind = true;
10209 return false;
10210 }
10211 TypeInfo.Type = I->getMatchingCType();
10212 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10213 TypeInfo.MustBeNull = I->getMustBeNull();
10214 return true;
10215 }
10216 return false;
10217 }
10218
10219 if (!MagicValues)
10220 return false;
10221
10222 llvm::DenseMap<Sema::TypeTagMagicValue,
10223 Sema::TypeTagData>::const_iterator I =
10224 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10225 if (I == MagicValues->end())
10226 return false;
10227
10228 TypeInfo = I->second;
10229 return true;
10230}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010231} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010232
10233void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10234 uint64_t MagicValue, QualType Type,
10235 bool LayoutCompatible,
10236 bool MustBeNull) {
10237 if (!TypeTagForDatatypeMagicValues)
10238 TypeTagForDatatypeMagicValues.reset(
10239 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10240
10241 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10242 (*TypeTagForDatatypeMagicValues)[Magic] =
10243 TypeTagData(Type, LayoutCompatible, MustBeNull);
10244}
10245
10246namespace {
10247bool IsSameCharType(QualType T1, QualType T2) {
10248 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10249 if (!BT1)
10250 return false;
10251
10252 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10253 if (!BT2)
10254 return false;
10255
10256 BuiltinType::Kind T1Kind = BT1->getKind();
10257 BuiltinType::Kind T2Kind = BT2->getKind();
10258
10259 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10260 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10261 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10262 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10263}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010264} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010265
10266void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10267 const Expr * const *ExprArgs) {
10268 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10269 bool IsPointerAttr = Attr->getIsPointer();
10270
10271 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10272 bool FoundWrongKind;
10273 TypeTagData TypeInfo;
10274 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10275 TypeTagForDatatypeMagicValues.get(),
10276 FoundWrongKind, TypeInfo)) {
10277 if (FoundWrongKind)
10278 Diag(TypeTagExpr->getExprLoc(),
10279 diag::warn_type_tag_for_datatype_wrong_kind)
10280 << TypeTagExpr->getSourceRange();
10281 return;
10282 }
10283
10284 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10285 if (IsPointerAttr) {
10286 // Skip implicit cast of pointer to `void *' (as a function argument).
10287 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010288 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010289 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010290 ArgumentExpr = ICE->getSubExpr();
10291 }
10292 QualType ArgumentType = ArgumentExpr->getType();
10293
10294 // Passing a `void*' pointer shouldn't trigger a warning.
10295 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10296 return;
10297
10298 if (TypeInfo.MustBeNull) {
10299 // Type tag with matching void type requires a null pointer.
10300 if (!ArgumentExpr->isNullPointerConstant(Context,
10301 Expr::NPC_ValueDependentIsNotNull)) {
10302 Diag(ArgumentExpr->getExprLoc(),
10303 diag::warn_type_safety_null_pointer_required)
10304 << ArgumentKind->getName()
10305 << ArgumentExpr->getSourceRange()
10306 << TypeTagExpr->getSourceRange();
10307 }
10308 return;
10309 }
10310
10311 QualType RequiredType = TypeInfo.Type;
10312 if (IsPointerAttr)
10313 RequiredType = Context.getPointerType(RequiredType);
10314
10315 bool mismatch = false;
10316 if (!TypeInfo.LayoutCompatible) {
10317 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10318
10319 // C++11 [basic.fundamental] p1:
10320 // Plain char, signed char, and unsigned char are three distinct types.
10321 //
10322 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10323 // char' depending on the current char signedness mode.
10324 if (mismatch)
10325 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10326 RequiredType->getPointeeType())) ||
10327 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10328 mismatch = false;
10329 } else
10330 if (IsPointerAttr)
10331 mismatch = !isLayoutCompatible(Context,
10332 ArgumentType->getPointeeType(),
10333 RequiredType->getPointeeType());
10334 else
10335 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10336
10337 if (mismatch)
10338 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010339 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010340 << TypeInfo.LayoutCompatible << RequiredType
10341 << ArgumentExpr->getSourceRange()
10342 << TypeTagExpr->getSourceRange();
10343}