1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements extra semantic analysis beyond what is enforced
11 // by the C type system.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Sema/SemaInternal.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/ExprOpenMP.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/AST/StmtObjC.h"
27 #include "clang/Analysis/Analyses/FormatString.h"
28 #include "clang/Basic/CharInfo.h"
29 #include "clang/Basic/TargetBuiltins.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
32 #include "clang/Sema/Initialization.h"
33 #include "clang/Sema/Lookup.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/Sema.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/Support/ConvertUTF.h"
40 #include "llvm/Support/raw_ostream.h"
42 using namespace clang;
45 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
46 unsigned ByteNo) const {
47 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
48 Context.getTargetInfo());
51 /// Checks that a call expression's argument count is the desired number.
52 /// This is useful when doing custom type-checking. Returns true on error.
53 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
54 unsigned argCount = call->getNumArgs();
55 if (argCount == desiredArgCount) return false;
57 if (argCount < desiredArgCount)
58 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
59 << 0 /*function call*/ << desiredArgCount << argCount
60 << call->getSourceRange();
62 // Highlight all the excess arguments.
63 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
64 call->getArg(argCount - 1)->getLocEnd());
66 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
67 << 0 /*function call*/ << desiredArgCount << argCount
68 << call->getArg(1)->getSourceRange();
71 /// Check that the first argument to __builtin_annotation is an integer
72 /// and the second argument is a non-wide string literal.
73 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
74 if (checkArgCount(S, TheCall, 2))
77 // First argument should be an integer.
78 Expr *ValArg = TheCall->getArg(0);
79 QualType Ty = ValArg->getType();
80 if (!Ty->isIntegerType()) {
81 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
82 << ValArg->getSourceRange();
86 // Second argument should be a constant string.
87 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
88 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
89 if (!Literal || !Literal->isAscii()) {
90 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
91 << StrArg->getSourceRange();
99 /// Check that the argument to __builtin_addressof is a glvalue, and set the
100 /// result type to the corresponding pointer type.
101 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
102 if (checkArgCount(S, TheCall, 1))
105 ExprResult Arg(TheCall->getArg(0));
106 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
107 if (ResultType.isNull())
110 TheCall->setArg(0, Arg.get());
111 TheCall->setType(ResultType);
115 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
116 if (checkArgCount(S, TheCall, 3))
119 // First two arguments should be integers.
120 for (unsigned I = 0; I < 2; ++I) {
121 Expr *Arg = TheCall->getArg(I);
122 QualType Ty = Arg->getType();
123 if (!Ty->isIntegerType()) {
124 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
125 << Ty << Arg->getSourceRange();
130 // Third argument should be a pointer to a non-const integer.
131 // IRGen correctly handles volatile, restrict, and address spaces, and
132 // the other qualifiers aren't possible.
134 Expr *Arg = TheCall->getArg(2);
135 QualType Ty = Arg->getType();
136 const auto *PtrTy = Ty->getAs<PointerType>();
137 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
138 !PtrTy->getPointeeType().isConstQualified())) {
139 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
140 << Ty << Arg->getSourceRange();
148 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
149 CallExpr *TheCall, unsigned SizeIdx,
150 unsigned DstSizeIdx) {
151 if (TheCall->getNumArgs() <= SizeIdx ||
152 TheCall->getNumArgs() <= DstSizeIdx)
155 const Expr *SizeArg = TheCall->getArg(SizeIdx);
156 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
158 llvm::APSInt Size, DstSize;
160 // find out if both sizes are known at compile time
161 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
162 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165 if (Size.ule(DstSize))
168 // confirmed overflow so generate the diagnostic.
169 IdentifierInfo *FnName = FDecl->getIdentifier();
170 SourceLocation SL = TheCall->getLocStart();
171 SourceRange SR = TheCall->getSourceRange();
173 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
177 if (checkArgCount(S, BuiltinCall, 2))
180 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
181 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
182 Expr *Call = BuiltinCall->getArg(0);
183 Expr *Chain = BuiltinCall->getArg(1);
185 if (Call->getStmtClass() != Stmt::CallExprClass) {
186 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
187 << Call->getSourceRange();
191 auto CE = cast<CallExpr>(Call);
192 if (CE->getCallee()->getType()->isBlockPointerType()) {
193 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
194 << Call->getSourceRange();
198 const Decl *TargetDecl = CE->getCalleeDecl();
199 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
200 if (FD->getBuiltinID()) {
201 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
202 << Call->getSourceRange();
206 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
207 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
208 << Call->getSourceRange();
212 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
213 if (ChainResult.isInvalid())
215 if (!ChainResult.get()->getType()->isPointerType()) {
216 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
217 << Chain->getSourceRange();
221 QualType ReturnTy = CE->getCallReturnType(S.Context);
222 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
223 QualType BuiltinTy = S.Context.getFunctionType(
224 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
225 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
230 BuiltinCall->setType(CE->getType());
231 BuiltinCall->setValueKind(CE->getValueKind());
232 BuiltinCall->setObjectKind(CE->getObjectKind());
233 BuiltinCall->setCallee(Builtin);
234 BuiltinCall->setArg(1, ChainResult.get());
239 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
240 Scope::ScopeFlags NeededScopeFlags,
242 // Scopes aren't available during instantiation. Fortunately, builtin
243 // functions cannot be template args so they cannot be formed through template
244 // instantiation. Therefore checking once during the parse is sufficient.
245 if (!SemaRef.ActiveTemplateInstantiations.empty())
248 Scope *S = SemaRef.getCurScope();
249 while (S && !S->isSEHExceptScope())
251 if (!S || !(S->getFlags() & NeededScopeFlags)) {
252 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
253 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
254 << DRE->getDecl()->getIdentifier();
262 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
264 ExprResult TheCallResult(TheCall);
266 // Find out if any arguments are required to be integer constant expressions.
267 unsigned ICEArguments = 0;
268 ASTContext::GetBuiltinTypeError Error;
269 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
270 if (Error != ASTContext::GE_None)
271 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
273 // If any arguments are required to be ICE's, check and diagnose.
274 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
275 // Skip arguments not required to be ICE's.
276 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
279 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
281 ICEArguments &= ~(1 << ArgNo);
285 case Builtin::BI__builtin___CFStringMakeConstantString:
286 assert(TheCall->getNumArgs() == 1 &&
287 "Wrong # arguments to builtin CFStringMakeConstantString");
288 if (CheckObjCString(TheCall->getArg(0)))
291 case Builtin::BI__builtin_stdarg_start:
292 case Builtin::BI__builtin_va_start:
293 if (SemaBuiltinVAStart(TheCall))
296 case Builtin::BI__va_start: {
297 switch (Context.getTargetInfo().getTriple().getArch()) {
298 case llvm::Triple::arm:
299 case llvm::Triple::thumb:
300 if (SemaBuiltinVAStartARM(TheCall))
304 if (SemaBuiltinVAStart(TheCall))
310 case Builtin::BI__builtin_isgreater:
311 case Builtin::BI__builtin_isgreaterequal:
312 case Builtin::BI__builtin_isless:
313 case Builtin::BI__builtin_islessequal:
314 case Builtin::BI__builtin_islessgreater:
315 case Builtin::BI__builtin_isunordered:
316 if (SemaBuiltinUnorderedCompare(TheCall))
319 case Builtin::BI__builtin_fpclassify:
320 if (SemaBuiltinFPClassification(TheCall, 6))
323 case Builtin::BI__builtin_isfinite:
324 case Builtin::BI__builtin_isinf:
325 case Builtin::BI__builtin_isinf_sign:
326 case Builtin::BI__builtin_isnan:
327 case Builtin::BI__builtin_isnormal:
328 if (SemaBuiltinFPClassification(TheCall, 1))
331 case Builtin::BI__builtin_shufflevector:
332 return SemaBuiltinShuffleVector(TheCall);
333 // TheCall will be freed by the smart pointer here, but that's fine, since
334 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
335 case Builtin::BI__builtin_prefetch:
336 if (SemaBuiltinPrefetch(TheCall))
339 case Builtin::BI__assume:
340 case Builtin::BI__builtin_assume:
341 if (SemaBuiltinAssume(TheCall))
344 case Builtin::BI__builtin_assume_aligned:
345 if (SemaBuiltinAssumeAligned(TheCall))
348 case Builtin::BI__builtin_object_size:
349 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
352 case Builtin::BI__builtin_longjmp:
353 if (SemaBuiltinLongjmp(TheCall))
356 case Builtin::BI__builtin_setjmp:
357 if (SemaBuiltinSetjmp(TheCall))
360 case Builtin::BI_setjmp:
361 case Builtin::BI_setjmpex:
362 if (checkArgCount(*this, TheCall, 1))
366 case Builtin::BI__builtin_classify_type:
367 if (checkArgCount(*this, TheCall, 1)) return true;
368 TheCall->setType(Context.IntTy);
370 case Builtin::BI__builtin_constant_p:
371 if (checkArgCount(*this, TheCall, 1)) return true;
372 TheCall->setType(Context.IntTy);
374 case Builtin::BI__sync_fetch_and_add:
375 case Builtin::BI__sync_fetch_and_add_1:
376 case Builtin::BI__sync_fetch_and_add_2:
377 case Builtin::BI__sync_fetch_and_add_4:
378 case Builtin::BI__sync_fetch_and_add_8:
379 case Builtin::BI__sync_fetch_and_add_16:
380 case Builtin::BI__sync_fetch_and_sub:
381 case Builtin::BI__sync_fetch_and_sub_1:
382 case Builtin::BI__sync_fetch_and_sub_2:
383 case Builtin::BI__sync_fetch_and_sub_4:
384 case Builtin::BI__sync_fetch_and_sub_8:
385 case Builtin::BI__sync_fetch_and_sub_16:
386 case Builtin::BI__sync_fetch_and_or:
387 case Builtin::BI__sync_fetch_and_or_1:
388 case Builtin::BI__sync_fetch_and_or_2:
389 case Builtin::BI__sync_fetch_and_or_4:
390 case Builtin::BI__sync_fetch_and_or_8:
391 case Builtin::BI__sync_fetch_and_or_16:
392 case Builtin::BI__sync_fetch_and_and:
393 case Builtin::BI__sync_fetch_and_and_1:
394 case Builtin::BI__sync_fetch_and_and_2:
395 case Builtin::BI__sync_fetch_and_and_4:
396 case Builtin::BI__sync_fetch_and_and_8:
397 case Builtin::BI__sync_fetch_and_and_16:
398 case Builtin::BI__sync_fetch_and_xor:
399 case Builtin::BI__sync_fetch_and_xor_1:
400 case Builtin::BI__sync_fetch_and_xor_2:
401 case Builtin::BI__sync_fetch_and_xor_4:
402 case Builtin::BI__sync_fetch_and_xor_8:
403 case Builtin::BI__sync_fetch_and_xor_16:
404 case Builtin::BI__sync_fetch_and_nand:
405 case Builtin::BI__sync_fetch_and_nand_1:
406 case Builtin::BI__sync_fetch_and_nand_2:
407 case Builtin::BI__sync_fetch_and_nand_4:
408 case Builtin::BI__sync_fetch_and_nand_8:
409 case Builtin::BI__sync_fetch_and_nand_16:
410 case Builtin::BI__sync_add_and_fetch:
411 case Builtin::BI__sync_add_and_fetch_1:
412 case Builtin::BI__sync_add_and_fetch_2:
413 case Builtin::BI__sync_add_and_fetch_4:
414 case Builtin::BI__sync_add_and_fetch_8:
415 case Builtin::BI__sync_add_and_fetch_16:
416 case Builtin::BI__sync_sub_and_fetch:
417 case Builtin::BI__sync_sub_and_fetch_1:
418 case Builtin::BI__sync_sub_and_fetch_2:
419 case Builtin::BI__sync_sub_and_fetch_4:
420 case Builtin::BI__sync_sub_and_fetch_8:
421 case Builtin::BI__sync_sub_and_fetch_16:
422 case Builtin::BI__sync_and_and_fetch:
423 case Builtin::BI__sync_and_and_fetch_1:
424 case Builtin::BI__sync_and_and_fetch_2:
425 case Builtin::BI__sync_and_and_fetch_4:
426 case Builtin::BI__sync_and_and_fetch_8:
427 case Builtin::BI__sync_and_and_fetch_16:
428 case Builtin::BI__sync_or_and_fetch:
429 case Builtin::BI__sync_or_and_fetch_1:
430 case Builtin::BI__sync_or_and_fetch_2:
431 case Builtin::BI__sync_or_and_fetch_4:
432 case Builtin::BI__sync_or_and_fetch_8:
433 case Builtin::BI__sync_or_and_fetch_16:
434 case Builtin::BI__sync_xor_and_fetch:
435 case Builtin::BI__sync_xor_and_fetch_1:
436 case Builtin::BI__sync_xor_and_fetch_2:
437 case Builtin::BI__sync_xor_and_fetch_4:
438 case Builtin::BI__sync_xor_and_fetch_8:
439 case Builtin::BI__sync_xor_and_fetch_16:
440 case Builtin::BI__sync_nand_and_fetch:
441 case Builtin::BI__sync_nand_and_fetch_1:
442 case Builtin::BI__sync_nand_and_fetch_2:
443 case Builtin::BI__sync_nand_and_fetch_4:
444 case Builtin::BI__sync_nand_and_fetch_8:
445 case Builtin::BI__sync_nand_and_fetch_16:
446 case Builtin::BI__sync_val_compare_and_swap:
447 case Builtin::BI__sync_val_compare_and_swap_1:
448 case Builtin::BI__sync_val_compare_and_swap_2:
449 case Builtin::BI__sync_val_compare_and_swap_4:
450 case Builtin::BI__sync_val_compare_and_swap_8:
451 case Builtin::BI__sync_val_compare_and_swap_16:
452 case Builtin::BI__sync_bool_compare_and_swap:
453 case Builtin::BI__sync_bool_compare_and_swap_1:
454 case Builtin::BI__sync_bool_compare_and_swap_2:
455 case Builtin::BI__sync_bool_compare_and_swap_4:
456 case Builtin::BI__sync_bool_compare_and_swap_8:
457 case Builtin::BI__sync_bool_compare_and_swap_16:
458 case Builtin::BI__sync_lock_test_and_set:
459 case Builtin::BI__sync_lock_test_and_set_1:
460 case Builtin::BI__sync_lock_test_and_set_2:
461 case Builtin::BI__sync_lock_test_and_set_4:
462 case Builtin::BI__sync_lock_test_and_set_8:
463 case Builtin::BI__sync_lock_test_and_set_16:
464 case Builtin::BI__sync_lock_release:
465 case Builtin::BI__sync_lock_release_1:
466 case Builtin::BI__sync_lock_release_2:
467 case Builtin::BI__sync_lock_release_4:
468 case Builtin::BI__sync_lock_release_8:
469 case Builtin::BI__sync_lock_release_16:
470 case Builtin::BI__sync_swap:
471 case Builtin::BI__sync_swap_1:
472 case Builtin::BI__sync_swap_2:
473 case Builtin::BI__sync_swap_4:
474 case Builtin::BI__sync_swap_8:
475 case Builtin::BI__sync_swap_16:
476 return SemaBuiltinAtomicOverloaded(TheCallResult);
477 case Builtin::BI__builtin_nontemporal_load:
478 case Builtin::BI__builtin_nontemporal_store:
479 return SemaBuiltinNontemporalOverloaded(TheCallResult);
480 #define BUILTIN(ID, TYPE, ATTRS)
481 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
482 case Builtin::BI##ID: \
483 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
484 #include "clang/Basic/Builtins.def"
485 case Builtin::BI__builtin_annotation:
486 if (SemaBuiltinAnnotation(*this, TheCall))
489 case Builtin::BI__builtin_addressof:
490 if (SemaBuiltinAddressof(*this, TheCall))
493 case Builtin::BI__builtin_add_overflow:
494 case Builtin::BI__builtin_sub_overflow:
495 case Builtin::BI__builtin_mul_overflow:
496 if (SemaBuiltinOverflow(*this, TheCall))
499 case Builtin::BI__builtin_operator_new:
500 case Builtin::BI__builtin_operator_delete:
501 if (!getLangOpts().CPlusPlus) {
502 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
503 << (BuiltinID == Builtin::BI__builtin_operator_new
504 ? "__builtin_operator_new"
505 : "__builtin_operator_delete")
509 // CodeGen assumes it can find the global new and delete to call,
510 // so ensure that they are declared.
511 DeclareGlobalNewDelete();
514 // check secure string manipulation functions where overflows
515 // are detectable at compile time
516 case Builtin::BI__builtin___memcpy_chk:
517 case Builtin::BI__builtin___memmove_chk:
518 case Builtin::BI__builtin___memset_chk:
519 case Builtin::BI__builtin___strlcat_chk:
520 case Builtin::BI__builtin___strlcpy_chk:
521 case Builtin::BI__builtin___strncat_chk:
522 case Builtin::BI__builtin___strncpy_chk:
523 case Builtin::BI__builtin___stpncpy_chk:
524 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
526 case Builtin::BI__builtin___memccpy_chk:
527 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
529 case Builtin::BI__builtin___snprintf_chk:
530 case Builtin::BI__builtin___vsnprintf_chk:
531 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
534 case Builtin::BI__builtin_call_with_static_chain:
535 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
539 case Builtin::BI__exception_code:
540 case Builtin::BI_exception_code: {
541 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
542 diag::err_seh___except_block))
546 case Builtin::BI__exception_info:
547 case Builtin::BI_exception_info: {
548 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
549 diag::err_seh___except_filter))
554 case Builtin::BI__GetExceptionInfo:
555 if (checkArgCount(*this, TheCall, 1))
558 if (CheckCXXThrowOperand(
559 TheCall->getLocStart(),
560 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
564 TheCall->setType(Context.VoidPtrTy);
569 // Since the target specific builtins for each arch overlap, only check those
570 // of the arch we are compiling for.
571 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
572 switch (Context.getTargetInfo().getTriple().getArch()) {
573 case llvm::Triple::arm:
574 case llvm::Triple::armeb:
575 case llvm::Triple::thumb:
576 case llvm::Triple::thumbeb:
577 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
580 case llvm::Triple::aarch64:
581 case llvm::Triple::aarch64_be:
582 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
585 case llvm::Triple::mips:
586 case llvm::Triple::mipsel:
587 case llvm::Triple::mips64:
588 case llvm::Triple::mips64el:
589 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
592 case llvm::Triple::systemz:
593 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
596 case llvm::Triple::x86:
597 case llvm::Triple::x86_64:
598 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
601 case llvm::Triple::ppc:
602 case llvm::Triple::ppc64:
603 case llvm::Triple::ppc64le:
604 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
612 return TheCallResult;
615 // Get the valid immediate range for the specified NEON type code.
616 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
617 NeonTypeFlags Type(t);
618 int IsQuad = ForceQuad ? true : Type.isQuad();
619 switch (Type.getEltType()) {
620 case NeonTypeFlags::Int8:
621 case NeonTypeFlags::Poly8:
622 return shift ? 7 : (8 << IsQuad) - 1;
623 case NeonTypeFlags::Int16:
624 case NeonTypeFlags::Poly16:
625 return shift ? 15 : (4 << IsQuad) - 1;
626 case NeonTypeFlags::Int32:
627 return shift ? 31 : (2 << IsQuad) - 1;
628 case NeonTypeFlags::Int64:
629 case NeonTypeFlags::Poly64:
630 return shift ? 63 : (1 << IsQuad) - 1;
631 case NeonTypeFlags::Poly128:
632 return shift ? 127 : (1 << IsQuad) - 1;
633 case NeonTypeFlags::Float16:
634 assert(!shift && "cannot shift float types!");
635 return (4 << IsQuad) - 1;
636 case NeonTypeFlags::Float32:
637 assert(!shift && "cannot shift float types!");
638 return (2 << IsQuad) - 1;
639 case NeonTypeFlags::Float64:
640 assert(!shift && "cannot shift float types!");
641 return (1 << IsQuad) - 1;
643 llvm_unreachable("Invalid NeonTypeFlag!");
646 /// getNeonEltType - Return the QualType corresponding to the elements of
647 /// the vector type specified by the NeonTypeFlags. This is used to check
648 /// the pointer arguments for Neon load/store intrinsics.
649 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
650 bool IsPolyUnsigned, bool IsInt64Long) {
651 switch (Flags.getEltType()) {
652 case NeonTypeFlags::Int8:
653 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
654 case NeonTypeFlags::Int16:
655 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
656 case NeonTypeFlags::Int32:
657 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
658 case NeonTypeFlags::Int64:
660 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
662 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
663 : Context.LongLongTy;
664 case NeonTypeFlags::Poly8:
665 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
666 case NeonTypeFlags::Poly16:
667 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
668 case NeonTypeFlags::Poly64:
670 return Context.UnsignedLongTy;
672 return Context.UnsignedLongLongTy;
673 case NeonTypeFlags::Poly128:
675 case NeonTypeFlags::Float16:
676 return Context.HalfTy;
677 case NeonTypeFlags::Float32:
678 return Context.FloatTy;
679 case NeonTypeFlags::Float64:
680 return Context.DoubleTy;
682 llvm_unreachable("Invalid NeonTypeFlag!");
685 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
690 bool HasConstPtr = false;
692 #define GET_NEON_OVERLOAD_CHECK
693 #include "clang/Basic/arm_neon.inc"
694 #undef GET_NEON_OVERLOAD_CHECK
697 // For NEON intrinsics which are overloaded on vector element type, validate
698 // the immediate which specifies which variant to emit.
699 unsigned ImmArg = TheCall->getNumArgs()-1;
701 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
704 TV = Result.getLimitedValue(64);
705 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
706 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
707 << TheCall->getArg(ImmArg)->getSourceRange();
710 if (PtrArgNum >= 0) {
711 // Check that pointer arguments have the specified type.
712 Expr *Arg = TheCall->getArg(PtrArgNum);
713 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
714 Arg = ICE->getSubExpr();
715 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
716 QualType RHSTy = RHS.get()->getType();
718 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
719 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
721 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
723 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
725 EltTy = EltTy.withConst();
726 QualType LHSTy = Context.getPointerType(EltTy);
727 AssignConvertType ConvTy;
728 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
731 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
732 RHS.get(), AA_Assigning))
736 // For NEON intrinsics which take an immediate value as part of the
737 // instruction, range check them here.
738 unsigned i = 0, l = 0, u = 0;
742 #define GET_NEON_IMMEDIATE_CHECK
743 #include "clang/Basic/arm_neon.inc"
744 #undef GET_NEON_IMMEDIATE_CHECK
747 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
750 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
752 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
753 BuiltinID == ARM::BI__builtin_arm_ldaex ||
754 BuiltinID == ARM::BI__builtin_arm_strex ||
755 BuiltinID == ARM::BI__builtin_arm_stlex ||
756 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
757 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
758 BuiltinID == AArch64::BI__builtin_arm_strex ||
759 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
760 "unexpected ARM builtin");
761 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
762 BuiltinID == ARM::BI__builtin_arm_ldaex ||
763 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
764 BuiltinID == AArch64::BI__builtin_arm_ldaex;
766 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
768 // Ensure that we have the proper number of arguments.
769 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
772 // Inspect the pointer argument of the atomic builtin. This should always be
773 // a pointer type, whose element is an integral scalar or pointer type.
774 // Because it is a pointer type, we don't have to worry about any implicit
776 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
777 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
778 if (PointerArgRes.isInvalid())
780 PointerArg = PointerArgRes.get();
782 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
784 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
785 << PointerArg->getType() << PointerArg->getSourceRange();
789 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
790 // task is to insert the appropriate casts into the AST. First work out just
791 // what the appropriate type is.
792 QualType ValType = pointerType->getPointeeType();
793 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
797 // Issue a warning if the cast is dodgy.
798 CastKind CastNeeded = CK_NoOp;
799 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
800 CastNeeded = CK_BitCast;
801 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
802 << PointerArg->getType()
803 << Context.getPointerType(AddrType)
804 << AA_Passing << PointerArg->getSourceRange();
807 // Finally, do the cast and replace the argument with the corrected version.
808 AddrType = Context.getPointerType(AddrType);
809 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
810 if (PointerArgRes.isInvalid())
812 PointerArg = PointerArgRes.get();
814 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
816 // In general, we allow ints, floats and pointers to be loaded and stored.
817 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
818 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
819 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
820 << PointerArg->getType() << PointerArg->getSourceRange();
824 // But ARM doesn't have instructions to deal with 128-bit versions.
825 if (Context.getTypeSize(ValType) > MaxWidth) {
826 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
827 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
828 << PointerArg->getType() << PointerArg->getSourceRange();
832 switch (ValType.getObjCLifetime()) {
833 case Qualifiers::OCL_None:
834 case Qualifiers::OCL_ExplicitNone:
838 case Qualifiers::OCL_Weak:
839 case Qualifiers::OCL_Strong:
840 case Qualifiers::OCL_Autoreleasing:
841 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
842 << ValType << PointerArg->getSourceRange();
848 TheCall->setType(ValType);
852 // Initialize the argument to be stored.
853 ExprResult ValArg = TheCall->getArg(0);
854 InitializedEntity Entity = InitializedEntity::InitializeParameter(
855 Context, ValType, /*consume*/ false);
856 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
857 if (ValArg.isInvalid())
859 TheCall->setArg(0, ValArg.get());
861 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
862 // but the custom checker bypasses all default analysis.
863 TheCall->setType(Context.IntTy);
867 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
870 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
871 BuiltinID == ARM::BI__builtin_arm_ldaex ||
872 BuiltinID == ARM::BI__builtin_arm_strex ||
873 BuiltinID == ARM::BI__builtin_arm_stlex) {
874 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
877 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
878 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
879 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
882 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
883 BuiltinID == ARM::BI__builtin_arm_wsr64)
884 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
886 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
887 BuiltinID == ARM::BI__builtin_arm_rsrp ||
888 BuiltinID == ARM::BI__builtin_arm_wsr ||
889 BuiltinID == ARM::BI__builtin_arm_wsrp)
890 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
892 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
895 // For intrinsics which take an immediate value as part of the instruction,
896 // range check them here.
897 unsigned i = 0, l = 0, u = 0;
899 default: return false;
900 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
901 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
902 case ARM::BI__builtin_arm_vcvtr_f:
903 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
904 case ARM::BI__builtin_arm_dmb:
905 case ARM::BI__builtin_arm_dsb:
906 case ARM::BI__builtin_arm_isb:
907 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
910 // FIXME: VFP Intrinsics should error if VFP not present.
911 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
914 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
918 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
919 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
920 BuiltinID == AArch64::BI__builtin_arm_strex ||
921 BuiltinID == AArch64::BI__builtin_arm_stlex) {
922 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
925 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
926 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
927 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
928 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
929 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
932 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
933 BuiltinID == AArch64::BI__builtin_arm_wsr64)
934 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
936 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
937 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
938 BuiltinID == AArch64::BI__builtin_arm_wsr ||
939 BuiltinID == AArch64::BI__builtin_arm_wsrp)
940 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
942 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
945 // For intrinsics which take an immediate value as part of the instruction,
946 // range check them here.
947 unsigned i = 0, l = 0, u = 0;
949 default: return false;
950 case AArch64::BI__builtin_arm_dmb:
951 case AArch64::BI__builtin_arm_dsb:
952 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
955 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
958 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
959 unsigned i = 0, l = 0, u = 0;
961 default: return false;
962 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
963 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
964 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
965 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
966 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
967 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
968 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
971 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
974 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
975 unsigned i = 0, l = 0, u = 0;
976 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
977 BuiltinID == PPC::BI__builtin_divdeu ||
978 BuiltinID == PPC::BI__builtin_bpermd;
979 bool IsTarget64Bit = Context.getTargetInfo()
980 .getTypeWidth(Context
982 .getIntPtrType()) == 64;
983 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
984 BuiltinID == PPC::BI__builtin_divweu ||
985 BuiltinID == PPC::BI__builtin_divde ||
986 BuiltinID == PPC::BI__builtin_divdeu;
988 if (Is64BitBltin && !IsTarget64Bit)
989 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
990 << TheCall->getSourceRange();
992 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
993 (BuiltinID == PPC::BI__builtin_bpermd &&
994 !Context.getTargetInfo().hasFeature("bpermd")))
995 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
996 << TheCall->getSourceRange();
999 default: return false;
1000 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1001 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1002 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1003 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1004 case PPC::BI__builtin_tbegin:
1005 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1006 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1007 case PPC::BI__builtin_tabortwc:
1008 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1009 case PPC::BI__builtin_tabortwci:
1010 case PPC::BI__builtin_tabortdci:
1011 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1012 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1014 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1017 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1018 CallExpr *TheCall) {
1019 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1020 Expr *Arg = TheCall->getArg(0);
1021 llvm::APSInt AbortCode(32);
1022 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1023 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1024 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1025 << Arg->getSourceRange();
1028 // For intrinsics which take an immediate value as part of the instruction,
1029 // range check them here.
1030 unsigned i = 0, l = 0, u = 0;
1031 switch (BuiltinID) {
1032 default: return false;
1033 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1034 case SystemZ::BI__builtin_s390_verimb:
1035 case SystemZ::BI__builtin_s390_verimh:
1036 case SystemZ::BI__builtin_s390_verimf:
1037 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1038 case SystemZ::BI__builtin_s390_vfaeb:
1039 case SystemZ::BI__builtin_s390_vfaeh:
1040 case SystemZ::BI__builtin_s390_vfaef:
1041 case SystemZ::BI__builtin_s390_vfaebs:
1042 case SystemZ::BI__builtin_s390_vfaehs:
1043 case SystemZ::BI__builtin_s390_vfaefs:
1044 case SystemZ::BI__builtin_s390_vfaezb:
1045 case SystemZ::BI__builtin_s390_vfaezh:
1046 case SystemZ::BI__builtin_s390_vfaezf:
1047 case SystemZ::BI__builtin_s390_vfaezbs:
1048 case SystemZ::BI__builtin_s390_vfaezhs:
1049 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1050 case SystemZ::BI__builtin_s390_vfidb:
1051 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1052 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1053 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1054 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1055 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1056 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1057 case SystemZ::BI__builtin_s390_vstrcb:
1058 case SystemZ::BI__builtin_s390_vstrch:
1059 case SystemZ::BI__builtin_s390_vstrcf:
1060 case SystemZ::BI__builtin_s390_vstrczb:
1061 case SystemZ::BI__builtin_s390_vstrczh:
1062 case SystemZ::BI__builtin_s390_vstrczf:
1063 case SystemZ::BI__builtin_s390_vstrcbs:
1064 case SystemZ::BI__builtin_s390_vstrchs:
1065 case SystemZ::BI__builtin_s390_vstrcfs:
1066 case SystemZ::BI__builtin_s390_vstrczbs:
1067 case SystemZ::BI__builtin_s390_vstrczhs:
1068 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1070 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1073 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1074 /// This checks that the target supports __builtin_cpu_supports and
1075 /// that the string argument is constant and valid.
1076 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1077 Expr *Arg = TheCall->getArg(0);
1079 // Check if the argument is a string literal.
1080 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1081 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1082 << Arg->getSourceRange();
1084 // Check the contents of the string.
1086 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1087 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1088 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1089 << Arg->getSourceRange();
1093 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1094 unsigned i = 0, l = 0, u = 0;
1095 switch (BuiltinID) {
1096 default: return false;
1097 case X86::BI__builtin_cpu_supports:
1098 return SemaBuiltinCpuSupports(*this, TheCall);
1099 case X86::BI__builtin_ms_va_start:
1100 return SemaBuiltinMSVAStart(TheCall);
1101 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
1102 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
1103 case X86::BI__builtin_ia32_vpermil2pd:
1104 case X86::BI__builtin_ia32_vpermil2pd256:
1105 case X86::BI__builtin_ia32_vpermil2ps:
1106 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
1107 case X86::BI__builtin_ia32_cmpb128_mask:
1108 case X86::BI__builtin_ia32_cmpw128_mask:
1109 case X86::BI__builtin_ia32_cmpd128_mask:
1110 case X86::BI__builtin_ia32_cmpq128_mask:
1111 case X86::BI__builtin_ia32_cmpb256_mask:
1112 case X86::BI__builtin_ia32_cmpw256_mask:
1113 case X86::BI__builtin_ia32_cmpd256_mask:
1114 case X86::BI__builtin_ia32_cmpq256_mask:
1115 case X86::BI__builtin_ia32_cmpb512_mask:
1116 case X86::BI__builtin_ia32_cmpw512_mask:
1117 case X86::BI__builtin_ia32_cmpd512_mask:
1118 case X86::BI__builtin_ia32_cmpq512_mask:
1119 case X86::BI__builtin_ia32_ucmpb128_mask:
1120 case X86::BI__builtin_ia32_ucmpw128_mask:
1121 case X86::BI__builtin_ia32_ucmpd128_mask:
1122 case X86::BI__builtin_ia32_ucmpq128_mask:
1123 case X86::BI__builtin_ia32_ucmpb256_mask:
1124 case X86::BI__builtin_ia32_ucmpw256_mask:
1125 case X86::BI__builtin_ia32_ucmpd256_mask:
1126 case X86::BI__builtin_ia32_ucmpq256_mask:
1127 case X86::BI__builtin_ia32_ucmpb512_mask:
1128 case X86::BI__builtin_ia32_ucmpw512_mask:
1129 case X86::BI__builtin_ia32_ucmpd512_mask:
1130 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
1131 case X86::BI__builtin_ia32_roundps:
1132 case X86::BI__builtin_ia32_roundpd:
1133 case X86::BI__builtin_ia32_roundps256:
1134 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1135 case X86::BI__builtin_ia32_roundss:
1136 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1137 case X86::BI__builtin_ia32_cmpps:
1138 case X86::BI__builtin_ia32_cmpss:
1139 case X86::BI__builtin_ia32_cmppd:
1140 case X86::BI__builtin_ia32_cmpsd:
1141 case X86::BI__builtin_ia32_cmpps256:
1142 case X86::BI__builtin_ia32_cmppd256:
1143 case X86::BI__builtin_ia32_cmpps512_mask:
1144 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
1145 case X86::BI__builtin_ia32_vpcomub:
1146 case X86::BI__builtin_ia32_vpcomuw:
1147 case X86::BI__builtin_ia32_vpcomud:
1148 case X86::BI__builtin_ia32_vpcomuq:
1149 case X86::BI__builtin_ia32_vpcomb:
1150 case X86::BI__builtin_ia32_vpcomw:
1151 case X86::BI__builtin_ia32_vpcomd:
1152 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
1154 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1157 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1158 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
1159 /// Returns true when the format fits the function and the FormatStringInfo has
1161 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1162 FormatStringInfo *FSI) {
1163 FSI->HasVAListArg = Format->getFirstArg() == 0;
1164 FSI->FormatIdx = Format->getFormatIdx() - 1;
1165 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
1167 // The way the format attribute works in GCC, the implicit this argument
1168 // of member functions is counted. However, it doesn't appear in our own
1169 // lists, so decrement format_idx in that case.
1171 if(FSI->FormatIdx == 0)
1174 if (FSI->FirstDataArg != 0)
1175 --FSI->FirstDataArg;
1180 /// Checks if a the given expression evaluates to null.
1182 /// \brief Returns true if the value evaluates to null.
1183 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
1184 // If the expression has non-null type, it doesn't evaluate to null.
1185 if (auto nullability
1186 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1187 if (*nullability == NullabilityKind::NonNull)
1191 // As a special case, transparent unions initialized with zero are
1192 // considered null for the purposes of the nonnull attribute.
1193 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
1194 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1195 if (const CompoundLiteralExpr *CLE =
1196 dyn_cast<CompoundLiteralExpr>(Expr))
1197 if (const InitListExpr *ILE =
1198 dyn_cast<InitListExpr>(CLE->getInitializer()))
1199 Expr = ILE->getInit(0);
1203 return (!Expr->isValueDependent() &&
1204 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1208 static void CheckNonNullArgument(Sema &S,
1209 const Expr *ArgExpr,
1210 SourceLocation CallSiteLoc) {
1211 if (CheckNonNullExpr(S, ArgExpr))
1212 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1213 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
1216 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1217 FormatStringInfo FSI;
1218 if ((GetFormatStringType(Format) == FST_NSString) &&
1219 getFormatStringInfo(Format, false, &FSI)) {
1220 Idx = FSI.FormatIdx;
1225 /// \brief Diagnose use of %s directive in an NSString which is being passed
1226 /// as formatting string to formatting method.
1228 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1229 const NamedDecl *FDecl,
1233 bool Format = false;
1234 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1235 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
1240 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1241 if (S.GetFormatNSStringIdx(I, Idx)) {
1246 if (!Format || NumArgs <= Idx)
1248 const Expr *FormatExpr = Args[Idx];
1249 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1250 FormatExpr = CSCE->getSubExpr();
1251 const StringLiteral *FormatString;
1252 if (const ObjCStringLiteral *OSL =
1253 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1254 FormatString = OSL->getString();
1256 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1259 if (S.FormatStringHasSArg(FormatString)) {
1260 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1262 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1263 << FDecl->getDeclName();
1267 /// Determine whether the given type has a non-null nullability annotation.
1268 static bool isNonNullType(ASTContext &ctx, QualType type) {
1269 if (auto nullability = type->getNullability(ctx))
1270 return *nullability == NullabilityKind::NonNull;
1275 static void CheckNonNullArguments(Sema &S,
1276 const NamedDecl *FDecl,
1277 const FunctionProtoType *Proto,
1278 ArrayRef<const Expr *> Args,
1279 SourceLocation CallSiteLoc) {
1280 assert((FDecl || Proto) && "Need a function declaration or prototype");
1282 // Check the attributes attached to the method/function itself.
1283 llvm::SmallBitVector NonNullArgs;
1285 // Handle the nonnull attribute on the function/method declaration itself.
1286 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1287 if (!NonNull->args_size()) {
1288 // Easy case: all pointer arguments are nonnull.
1289 for (const auto *Arg : Args)
1290 if (S.isValidPointerAttrType(Arg->getType()))
1291 CheckNonNullArgument(S, Arg, CallSiteLoc);
1295 for (unsigned Val : NonNull->args()) {
1296 if (Val >= Args.size())
1298 if (NonNullArgs.empty())
1299 NonNullArgs.resize(Args.size());
1300 NonNullArgs.set(Val);
1305 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1306 // Handle the nonnull attribute on the parameters of the
1308 ArrayRef<ParmVarDecl*> parms;
1309 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1310 parms = FD->parameters();
1312 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1314 unsigned ParamIndex = 0;
1315 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1316 I != E; ++I, ++ParamIndex) {
1317 const ParmVarDecl *PVD = *I;
1318 if (PVD->hasAttr<NonNullAttr>() ||
1319 isNonNullType(S.Context, PVD->getType())) {
1320 if (NonNullArgs.empty())
1321 NonNullArgs.resize(Args.size());
1323 NonNullArgs.set(ParamIndex);
1327 // If we have a non-function, non-method declaration but no
1328 // function prototype, try to dig out the function prototype.
1330 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1331 QualType type = VD->getType().getNonReferenceType();
1332 if (auto pointerType = type->getAs<PointerType>())
1333 type = pointerType->getPointeeType();
1334 else if (auto blockType = type->getAs<BlockPointerType>())
1335 type = blockType->getPointeeType();
1336 // FIXME: data member pointers?
1338 // Dig out the function prototype, if there is one.
1339 Proto = type->getAs<FunctionProtoType>();
1343 // Fill in non-null argument information from the nullability
1344 // information on the parameter types (if we have them).
1347 for (auto paramType : Proto->getParamTypes()) {
1348 if (isNonNullType(S.Context, paramType)) {
1349 if (NonNullArgs.empty())
1350 NonNullArgs.resize(Args.size());
1352 NonNullArgs.set(Index);
1360 // Check for non-null arguments.
1361 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1362 ArgIndex != ArgIndexEnd; ++ArgIndex) {
1363 if (NonNullArgs[ArgIndex])
1364 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
1368 /// Handles the checks for format strings, non-POD arguments to vararg
1369 /// functions, and NULL arguments passed to non-NULL parameters.
1370 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1371 ArrayRef<const Expr *> Args, bool IsMemberFunction,
1372 SourceLocation Loc, SourceRange Range,
1373 VariadicCallType CallType) {
1374 // FIXME: We should check as much as we can in the template definition.
1375 if (CurContext->isDependentContext())
1378 // Printf and scanf checking.
1379 llvm::SmallBitVector CheckedVarArgs;
1381 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1382 // Only create vector if there are format attributes.
1383 CheckedVarArgs.resize(Args.size());
1385 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
1390 // Refuse POD arguments that weren't caught by the format string
1392 if (CallType != VariadicDoesNotApply) {
1393 unsigned NumParams = Proto ? Proto->getNumParams()
1394 : FDecl && isa<FunctionDecl>(FDecl)
1395 ? cast<FunctionDecl>(FDecl)->getNumParams()
1396 : FDecl && isa<ObjCMethodDecl>(FDecl)
1397 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1400 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
1401 // Args[ArgIdx] can be null in malformed code.
1402 if (const Expr *Arg = Args[ArgIdx]) {
1403 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1404 checkVariadicArgument(Arg, CallType);
1409 if (FDecl || Proto) {
1410 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
1412 // Type safety checking.
1414 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1415 CheckArgumentWithTypeTag(I, Args.data());
1420 /// CheckConstructorCall - Check a constructor call for correctness and safety
1421 /// properties not enforced by the C type system.
1422 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1423 ArrayRef<const Expr *> Args,
1424 const FunctionProtoType *Proto,
1425 SourceLocation Loc) {
1426 VariadicCallType CallType =
1427 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
1428 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1432 /// CheckFunctionCall - Check a direct function call for various correctness
1433 /// and safety properties not strictly enforced by the C type system.
1434 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1435 const FunctionProtoType *Proto) {
1436 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1437 isa<CXXMethodDecl>(FDecl);
1438 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1439 IsMemberOperatorCall;
1440 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1441 TheCall->getCallee());
1442 Expr** Args = TheCall->getArgs();
1443 unsigned NumArgs = TheCall->getNumArgs();
1444 if (IsMemberOperatorCall) {
1445 // If this is a call to a member operator, hide the first argument
1447 // FIXME: Our choice of AST representation here is less than ideal.
1451 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
1452 IsMemberFunction, TheCall->getRParenLoc(),
1453 TheCall->getCallee()->getSourceRange(), CallType);
1455 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1456 // None of the checks below are needed for functions that don't have
1457 // simple names (e.g., C++ conversion functions).
1461 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
1462 if (getLangOpts().ObjC1)
1463 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
1465 unsigned CMId = FDecl->getMemoryFunctionKind();
1469 // Handle memory setting and copying functions.
1470 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
1471 CheckStrlcpycatArguments(TheCall, FnInfo);
1472 else if (CMId == Builtin::BIstrncat)
1473 CheckStrncatArguments(TheCall, FnInfo);
1475 CheckMemaccessArguments(TheCall, CMId, FnInfo);
1480 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
1481 ArrayRef<const Expr *> Args) {
1482 VariadicCallType CallType =
1483 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
1485 checkCall(Method, nullptr, Args,
1486 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1492 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1493 const FunctionProtoType *Proto) {
1495 if (const auto *V = dyn_cast<VarDecl>(NDecl))
1496 Ty = V->getType().getNonReferenceType();
1497 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
1498 Ty = F->getType().getNonReferenceType();
1502 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1503 !Ty->isFunctionProtoType())
1506 VariadicCallType CallType;
1507 if (!Proto || !Proto->isVariadic()) {
1508 CallType = VariadicDoesNotApply;
1509 } else if (Ty->isBlockPointerType()) {
1510 CallType = VariadicBlock;
1511 } else { // Ty->isFunctionPointerType()
1512 CallType = VariadicFunction;
1515 checkCall(NDecl, Proto,
1516 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1517 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1518 TheCall->getCallee()->getSourceRange(), CallType);
1523 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1524 /// such as function pointers returned from functions.
1525 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
1526 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
1527 TheCall->getCallee());
1528 checkCall(/*FDecl=*/nullptr, Proto,
1529 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1530 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1531 TheCall->getCallee()->getSourceRange(), CallType);
1536 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1537 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1538 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1542 case AtomicExpr::AO__c11_atomic_init:
1543 llvm_unreachable("There is no ordering argument for an init");
1545 case AtomicExpr::AO__c11_atomic_load:
1546 case AtomicExpr::AO__atomic_load_n:
1547 case AtomicExpr::AO__atomic_load:
1548 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1549 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1551 case AtomicExpr::AO__c11_atomic_store:
1552 case AtomicExpr::AO__atomic_store:
1553 case AtomicExpr::AO__atomic_store_n:
1554 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1555 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1556 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1563 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1564 AtomicExpr::AtomicOp Op) {
1565 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1566 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1568 // All these operations take one of the following forms:
1570 // C __c11_atomic_init(A *, C)
1572 // C __c11_atomic_load(A *, int)
1574 // void __atomic_load(A *, CP, int)
1576 // C __c11_atomic_add(A *, M, int)
1578 // C __atomic_exchange_n(A *, CP, int)
1580 // void __atomic_exchange(A *, C *, CP, int)
1582 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1584 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1587 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1588 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1590 // C is an appropriate type,
1591 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1592 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1593 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1594 // the int parameters are for orderings.
1596 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1597 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1598 AtomicExpr::AO__atomic_load,
1599 "need to update code for modified C11 atomics");
1600 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1601 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1602 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1603 Op == AtomicExpr::AO__atomic_store_n ||
1604 Op == AtomicExpr::AO__atomic_exchange_n ||
1605 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1606 bool IsAddSub = false;
1609 case AtomicExpr::AO__c11_atomic_init:
1613 case AtomicExpr::AO__c11_atomic_load:
1614 case AtomicExpr::AO__atomic_load_n:
1618 case AtomicExpr::AO__c11_atomic_store:
1619 case AtomicExpr::AO__atomic_load:
1620 case AtomicExpr::AO__atomic_store:
1621 case AtomicExpr::AO__atomic_store_n:
1625 case AtomicExpr::AO__c11_atomic_fetch_add:
1626 case AtomicExpr::AO__c11_atomic_fetch_sub:
1627 case AtomicExpr::AO__atomic_fetch_add:
1628 case AtomicExpr::AO__atomic_fetch_sub:
1629 case AtomicExpr::AO__atomic_add_fetch:
1630 case AtomicExpr::AO__atomic_sub_fetch:
1633 case AtomicExpr::AO__c11_atomic_fetch_and:
1634 case AtomicExpr::AO__c11_atomic_fetch_or:
1635 case AtomicExpr::AO__c11_atomic_fetch_xor:
1636 case AtomicExpr::AO__atomic_fetch_and:
1637 case AtomicExpr::AO__atomic_fetch_or:
1638 case AtomicExpr::AO__atomic_fetch_xor:
1639 case AtomicExpr::AO__atomic_fetch_nand:
1640 case AtomicExpr::AO__atomic_and_fetch:
1641 case AtomicExpr::AO__atomic_or_fetch:
1642 case AtomicExpr::AO__atomic_xor_fetch:
1643 case AtomicExpr::AO__atomic_nand_fetch:
1647 case AtomicExpr::AO__c11_atomic_exchange:
1648 case AtomicExpr::AO__atomic_exchange_n:
1652 case AtomicExpr::AO__atomic_exchange:
1656 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1657 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1661 case AtomicExpr::AO__atomic_compare_exchange:
1662 case AtomicExpr::AO__atomic_compare_exchange_n:
1667 // Check we have the right number of arguments.
1668 if (TheCall->getNumArgs() < NumArgs[Form]) {
1669 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1670 << 0 << NumArgs[Form] << TheCall->getNumArgs()
1671 << TheCall->getCallee()->getSourceRange();
1673 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1674 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
1675 diag::err_typecheck_call_too_many_args)
1676 << 0 << NumArgs[Form] << TheCall->getNumArgs()
1677 << TheCall->getCallee()->getSourceRange();
1681 // Inspect the first argument of the atomic operation.
1682 Expr *Ptr = TheCall->getArg(0);
1683 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1684 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1686 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1687 << Ptr->getType() << Ptr->getSourceRange();
1691 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1692 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1693 QualType ValType = AtomTy; // 'C'
1695 if (!AtomTy->isAtomicType()) {
1696 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1697 << Ptr->getType() << Ptr->getSourceRange();
1700 if (AtomTy.isConstQualified()) {
1701 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1702 << Ptr->getType() << Ptr->getSourceRange();
1705 ValType = AtomTy->getAs<AtomicType>()->getValueType();
1706 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1707 if (ValType.isConstQualified()) {
1708 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1709 << Ptr->getType() << Ptr->getSourceRange();
1714 // For an arithmetic operation, the implied arithmetic must be well-formed.
1715 if (Form == Arithmetic) {
1716 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1717 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1718 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1719 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1722 if (!IsAddSub && !ValType->isIntegerType()) {
1723 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1724 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1727 if (IsC11 && ValType->isPointerType() &&
1728 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1729 diag::err_incomplete_type)) {
1732 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1733 // For __atomic_*_n operations, the value type must be a scalar integral or
1734 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1735 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1736 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1740 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1741 !AtomTy->isScalarType()) {
1742 // For GNU atomics, require a trivially-copyable type. This is not part of
1743 // the GNU atomics specification, but we enforce it for sanity.
1744 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1745 << Ptr->getType() << Ptr->getSourceRange();
1749 switch (ValType.getObjCLifetime()) {
1750 case Qualifiers::OCL_None:
1751 case Qualifiers::OCL_ExplicitNone:
1755 case Qualifiers::OCL_Weak:
1756 case Qualifiers::OCL_Strong:
1757 case Qualifiers::OCL_Autoreleasing:
1758 // FIXME: Can this happen? By this point, ValType should be known
1759 // to be trivially copyable.
1760 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1761 << ValType << Ptr->getSourceRange();
1765 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
1766 // volatile-ness of the pointee-type inject itself into the result or the
1768 ValType.removeLocalVolatile();
1769 QualType ResultType = ValType;
1770 if (Form == Copy || Form == GNUXchg || Form == Init)
1771 ResultType = Context.VoidTy;
1772 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1773 ResultType = Context.BoolTy;
1775 // The type of a parameter passed 'by value'. In the GNU atomics, such
1776 // arguments are actually passed as pointers.
1777 QualType ByValType = ValType; // 'CP'
1779 ByValType = Ptr->getType();
1781 // FIXME: __atomic_load allows the first argument to be a a pointer to const
1782 // but not the second argument. We need to manually remove possible const
1785 // The first argument --- the pointer --- has a fixed type; we
1786 // deduce the types of the rest of the arguments accordingly. Walk
1787 // the remaining arguments, converting them to the deduced value type.
1788 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1790 if (i < NumVals[Form] + 1) {
1793 // The second argument is the non-atomic operand. For arithmetic, this
1794 // is always passed by value, and for a compare_exchange it is always
1795 // passed by address. For the rest, GNU uses by-address and C11 uses
1797 assert(Form != Load);
1798 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1800 else if (Form == Copy || Form == Xchg)
1802 else if (Form == Arithmetic)
1803 Ty = Context.getPointerDiffType();
1805 Expr *ValArg = TheCall->getArg(i);
1807 // Keep address space of non-atomic pointer type.
1808 if (const PointerType *PtrTy =
1809 ValArg->getType()->getAs<PointerType>()) {
1810 AS = PtrTy->getPointeeType().getAddressSpace();
1812 Ty = Context.getPointerType(
1813 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
1817 // The third argument to compare_exchange / GNU exchange is a
1818 // (pointer to a) desired value.
1822 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1823 Ty = Context.BoolTy;
1827 // The order(s) are always converted to int.
1831 InitializedEntity Entity =
1832 InitializedEntity::InitializeParameter(Context, Ty, false);
1833 ExprResult Arg = TheCall->getArg(i);
1834 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1835 if (Arg.isInvalid())
1837 TheCall->setArg(i, Arg.get());
1840 // Permute the arguments into a 'consistent' order.
1841 SmallVector<Expr*, 5> SubExprs;
1842 SubExprs.push_back(Ptr);
1845 // Note, AtomicExpr::getVal1() has a special case for this atomic.
1846 SubExprs.push_back(TheCall->getArg(1)); // Val1
1849 SubExprs.push_back(TheCall->getArg(1)); // Order
1854 SubExprs.push_back(TheCall->getArg(2)); // Order
1855 SubExprs.push_back(TheCall->getArg(1)); // Val1
1858 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1859 SubExprs.push_back(TheCall->getArg(3)); // Order
1860 SubExprs.push_back(TheCall->getArg(1)); // Val1
1861 SubExprs.push_back(TheCall->getArg(2)); // Val2
1864 SubExprs.push_back(TheCall->getArg(3)); // Order
1865 SubExprs.push_back(TheCall->getArg(1)); // Val1
1866 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1867 SubExprs.push_back(TheCall->getArg(2)); // Val2
1870 SubExprs.push_back(TheCall->getArg(4)); // Order
1871 SubExprs.push_back(TheCall->getArg(1)); // Val1
1872 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1873 SubExprs.push_back(TheCall->getArg(2)); // Val2
1874 SubExprs.push_back(TheCall->getArg(3)); // Weak
1878 if (SubExprs.size() >= 2 && Form != Init) {
1879 llvm::APSInt Result(32);
1880 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1881 !isValidOrderingForOp(Result.getSExtValue(), Op))
1882 Diag(SubExprs[1]->getLocStart(),
1883 diag::warn_atomic_op_has_invalid_memory_order)
1884 << SubExprs[1]->getSourceRange();
1887 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1888 SubExprs, ResultType, Op,
1889 TheCall->getRParenLoc());
1891 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1892 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1893 Context.AtomicUsesUnsupportedLibcall(AE))
1894 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1895 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1901 /// checkBuiltinArgument - Given a call to a builtin function, perform
1902 /// normal type-checking on the given argument, updating the call in
1903 /// place. This is useful when a builtin function requires custom
1904 /// type-checking for some of its arguments but not necessarily all of
1907 /// Returns true on error.
1908 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1909 FunctionDecl *Fn = E->getDirectCallee();
1910 assert(Fn && "builtin call without direct callee!");
1912 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1913 InitializedEntity Entity =
1914 InitializedEntity::InitializeParameter(S.Context, Param);
1916 ExprResult Arg = E->getArg(0);
1917 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1918 if (Arg.isInvalid())
1921 E->setArg(ArgIndex, Arg.get());
1925 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
1926 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
1927 /// type of its first argument. The main ActOnCallExpr routines have already
1928 /// promoted the types of arguments because all of these calls are prototyped as
1931 /// This function goes through and does final semantic checking for these
1934 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1935 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1936 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1937 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1939 // Ensure that we have at least one argument to do type inference from.
1940 if (TheCall->getNumArgs() < 1) {
1941 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1942 << 0 << 1 << TheCall->getNumArgs()
1943 << TheCall->getCallee()->getSourceRange();
1947 // Inspect the first argument of the atomic builtin. This should always be
1948 // a pointer type, whose element is an integral scalar or pointer type.
1949 // Because it is a pointer type, we don't have to worry about any implicit
1951 // FIXME: We don't allow floating point scalars as input.
1952 Expr *FirstArg = TheCall->getArg(0);
1953 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1954 if (FirstArgResult.isInvalid())
1956 FirstArg = FirstArgResult.get();
1957 TheCall->setArg(0, FirstArg);
1959 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1961 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1962 << FirstArg->getType() << FirstArg->getSourceRange();
1966 QualType ValType = pointerType->getPointeeType();
1967 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1968 !ValType->isBlockPointerType()) {
1969 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1970 << FirstArg->getType() << FirstArg->getSourceRange();
1974 switch (ValType.getObjCLifetime()) {
1975 case Qualifiers::OCL_None:
1976 case Qualifiers::OCL_ExplicitNone:
1980 case Qualifiers::OCL_Weak:
1981 case Qualifiers::OCL_Strong:
1982 case Qualifiers::OCL_Autoreleasing:
1983 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1984 << ValType << FirstArg->getSourceRange();
1988 // Strip any qualifiers off ValType.
1989 ValType = ValType.getUnqualifiedType();
1991 // The majority of builtins return a value, but a few have special return
1992 // types, so allow them to override appropriately below.
1993 QualType ResultType = ValType;
1995 // We need to figure out which concrete builtin this maps onto. For example,
1996 // __sync_fetch_and_add with a 2 byte object turns into
1997 // __sync_fetch_and_add_2.
1998 #define BUILTIN_ROW(x) \
1999 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2000 Builtin::BI##x##_8, Builtin::BI##x##_16 }
2002 static const unsigned BuiltinIndices[][5] = {
2003 BUILTIN_ROW(__sync_fetch_and_add),
2004 BUILTIN_ROW(__sync_fetch_and_sub),
2005 BUILTIN_ROW(__sync_fetch_and_or),
2006 BUILTIN_ROW(__sync_fetch_and_and),
2007 BUILTIN_ROW(__sync_fetch_and_xor),
2008 BUILTIN_ROW(__sync_fetch_and_nand),
2010 BUILTIN_ROW(__sync_add_and_fetch),
2011 BUILTIN_ROW(__sync_sub_and_fetch),
2012 BUILTIN_ROW(__sync_and_and_fetch),
2013 BUILTIN_ROW(__sync_or_and_fetch),
2014 BUILTIN_ROW(__sync_xor_and_fetch),
2015 BUILTIN_ROW(__sync_nand_and_fetch),
2017 BUILTIN_ROW(__sync_val_compare_and_swap),
2018 BUILTIN_ROW(__sync_bool_compare_and_swap),
2019 BUILTIN_ROW(__sync_lock_test_and_set),
2020 BUILTIN_ROW(__sync_lock_release),
2021 BUILTIN_ROW(__sync_swap)
2025 // Determine the index of the size.
2027 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
2028 case 1: SizeIndex = 0; break;
2029 case 2: SizeIndex = 1; break;
2030 case 4: SizeIndex = 2; break;
2031 case 8: SizeIndex = 3; break;
2032 case 16: SizeIndex = 4; break;
2034 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2035 << FirstArg->getType() << FirstArg->getSourceRange();
2039 // Each of these builtins has one pointer argument, followed by some number of
2040 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2041 // that we ignore. Find out which row of BuiltinIndices to read from as well
2042 // as the number of fixed args.
2043 unsigned BuiltinID = FDecl->getBuiltinID();
2044 unsigned BuiltinIndex, NumFixed = 1;
2045 bool WarnAboutSemanticsChange = false;
2046 switch (BuiltinID) {
2047 default: llvm_unreachable("Unknown overloaded atomic builtin!");
2048 case Builtin::BI__sync_fetch_and_add:
2049 case Builtin::BI__sync_fetch_and_add_1:
2050 case Builtin::BI__sync_fetch_and_add_2:
2051 case Builtin::BI__sync_fetch_and_add_4:
2052 case Builtin::BI__sync_fetch_and_add_8:
2053 case Builtin::BI__sync_fetch_and_add_16:
2057 case Builtin::BI__sync_fetch_and_sub:
2058 case Builtin::BI__sync_fetch_and_sub_1:
2059 case Builtin::BI__sync_fetch_and_sub_2:
2060 case Builtin::BI__sync_fetch_and_sub_4:
2061 case Builtin::BI__sync_fetch_and_sub_8:
2062 case Builtin::BI__sync_fetch_and_sub_16:
2066 case Builtin::BI__sync_fetch_and_or:
2067 case Builtin::BI__sync_fetch_and_or_1:
2068 case Builtin::BI__sync_fetch_and_or_2:
2069 case Builtin::BI__sync_fetch_and_or_4:
2070 case Builtin::BI__sync_fetch_and_or_8:
2071 case Builtin::BI__sync_fetch_and_or_16:
2075 case Builtin::BI__sync_fetch_and_and:
2076 case Builtin::BI__sync_fetch_and_and_1:
2077 case Builtin::BI__sync_fetch_and_and_2:
2078 case Builtin::BI__sync_fetch_and_and_4:
2079 case Builtin::BI__sync_fetch_and_and_8:
2080 case Builtin::BI__sync_fetch_and_and_16:
2084 case Builtin::BI__sync_fetch_and_xor:
2085 case Builtin::BI__sync_fetch_and_xor_1:
2086 case Builtin::BI__sync_fetch_and_xor_2:
2087 case Builtin::BI__sync_fetch_and_xor_4:
2088 case Builtin::BI__sync_fetch_and_xor_8:
2089 case Builtin::BI__sync_fetch_and_xor_16:
2093 case Builtin::BI__sync_fetch_and_nand:
2094 case Builtin::BI__sync_fetch_and_nand_1:
2095 case Builtin::BI__sync_fetch_and_nand_2:
2096 case Builtin::BI__sync_fetch_and_nand_4:
2097 case Builtin::BI__sync_fetch_and_nand_8:
2098 case Builtin::BI__sync_fetch_and_nand_16:
2100 WarnAboutSemanticsChange = true;
2103 case Builtin::BI__sync_add_and_fetch:
2104 case Builtin::BI__sync_add_and_fetch_1:
2105 case Builtin::BI__sync_add_and_fetch_2:
2106 case Builtin::BI__sync_add_and_fetch_4:
2107 case Builtin::BI__sync_add_and_fetch_8:
2108 case Builtin::BI__sync_add_and_fetch_16:
2112 case Builtin::BI__sync_sub_and_fetch:
2113 case Builtin::BI__sync_sub_and_fetch_1:
2114 case Builtin::BI__sync_sub_and_fetch_2:
2115 case Builtin::BI__sync_sub_and_fetch_4:
2116 case Builtin::BI__sync_sub_and_fetch_8:
2117 case Builtin::BI__sync_sub_and_fetch_16:
2121 case Builtin::BI__sync_and_and_fetch:
2122 case Builtin::BI__sync_and_and_fetch_1:
2123 case Builtin::BI__sync_and_and_fetch_2:
2124 case Builtin::BI__sync_and_and_fetch_4:
2125 case Builtin::BI__sync_and_and_fetch_8:
2126 case Builtin::BI__sync_and_and_fetch_16:
2130 case Builtin::BI__sync_or_and_fetch:
2131 case Builtin::BI__sync_or_and_fetch_1:
2132 case Builtin::BI__sync_or_and_fetch_2:
2133 case Builtin::BI__sync_or_and_fetch_4:
2134 case Builtin::BI__sync_or_and_fetch_8:
2135 case Builtin::BI__sync_or_and_fetch_16:
2139 case Builtin::BI__sync_xor_and_fetch:
2140 case Builtin::BI__sync_xor_and_fetch_1:
2141 case Builtin::BI__sync_xor_and_fetch_2:
2142 case Builtin::BI__sync_xor_and_fetch_4:
2143 case Builtin::BI__sync_xor_and_fetch_8:
2144 case Builtin::BI__sync_xor_and_fetch_16:
2148 case Builtin::BI__sync_nand_and_fetch:
2149 case Builtin::BI__sync_nand_and_fetch_1:
2150 case Builtin::BI__sync_nand_and_fetch_2:
2151 case Builtin::BI__sync_nand_and_fetch_4:
2152 case Builtin::BI__sync_nand_and_fetch_8:
2153 case Builtin::BI__sync_nand_and_fetch_16:
2155 WarnAboutSemanticsChange = true;
2158 case Builtin::BI__sync_val_compare_and_swap:
2159 case Builtin::BI__sync_val_compare_and_swap_1:
2160 case Builtin::BI__sync_val_compare_and_swap_2:
2161 case Builtin::BI__sync_val_compare_and_swap_4:
2162 case Builtin::BI__sync_val_compare_and_swap_8:
2163 case Builtin::BI__sync_val_compare_and_swap_16:
2168 case Builtin::BI__sync_bool_compare_and_swap:
2169 case Builtin::BI__sync_bool_compare_and_swap_1:
2170 case Builtin::BI__sync_bool_compare_and_swap_2:
2171 case Builtin::BI__sync_bool_compare_and_swap_4:
2172 case Builtin::BI__sync_bool_compare_and_swap_8:
2173 case Builtin::BI__sync_bool_compare_and_swap_16:
2176 ResultType = Context.BoolTy;
2179 case Builtin::BI__sync_lock_test_and_set:
2180 case Builtin::BI__sync_lock_test_and_set_1:
2181 case Builtin::BI__sync_lock_test_and_set_2:
2182 case Builtin::BI__sync_lock_test_and_set_4:
2183 case Builtin::BI__sync_lock_test_and_set_8:
2184 case Builtin::BI__sync_lock_test_and_set_16:
2188 case Builtin::BI__sync_lock_release:
2189 case Builtin::BI__sync_lock_release_1:
2190 case Builtin::BI__sync_lock_release_2:
2191 case Builtin::BI__sync_lock_release_4:
2192 case Builtin::BI__sync_lock_release_8:
2193 case Builtin::BI__sync_lock_release_16:
2196 ResultType = Context.VoidTy;
2199 case Builtin::BI__sync_swap:
2200 case Builtin::BI__sync_swap_1:
2201 case Builtin::BI__sync_swap_2:
2202 case Builtin::BI__sync_swap_4:
2203 case Builtin::BI__sync_swap_8:
2204 case Builtin::BI__sync_swap_16:
2209 // Now that we know how many fixed arguments we expect, first check that we
2210 // have at least that many.
2211 if (TheCall->getNumArgs() < 1+NumFixed) {
2212 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2213 << 0 << 1+NumFixed << TheCall->getNumArgs()
2214 << TheCall->getCallee()->getSourceRange();
2218 if (WarnAboutSemanticsChange) {
2219 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2220 << TheCall->getCallee()->getSourceRange();
2223 // Get the decl for the concrete builtin from this, we can tell what the
2224 // concrete integer type we should convert to is.
2225 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
2226 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
2227 FunctionDecl *NewBuiltinDecl;
2228 if (NewBuiltinID == BuiltinID)
2229 NewBuiltinDecl = FDecl;
2231 // Perform builtin lookup to avoid redeclaring it.
2232 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2233 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2234 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2235 assert(Res.getFoundDecl());
2236 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
2237 if (!NewBuiltinDecl)
2241 // The first argument --- the pointer --- has a fixed type; we
2242 // deduce the types of the rest of the arguments accordingly. Walk
2243 // the remaining arguments, converting them to the deduced value type.
2244 for (unsigned i = 0; i != NumFixed; ++i) {
2245 ExprResult Arg = TheCall->getArg(i+1);
2247 // GCC does an implicit conversion to the pointer or integer ValType. This
2248 // can fail in some cases (1i -> int**), check for this error case now.
2249 // Initialize the argument.
2250 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2251 ValType, /*consume*/ false);
2252 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2253 if (Arg.isInvalid())
2256 // Okay, we have something that *can* be converted to the right type. Check
2257 // to see if there is a potentially weird extension going on here. This can
2258 // happen when you do an atomic operation on something like an char* and
2259 // pass in 42. The 42 gets converted to char. This is even more strange
2260 // for things like 45.123 -> char, etc.
2261 // FIXME: Do this check.
2262 TheCall->setArg(i+1, Arg.get());
2265 ASTContext& Context = this->getASTContext();
2267 // Create a new DeclRefExpr to refer to the new decl.
2268 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2270 DRE->getQualifierLoc(),
2273 /*enclosing*/ false,
2275 Context.BuiltinFnTy,
2276 DRE->getValueKind());
2278 // Set the callee in the CallExpr.
2279 // FIXME: This loses syntactic information.
2280 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2281 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2282 CK_BuiltinFnToFnPtr);
2283 TheCall->setCallee(PromotedCall.get());
2285 // Change the result type of the call to match the original value type. This
2286 // is arbitrary, but the codegen for these builtins ins design to handle it
2288 TheCall->setType(ResultType);
2290 return TheCallResult;
2293 /// SemaBuiltinNontemporalOverloaded - We have a call to
2294 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2295 /// overloaded function based on the pointer type of its last argument.
2297 /// This function goes through and does final semantic checking for these
2299 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2300 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2302 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2303 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2304 unsigned BuiltinID = FDecl->getBuiltinID();
2305 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2306 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2307 "Unexpected nontemporal load/store builtin!");
2308 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2309 unsigned numArgs = isStore ? 2 : 1;
2311 // Ensure that we have the proper number of arguments.
2312 if (checkArgCount(*this, TheCall, numArgs))
2315 // Inspect the last argument of the nontemporal builtin. This should always
2316 // be a pointer type, from which we imply the type of the memory access.
2317 // Because it is a pointer type, we don't have to worry about any implicit
2319 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2320 ExprResult PointerArgResult =
2321 DefaultFunctionArrayLvalueConversion(PointerArg);
2323 if (PointerArgResult.isInvalid())
2325 PointerArg = PointerArgResult.get();
2326 TheCall->setArg(numArgs - 1, PointerArg);
2328 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2330 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2331 << PointerArg->getType() << PointerArg->getSourceRange();
2335 QualType ValType = pointerType->getPointeeType();
2337 // Strip any qualifiers off ValType.
2338 ValType = ValType.getUnqualifiedType();
2339 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2340 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2341 !ValType->isVectorType()) {
2342 Diag(DRE->getLocStart(),
2343 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2344 << PointerArg->getType() << PointerArg->getSourceRange();
2349 TheCall->setType(ValType);
2350 return TheCallResult;
2353 ExprResult ValArg = TheCall->getArg(0);
2354 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2355 Context, ValType, /*consume*/ false);
2356 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2357 if (ValArg.isInvalid())
2360 TheCall->setArg(0, ValArg.get());
2361 TheCall->setType(Context.VoidTy);
2362 return TheCallResult;
2365 /// CheckObjCString - Checks that the argument to the builtin
2366 /// CFString constructor is correct
2367 /// Note: It might also make sense to do the UTF-16 conversion here (would
2368 /// simplify the backend).
2369 bool Sema::CheckObjCString(Expr *Arg) {
2370 Arg = Arg->IgnoreParenCasts();
2371 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2373 if (!Literal || !Literal->isAscii()) {
2374 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2375 << Arg->getSourceRange();
2379 if (Literal->containsNonAsciiOrNull()) {
2380 StringRef String = Literal->getString();
2381 unsigned NumBytes = String.size();
2382 SmallVector<UTF16, 128> ToBuf(NumBytes);
2383 const UTF8 *FromPtr = (const UTF8 *)String.data();
2384 UTF16 *ToPtr = &ToBuf[0];
2386 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2387 &ToPtr, ToPtr + NumBytes,
2389 // Check for conversion failure.
2390 if (Result != conversionOK)
2391 Diag(Arg->getLocStart(),
2392 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2397 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2398 /// for validity. Emit an error and return true on failure; return false
2400 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
2401 Expr *Fn = TheCall->getCallee();
2402 if (TheCall->getNumArgs() > 2) {
2403 Diag(TheCall->getArg(2)->getLocStart(),
2404 diag::err_typecheck_call_too_many_args)
2405 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2406 << Fn->getSourceRange()
2407 << SourceRange(TheCall->getArg(2)->getLocStart(),
2408 (*(TheCall->arg_end()-1))->getLocEnd());
2412 if (TheCall->getNumArgs() < 2) {
2413 return Diag(TheCall->getLocEnd(),
2414 diag::err_typecheck_call_too_few_args_at_least)
2415 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
2418 // Type-check the first argument normally.
2419 if (checkBuiltinArgument(*this, TheCall, 0))
2422 // Determine whether the current function is variadic or not.
2423 BlockScopeInfo *CurBlock = getCurBlock();
2426 isVariadic = CurBlock->TheDecl->isVariadic();
2427 else if (FunctionDecl *FD = getCurFunctionDecl())
2428 isVariadic = FD->isVariadic();
2430 isVariadic = getCurMethodDecl()->isVariadic();
2433 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2437 // Verify that the second argument to the builtin is the last argument of the
2438 // current function or method.
2439 bool SecondArgIsLastNamedArgument = false;
2440 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
2442 // These are valid if SecondArgIsLastNamedArgument is false after the next
2445 SourceLocation ParamLoc;
2447 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2448 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
2449 // FIXME: This isn't correct for methods (results in bogus warning).
2450 // Get the last formal in the current function.
2451 const ParmVarDecl *LastArg;
2453 LastArg = *(CurBlock->TheDecl->param_end()-1);
2454 else if (FunctionDecl *FD = getCurFunctionDecl())
2455 LastArg = *(FD->param_end()-1);
2457 LastArg = *(getCurMethodDecl()->param_end()-1);
2458 SecondArgIsLastNamedArgument = PV == LastArg;
2460 Type = PV->getType();
2461 ParamLoc = PV->getLocation();
2465 if (!SecondArgIsLastNamedArgument)
2466 Diag(TheCall->getArg(1)->getLocStart(),
2467 diag::warn_second_parameter_of_va_start_not_last_named_argument);
2468 else if (Type->isReferenceType()) {
2469 Diag(Arg->getLocStart(),
2470 diag::warn_va_start_of_reference_type_is_undefined);
2471 Diag(ParamLoc, diag::note_parameter_type) << Type;
2474 TheCall->setType(Context.VoidTy);
2478 /// Check the arguments to '__builtin_va_start' for validity, and that
2479 /// it was called from a function of the native ABI.
2480 /// Emit an error and return true on failure; return false on success.
2481 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2482 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2483 // On x64 Windows, don't allow this in System V ABI functions.
2484 // (Yes, that means there's no corresponding way to support variadic
2485 // System V ABI functions on Windows.)
2486 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2487 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2488 clang::CallingConv CC = CC_C;
2489 if (const FunctionDecl *FD = getCurFunctionDecl())
2490 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2491 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2492 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2493 return Diag(TheCall->getCallee()->getLocStart(),
2494 diag::err_va_start_used_in_wrong_abi_function)
2495 << (OS != llvm::Triple::Win32);
2497 return SemaBuiltinVAStartImpl(TheCall);
2500 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
2501 /// it was called from a Win64 ABI function.
2502 /// Emit an error and return true on failure; return false on success.
2503 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2504 // This only makes sense for x86-64.
2505 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2506 Expr *Callee = TheCall->getCallee();
2507 if (TT.getArch() != llvm::Triple::x86_64)
2508 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2509 // Don't allow this in System V ABI functions.
2510 clang::CallingConv CC = CC_C;
2511 if (const FunctionDecl *FD = getCurFunctionDecl())
2512 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2513 if (CC == CC_X86_64SysV ||
2514 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2515 return Diag(Callee->getLocStart(),
2516 diag::err_ms_va_start_used_in_sysv_function);
2517 return SemaBuiltinVAStartImpl(TheCall);
2520 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2521 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2522 // const char *named_addr);
2524 Expr *Func = Call->getCallee();
2526 if (Call->getNumArgs() < 3)
2527 return Diag(Call->getLocEnd(),
2528 diag::err_typecheck_call_too_few_args_at_least)
2529 << 0 /*function call*/ << 3 << Call->getNumArgs();
2531 // Determine whether the current function is variadic or not.
2533 if (BlockScopeInfo *CurBlock = getCurBlock())
2534 IsVariadic = CurBlock->TheDecl->isVariadic();
2535 else if (FunctionDecl *FD = getCurFunctionDecl())
2536 IsVariadic = FD->isVariadic();
2537 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2538 IsVariadic = MD->isVariadic();
2540 llvm_unreachable("unexpected statement type");
2543 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2547 // Type-check the first argument normally.
2548 if (checkBuiltinArgument(*this, Call, 0))
2554 } ArgumentTypes[] = {
2555 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2556 { 2, Context.getSizeType() },
2559 for (const auto &AT : ArgumentTypes) {
2560 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2561 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2563 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2564 << Arg->getType() << AT.Type << 1 /* different class */
2565 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2566 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2572 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2573 /// friends. This is declared to take (...), so we have to check everything.
2574 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2575 if (TheCall->getNumArgs() < 2)
2576 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2577 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
2578 if (TheCall->getNumArgs() > 2)
2579 return Diag(TheCall->getArg(2)->getLocStart(),
2580 diag::err_typecheck_call_too_many_args)
2581 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2582 << SourceRange(TheCall->getArg(2)->getLocStart(),
2583 (*(TheCall->arg_end()-1))->getLocEnd());
2585 ExprResult OrigArg0 = TheCall->getArg(0);
2586 ExprResult OrigArg1 = TheCall->getArg(1);
2588 // Do standard promotions between the two arguments, returning their common
2590 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
2591 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2594 // Make sure any conversions are pushed back into the call; this is
2595 // type safe since unordered compare builtins are declared as "_Bool
2597 TheCall->setArg(0, OrigArg0.get());
2598 TheCall->setArg(1, OrigArg1.get());
2600 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
2603 // If the common type isn't a real floating type, then the arguments were
2604 // invalid for this operation.
2605 if (Res.isNull() || !Res->isRealFloatingType())
2606 return Diag(OrigArg0.get()->getLocStart(),
2607 diag::err_typecheck_call_invalid_ordered_compare)
2608 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2609 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
2614 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2615 /// __builtin_isnan and friends. This is declared to take (...), so we have
2616 /// to check everything. We expect the last argument to be a floating point
2618 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2619 if (TheCall->getNumArgs() < NumArgs)
2620 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2621 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
2622 if (TheCall->getNumArgs() > NumArgs)
2623 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
2624 diag::err_typecheck_call_too_many_args)
2625 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
2626 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
2627 (*(TheCall->arg_end()-1))->getLocEnd());
2629 Expr *OrigArg = TheCall->getArg(NumArgs-1);
2631 if (OrigArg->isTypeDependent())
2634 // This operation requires a non-_Complex floating-point number.
2635 if (!OrigArg->getType()->isRealFloatingType())
2636 return Diag(OrigArg->getLocStart(),
2637 diag::err_typecheck_call_invalid_unary_fp)
2638 << OrigArg->getType() << OrigArg->getSourceRange();
2640 // If this is an implicit conversion from float -> double, remove it.
2641 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2642 Expr *CastArg = Cast->getSubExpr();
2643 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2644 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2645 "promotion from float to double is the only expected cast here");
2646 Cast->setSubExpr(nullptr);
2647 TheCall->setArg(NumArgs-1, CastArg);
2654 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2655 // This is declared to take (...), so we have to check everything.
2656 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
2657 if (TheCall->getNumArgs() < 2)
2658 return ExprError(Diag(TheCall->getLocEnd(),
2659 diag::err_typecheck_call_too_few_args_at_least)
2660 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2661 << TheCall->getSourceRange());
2663 // Determine which of the following types of shufflevector we're checking:
2664 // 1) unary, vector mask: (lhs, mask)
2665 // 2) binary, vector mask: (lhs, rhs, mask)
2666 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2667 QualType resType = TheCall->getArg(0)->getType();
2668 unsigned numElements = 0;
2670 if (!TheCall->getArg(0)->isTypeDependent() &&
2671 !TheCall->getArg(1)->isTypeDependent()) {
2672 QualType LHSType = TheCall->getArg(0)->getType();
2673 QualType RHSType = TheCall->getArg(1)->getType();
2675 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2676 return ExprError(Diag(TheCall->getLocStart(),
2677 diag::err_shufflevector_non_vector)
2678 << SourceRange(TheCall->getArg(0)->getLocStart(),
2679 TheCall->getArg(1)->getLocEnd()));
2681 numElements = LHSType->getAs<VectorType>()->getNumElements();
2682 unsigned numResElements = TheCall->getNumArgs() - 2;
2684 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2685 // with mask. If so, verify that RHS is an integer vector type with the
2686 // same number of elts as lhs.
2687 if (TheCall->getNumArgs() == 2) {
2688 if (!RHSType->hasIntegerRepresentation() ||
2689 RHSType->getAs<VectorType>()->getNumElements() != numElements)
2690 return ExprError(Diag(TheCall->getLocStart(),
2691 diag::err_shufflevector_incompatible_vector)
2692 << SourceRange(TheCall->getArg(1)->getLocStart(),
2693 TheCall->getArg(1)->getLocEnd()));
2694 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
2695 return ExprError(Diag(TheCall->getLocStart(),
2696 diag::err_shufflevector_incompatible_vector)
2697 << SourceRange(TheCall->getArg(0)->getLocStart(),
2698 TheCall->getArg(1)->getLocEnd()));
2699 } else if (numElements != numResElements) {
2700 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
2701 resType = Context.getVectorType(eltType, numResElements,
2702 VectorType::GenericVector);
2706 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
2707 if (TheCall->getArg(i)->isTypeDependent() ||
2708 TheCall->getArg(i)->isValueDependent())
2711 llvm::APSInt Result(32);
2712 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2713 return ExprError(Diag(TheCall->getLocStart(),
2714 diag::err_shufflevector_nonconstant_argument)
2715 << TheCall->getArg(i)->getSourceRange());
2717 // Allow -1 which will be translated to undef in the IR.
2718 if (Result.isSigned() && Result.isAllOnesValue())
2721 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
2722 return ExprError(Diag(TheCall->getLocStart(),
2723 diag::err_shufflevector_argument_too_large)
2724 << TheCall->getArg(i)->getSourceRange());
2727 SmallVector<Expr*, 32> exprs;
2729 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
2730 exprs.push_back(TheCall->getArg(i));
2731 TheCall->setArg(i, nullptr);
2734 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2735 TheCall->getCallee()->getLocStart(),
2736 TheCall->getRParenLoc());
2739 /// SemaConvertVectorExpr - Handle __builtin_convertvector
2740 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2741 SourceLocation BuiltinLoc,
2742 SourceLocation RParenLoc) {
2743 ExprValueKind VK = VK_RValue;
2744 ExprObjectKind OK = OK_Ordinary;
2745 QualType DstTy = TInfo->getType();
2746 QualType SrcTy = E->getType();
2748 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2749 return ExprError(Diag(BuiltinLoc,
2750 diag::err_convertvector_non_vector)
2751 << E->getSourceRange());
2752 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2753 return ExprError(Diag(BuiltinLoc,
2754 diag::err_convertvector_non_vector_type));
2756 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2757 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2758 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2759 if (SrcElts != DstElts)
2760 return ExprError(Diag(BuiltinLoc,
2761 diag::err_convertvector_incompatible_vector)
2762 << E->getSourceRange());
2765 return new (Context)
2766 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
2769 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2770 // This is declared to take (const void*, ...) and can take two
2771 // optional constant int args.
2772 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
2773 unsigned NumArgs = TheCall->getNumArgs();
2776 return Diag(TheCall->getLocEnd(),
2777 diag::err_typecheck_call_too_many_args_at_most)
2778 << 0 /*function call*/ << 3 << NumArgs
2779 << TheCall->getSourceRange();
2781 // Argument 0 is checked for us and the remaining arguments must be
2782 // constant integers.
2783 for (unsigned i = 1; i != NumArgs; ++i)
2784 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
2790 /// SemaBuiltinAssume - Handle __assume (MS Extension).
2791 // __assume does not evaluate its arguments, and should warn if its argument
2792 // has side effects.
2793 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2794 Expr *Arg = TheCall->getArg(0);
2795 if (Arg->isInstantiationDependent()) return false;
2797 if (Arg->HasSideEffects(Context))
2798 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
2799 << Arg->getSourceRange()
2800 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2805 /// Handle __builtin_assume_aligned. This is declared
2806 /// as (const void*, size_t, ...) and can take one optional constant int arg.
2807 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2808 unsigned NumArgs = TheCall->getNumArgs();
2811 return Diag(TheCall->getLocEnd(),
2812 diag::err_typecheck_call_too_many_args_at_most)
2813 << 0 /*function call*/ << 3 << NumArgs
2814 << TheCall->getSourceRange();
2816 // The alignment must be a constant integer.
2817 Expr *Arg = TheCall->getArg(1);
2819 // We can't check the value of a dependent argument.
2820 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2821 llvm::APSInt Result;
2822 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2825 if (!Result.isPowerOf2())
2826 return Diag(TheCall->getLocStart(),
2827 diag::err_alignment_not_power_of_two)
2828 << Arg->getSourceRange();
2832 ExprResult Arg(TheCall->getArg(2));
2833 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2834 Context.getSizeType(), false);
2835 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2836 if (Arg.isInvalid()) return true;
2837 TheCall->setArg(2, Arg.get());
2843 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2844 /// TheCall is a constant expression.
2845 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2846 llvm::APSInt &Result) {
2847 Expr *Arg = TheCall->getArg(ArgNum);
2848 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2849 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2851 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2853 if (!Arg->isIntegerConstantExpr(Result, Context))
2854 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
2855 << FDecl->getDeclName() << Arg->getSourceRange();
2860 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2861 /// TheCall is a constant expression in the range [Low, High].
2862 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2863 int Low, int High) {
2864 llvm::APSInt Result;
2866 // We can't check the value of a dependent argument.
2867 Expr *Arg = TheCall->getArg(ArgNum);
2868 if (Arg->isTypeDependent() || Arg->isValueDependent())
2871 // Check constant-ness first.
2872 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2875 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
2876 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2877 << Low << High << Arg->getSourceRange();
2882 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
2883 /// TheCall is an ARM/AArch64 special register string literal.
2884 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
2885 int ArgNum, unsigned ExpectedFieldNum,
2887 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2888 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
2889 BuiltinID == ARM::BI__builtin_arm_rsr ||
2890 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2891 BuiltinID == ARM::BI__builtin_arm_wsr ||
2892 BuiltinID == ARM::BI__builtin_arm_wsrp;
2893 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2894 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
2895 BuiltinID == AArch64::BI__builtin_arm_rsr ||
2896 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2897 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2898 BuiltinID == AArch64::BI__builtin_arm_wsrp;
2899 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
2901 // We can't check the value of a dependent argument.
2902 Expr *Arg = TheCall->getArg(ArgNum);
2903 if (Arg->isTypeDependent() || Arg->isValueDependent())
2906 // Check if the argument is a string literal.
2907 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2908 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2909 << Arg->getSourceRange();
2911 // Check the type of special register given.
2912 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2913 SmallVector<StringRef, 6> Fields;
2914 Reg.split(Fields, ":");
2916 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
2917 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2918 << Arg->getSourceRange();
2920 // If the string is the name of a register then we cannot check that it is
2921 // valid here but if the string is of one the forms described in ACLE then we
2922 // can check that the supplied fields are integers and within the valid
2924 if (Fields.size() > 1) {
2925 bool FiveFields = Fields.size() == 5;
2927 bool ValidString = true;
2929 ValidString &= Fields[0].startswith_lower("cp") ||
2930 Fields[0].startswith_lower("p");
2933 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
2935 ValidString &= Fields[2].startswith_lower("c");
2937 Fields[2] = Fields[2].drop_front(1);
2940 ValidString &= Fields[3].startswith_lower("c");
2942 Fields[3] = Fields[3].drop_front(1);
2946 SmallVector<int, 5> Ranges;
2948 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
2950 Ranges.append({15, 7, 15});
2952 for (unsigned i=0; i<Fields.size(); ++i) {
2954 ValidString &= !Fields[i].getAsInteger(10, IntField);
2955 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
2959 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2960 << Arg->getSourceRange();
2962 } else if (IsAArch64Builtin && Fields.size() == 1) {
2963 // If the register name is one of those that appear in the condition below
2964 // and the special register builtin being used is one of the write builtins,
2965 // then we require that the argument provided for writing to the register
2966 // is an integer constant expression. This is because it will be lowered to
2967 // an MSR (immediate) instruction, so we need to know the immediate at
2969 if (TheCall->getNumArgs() != 2)
2972 std::string RegLower = Reg.lower();
2973 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
2974 RegLower != "pan" && RegLower != "uao")
2977 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2983 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
2984 /// This checks that the target supports __builtin_longjmp and
2985 /// that val is a constant 1.
2986 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2987 if (!Context.getTargetInfo().hasSjLjLowering())
2988 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2989 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2991 Expr *Arg = TheCall->getArg(1);
2992 llvm::APSInt Result;
2994 // TODO: This is less than ideal. Overload this to take a value.
2995 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2999 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3000 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3006 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3007 /// This checks that the target supports __builtin_setjmp.
3008 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3009 if (!Context.getTargetInfo().hasSjLjLowering())
3010 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3011 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3016 enum StringLiteralCheckType {
3018 SLCT_UncheckedLiteral,
3023 // Determine if an expression is a string literal or constant string.
3024 // If this function returns false on the arguments to a function expecting a
3025 // format string, we will usually need to emit a warning.
3026 // True string literals are then checked by CheckFormatString.
3027 static StringLiteralCheckType
3028 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3029 bool HasVAListArg, unsigned format_idx,
3030 unsigned firstDataArg, Sema::FormatStringType Type,
3031 Sema::VariadicCallType CallType, bool InFunctionCall,
3032 llvm::SmallBitVector &CheckedVarArgs) {
3034 if (E->isTypeDependent() || E->isValueDependent())
3035 return SLCT_NotALiteral;
3037 E = E->IgnoreParenCasts();
3039 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
3040 // Technically -Wformat-nonliteral does not warn about this case.
3041 // The behavior of printf and friends in this case is implementation
3042 // dependent. Ideally if the format string cannot be null then
3043 // it should have a 'nonnull' attribute in the function prototype.
3044 return SLCT_UncheckedLiteral;
3046 switch (E->getStmtClass()) {
3047 case Stmt::BinaryConditionalOperatorClass:
3048 case Stmt::ConditionalOperatorClass: {
3049 // The expression is a literal if both sub-expressions were, and it was
3050 // completely checked only if both sub-expressions were checked.
3051 const AbstractConditionalOperator *C =
3052 cast<AbstractConditionalOperator>(E);
3053 StringLiteralCheckType Left =
3054 checkFormatStringExpr(S, C->getTrueExpr(), Args,
3055 HasVAListArg, format_idx, firstDataArg,
3056 Type, CallType, InFunctionCall, CheckedVarArgs);
3057 if (Left == SLCT_NotALiteral)
3058 return SLCT_NotALiteral;
3059 StringLiteralCheckType Right =
3060 checkFormatStringExpr(S, C->getFalseExpr(), Args,
3061 HasVAListArg, format_idx, firstDataArg,
3062 Type, CallType, InFunctionCall, CheckedVarArgs);
3063 return Left < Right ? Left : Right;
3066 case Stmt::ImplicitCastExprClass: {
3067 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3071 case Stmt::OpaqueValueExprClass:
3072 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3076 return SLCT_NotALiteral;
3078 case Stmt::PredefinedExprClass:
3079 // While __func__, etc., are technically not string literals, they
3080 // cannot contain format specifiers and thus are not a security
3082 return SLCT_UncheckedLiteral;
3084 case Stmt::DeclRefExprClass: {
3085 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
3087 // As an exception, do not flag errors for variables binding to
3088 // const string literals.
3089 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3090 bool isConstant = false;
3091 QualType T = DR->getType();
3093 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3094 isConstant = AT->getElementType().isConstant(S.Context);
3095 } else if (const PointerType *PT = T->getAs<PointerType>()) {
3096 isConstant = T.isConstant(S.Context) &&
3097 PT->getPointeeType().isConstant(S.Context);
3098 } else if (T->isObjCObjectPointerType()) {
3099 // In ObjC, there is usually no "const ObjectPointer" type,
3100 // so don't check if the pointee type is constant.
3101 isConstant = T.isConstant(S.Context);
3105 if (const Expr *Init = VD->getAnyInitializer()) {
3106 // Look through initializers like const char c[] = { "foo" }
3107 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3108 if (InitList->isStringLiteralInit())
3109 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3111 return checkFormatStringExpr(S, Init, Args,
3112 HasVAListArg, format_idx,
3113 firstDataArg, Type, CallType,
3114 /*InFunctionCall*/false, CheckedVarArgs);
3118 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3119 // special check to see if the format string is a function parameter
3120 // of the function calling the printf function. If the function
3121 // has an attribute indicating it is a printf-like function, then we
3122 // should suppress warnings concerning non-literals being used in a call
3123 // to a vprintf function. For example:
3126 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3128 // va_start(ap, fmt);
3129 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3133 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3134 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3135 int PVIndex = PV->getFunctionScopeIndex() + 1;
3136 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
3137 // adjust for implicit parameter
3138 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3139 if (MD->isInstance())
3141 // We also check if the formats are compatible.
3142 // We can't pass a 'scanf' string to a 'printf' function.
3143 if (PVIndex == PVFormat->getFormatIdx() &&
3144 Type == S.GetFormatStringType(PVFormat))
3145 return SLCT_UncheckedLiteral;
3152 return SLCT_NotALiteral;
3155 case Stmt::CallExprClass:
3156 case Stmt::CXXMemberCallExprClass: {
3157 const CallExpr *CE = cast<CallExpr>(E);
3158 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3159 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3160 unsigned ArgIndex = FA->getFormatIdx();
3161 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3162 if (MD->isInstance())
3164 const Expr *Arg = CE->getArg(ArgIndex - 1);
3166 return checkFormatStringExpr(S, Arg, Args,
3167 HasVAListArg, format_idx, firstDataArg,
3168 Type, CallType, InFunctionCall,
3170 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3171 unsigned BuiltinID = FD->getBuiltinID();
3172 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3173 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3174 const Expr *Arg = CE->getArg(0);
3175 return checkFormatStringExpr(S, Arg, Args,
3176 HasVAListArg, format_idx,
3177 firstDataArg, Type, CallType,
3178 InFunctionCall, CheckedVarArgs);
3183 return SLCT_NotALiteral;
3185 case Stmt::ObjCStringLiteralClass:
3186 case Stmt::StringLiteralClass: {
3187 const StringLiteral *StrE = nullptr;
3189 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
3190 StrE = ObjCFExpr->getString();
3192 StrE = cast<StringLiteral>(E);
3195 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
3196 Type, InFunctionCall, CallType, CheckedVarArgs);
3197 return SLCT_CheckedLiteral;
3200 return SLCT_NotALiteral;
3204 return SLCT_NotALiteral;
3208 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
3209 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
3210 .Case("scanf", FST_Scanf)
3211 .Cases("printf", "printf0", FST_Printf)
3212 .Cases("NSString", "CFString", FST_NSString)
3213 .Case("strftime", FST_Strftime)
3214 .Case("strfmon", FST_Strfmon)
3215 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
3216 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
3217 .Case("os_trace", FST_OSTrace)
3218 .Default(FST_Unknown);
3221 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3222 /// functions) for correct use of format strings.
3223 /// Returns true if a format string has been fully checked.
3224 bool Sema::CheckFormatArguments(const FormatAttr *Format,
3225 ArrayRef<const Expr *> Args,
3227 VariadicCallType CallType,
3228 SourceLocation Loc, SourceRange Range,
3229 llvm::SmallBitVector &CheckedVarArgs) {
3230 FormatStringInfo FSI;
3231 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
3232 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
3233 FSI.FirstDataArg, GetFormatStringType(Format),
3234 CallType, Loc, Range, CheckedVarArgs);
3238 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
3239 bool HasVAListArg, unsigned format_idx,
3240 unsigned firstDataArg, FormatStringType Type,
3241 VariadicCallType CallType,
3242 SourceLocation Loc, SourceRange Range,
3243 llvm::SmallBitVector &CheckedVarArgs) {
3244 // CHECK: printf/scanf-like function is called with no format string.
3245 if (format_idx >= Args.size()) {
3246 Diag(Loc, diag::warn_missing_format_string) << Range;
3250 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
3252 // CHECK: format string is not a string literal.
3254 // Dynamically generated format strings are difficult to
3255 // automatically vet at compile time. Requiring that format strings
3256 // are string literals: (1) permits the checking of format strings by
3257 // the compiler and thereby (2) can practically remove the source of
3258 // many format string exploits.
3260 // Format string can be either ObjC string (e.g. @"%d") or
3261 // C string (e.g. "%d")
3262 // ObjC string uses the same format specifiers as C string, so we can use
3263 // the same format string checking logic for both ObjC and C strings.
3264 StringLiteralCheckType CT =
3265 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3266 format_idx, firstDataArg, Type, CallType,
3267 /*IsFunctionCall*/true, CheckedVarArgs);
3268 if (CT != SLCT_NotALiteral)
3269 // Literal format string found, check done!
3270 return CT == SLCT_CheckedLiteral;
3272 // Strftime is particular as it always uses a single 'time' argument,
3273 // so it is safe to pass a non-literal string.
3274 if (Type == FST_Strftime)
3277 // Do not emit diag when the string param is a macro expansion and the
3278 // format is either NSString or CFString. This is a hack to prevent
3279 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3280 // which are usually used in place of NS and CF string literals.
3281 if (Type == FST_NSString &&
3282 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
3285 // If there are no arguments specified, warn with -Wformat-security, otherwise
3286 // warn only with -Wformat-nonliteral.
3287 if (Args.size() == firstDataArg)
3288 Diag(Args[format_idx]->getLocStart(),
3289 diag::warn_format_nonliteral_noargs)
3290 << OrigFormatExpr->getSourceRange();
3292 Diag(Args[format_idx]->getLocStart(),
3293 diag::warn_format_nonliteral)
3294 << OrigFormatExpr->getSourceRange();
3299 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3302 const StringLiteral *FExpr;
3303 const Expr *OrigFormatExpr;
3304 const unsigned FirstDataArg;
3305 const unsigned NumDataArgs;
3306 const char *Beg; // Start of format string.
3307 const bool HasVAListArg;
3308 ArrayRef<const Expr *> Args;
3310 llvm::SmallBitVector CoveredArgs;
3311 bool usesPositionalArgs;
3313 bool inFunctionCall;
3314 Sema::VariadicCallType CallType;
3315 llvm::SmallBitVector &CheckedVarArgs;
3317 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
3318 const Expr *origFormatExpr, unsigned firstDataArg,
3319 unsigned numDataArgs, const char *beg, bool hasVAListArg,
3320 ArrayRef<const Expr *> Args,
3321 unsigned formatIdx, bool inFunctionCall,
3322 Sema::VariadicCallType callType,
3323 llvm::SmallBitVector &CheckedVarArgs)
3324 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
3325 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3326 Beg(beg), HasVAListArg(hasVAListArg),
3327 Args(Args), FormatIdx(formatIdx),
3328 usesPositionalArgs(false), atFirstArg(true),
3329 inFunctionCall(inFunctionCall), CallType(callType),
3330 CheckedVarArgs(CheckedVarArgs) {
3331 CoveredArgs.resize(numDataArgs);
3332 CoveredArgs.reset();
3335 void DoneProcessing();
3337 void HandleIncompleteSpecifier(const char *startSpecifier,
3338 unsigned specifierLen) override;
3340 void HandleInvalidLengthModifier(
3341 const analyze_format_string::FormatSpecifier &FS,
3342 const analyze_format_string::ConversionSpecifier &CS,
3343 const char *startSpecifier, unsigned specifierLen,
3346 void HandleNonStandardLengthModifier(
3347 const analyze_format_string::FormatSpecifier &FS,
3348 const char *startSpecifier, unsigned specifierLen);
3350 void HandleNonStandardConversionSpecifier(
3351 const analyze_format_string::ConversionSpecifier &CS,
3352 const char *startSpecifier, unsigned specifierLen);
3354 void HandlePosition(const char *startPos, unsigned posLen) override;
3356 void HandleInvalidPosition(const char *startSpecifier,
3357 unsigned specifierLen,
3358 analyze_format_string::PositionContext p) override;
3360 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
3362 void HandleNullChar(const char *nullCharacter) override;
3364 template <typename Range>
3365 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3366 const Expr *ArgumentExpr,
3367 PartialDiagnostic PDiag,
3368 SourceLocation StringLoc,
3369 bool IsStringLocation, Range StringRange,
3370 ArrayRef<FixItHint> Fixit = None);
3373 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3374 const char *startSpec,
3375 unsigned specifierLen,
3376 const char *csStart, unsigned csLen);
3378 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3379 const char *startSpec,
3380 unsigned specifierLen);
3382 SourceRange getFormatStringRange();
3383 CharSourceRange getSpecifierRange(const char *startSpecifier,
3384 unsigned specifierLen);
3385 SourceLocation getLocationOfByte(const char *x);
3387 const Expr *getDataArg(unsigned i) const;
3389 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3390 const analyze_format_string::ConversionSpecifier &CS,
3391 const char *startSpecifier, unsigned specifierLen,
3394 template <typename Range>
3395 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3396 bool IsStringLocation, Range StringRange,
3397 ArrayRef<FixItHint> Fixit = None);
3401 SourceRange CheckFormatHandler::getFormatStringRange() {
3402 return OrigFormatExpr->getSourceRange();
3405 CharSourceRange CheckFormatHandler::
3406 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
3407 SourceLocation Start = getLocationOfByte(startSpecifier);
3408 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3410 // Advance the end SourceLocation by one due to half-open ranges.
3411 End = End.getLocWithOffset(1);
3413 return CharSourceRange::getCharRange(Start, End);
3416 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
3417 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
3420 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3421 unsigned specifierLen){
3422 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3423 getLocationOfByte(startSpecifier),
3424 /*IsStringLocation*/true,
3425 getSpecifierRange(startSpecifier, specifierLen));
3428 void CheckFormatHandler::HandleInvalidLengthModifier(
3429 const analyze_format_string::FormatSpecifier &FS,
3430 const analyze_format_string::ConversionSpecifier &CS,
3431 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
3432 using namespace analyze_format_string;
3434 const LengthModifier &LM = FS.getLengthModifier();
3435 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3437 // See if we know how to fix this length modifier.
3438 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
3440 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
3441 getLocationOfByte(LM.getStart()),
3442 /*IsStringLocation*/true,
3443 getSpecifierRange(startSpecifier, specifierLen));
3445 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3446 << FixedLM->toString()
3447 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3451 if (DiagID == diag::warn_format_nonsensical_length)
3452 Hint = FixItHint::CreateRemoval(LMRange);
3454 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
3455 getLocationOfByte(LM.getStart()),
3456 /*IsStringLocation*/true,
3457 getSpecifierRange(startSpecifier, specifierLen),
3462 void CheckFormatHandler::HandleNonStandardLengthModifier(
3463 const analyze_format_string::FormatSpecifier &FS,
3464 const char *startSpecifier, unsigned specifierLen) {
3465 using namespace analyze_format_string;
3467 const LengthModifier &LM = FS.getLengthModifier();
3468 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3470 // See if we know how to fix this length modifier.
3471 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
3473 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3474 << LM.toString() << 0,
3475 getLocationOfByte(LM.getStart()),
3476 /*IsStringLocation*/true,
3477 getSpecifierRange(startSpecifier, specifierLen));
3479 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3480 << FixedLM->toString()
3481 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3484 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3485 << LM.toString() << 0,
3486 getLocationOfByte(LM.getStart()),
3487 /*IsStringLocation*/true,
3488 getSpecifierRange(startSpecifier, specifierLen));
3492 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3493 const analyze_format_string::ConversionSpecifier &CS,
3494 const char *startSpecifier, unsigned specifierLen) {
3495 using namespace analyze_format_string;
3497 // See if we know how to fix this conversion specifier.
3498 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
3500 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3501 << CS.toString() << /*conversion specifier*/1,
3502 getLocationOfByte(CS.getStart()),
3503 /*IsStringLocation*/true,
3504 getSpecifierRange(startSpecifier, specifierLen));
3506 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3507 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3508 << FixedCS->toString()
3509 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3511 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3512 << CS.toString() << /*conversion specifier*/1,
3513 getLocationOfByte(CS.getStart()),
3514 /*IsStringLocation*/true,
3515 getSpecifierRange(startSpecifier, specifierLen));
3519 void CheckFormatHandler::HandlePosition(const char *startPos,
3521 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3522 getLocationOfByte(startPos),
3523 /*IsStringLocation*/true,
3524 getSpecifierRange(startPos, posLen));
3528 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3529 analyze_format_string::PositionContext p) {
3530 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3532 getLocationOfByte(startPos), /*IsStringLocation*/true,
3533 getSpecifierRange(startPos, posLen));
3536 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
3538 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3539 getLocationOfByte(startPos),
3540 /*IsStringLocation*/true,
3541 getSpecifierRange(startPos, posLen));
3544 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
3545 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
3546 // The presence of a null character is likely an error.
3547 EmitFormatDiagnostic(
3548 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3549 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3550 getFormatStringRange());
3554 // Note that this may return NULL if there was an error parsing or building
3555 // one of the argument expressions.
3556 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
3557 return Args[FirstDataArg + i];
3560 void CheckFormatHandler::DoneProcessing() {
3561 // Does the number of data arguments exceed the number of
3562 // format conversions in the format string?
3563 if (!HasVAListArg) {
3564 // Find any arguments that weren't covered.
3566 signed notCoveredArg = CoveredArgs.find_first();
3567 if (notCoveredArg >= 0) {
3568 assert((unsigned)notCoveredArg < NumDataArgs);
3569 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3570 SourceLocation Loc = E->getLocStart();
3571 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3572 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3573 Loc, /*IsStringLocation*/false,
3574 getFormatStringRange());
3582 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3584 const char *startSpec,
3585 unsigned specifierLen,
3586 const char *csStart,
3589 bool keepGoing = true;
3590 if (argIndex < NumDataArgs) {
3591 // Consider the argument coverered, even though the specifier doesn't
3593 CoveredArgs.set(argIndex);
3596 // If argIndex exceeds the number of data arguments we
3597 // don't issue a warning because that is just a cascade of warnings (and
3598 // they may have intended '%%' anyway). We don't want to continue processing
3599 // the format string after this point, however, as we will like just get
3600 // gibberish when trying to match arguments.
3604 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3605 << StringRef(csStart, csLen),
3606 Loc, /*IsStringLocation*/true,
3607 getSpecifierRange(startSpec, specifierLen));
3613 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3614 const char *startSpec,
3615 unsigned specifierLen) {
3616 EmitFormatDiagnostic(
3617 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3618 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3622 CheckFormatHandler::CheckNumArgs(
3623 const analyze_format_string::FormatSpecifier &FS,
3624 const analyze_format_string::ConversionSpecifier &CS,
3625 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3627 if (argIndex >= NumDataArgs) {
3628 PartialDiagnostic PDiag = FS.usesPositionalArg()
3629 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3630 << (argIndex+1) << NumDataArgs)
3631 : S.PDiag(diag::warn_printf_insufficient_data_args);
3632 EmitFormatDiagnostic(
3633 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3634 getSpecifierRange(startSpecifier, specifierLen));
3640 template<typename Range>
3641 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3643 bool IsStringLocation,
3645 ArrayRef<FixItHint> FixIt) {
3646 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
3647 Loc, IsStringLocation, StringRange, FixIt);
3650 /// \brief If the format string is not within the funcion call, emit a note
3651 /// so that the function call and string are in diagnostic messages.
3653 /// \param InFunctionCall if true, the format string is within the function
3654 /// call and only one diagnostic message will be produced. Otherwise, an
3655 /// extra note will be emitted pointing to location of the format string.
3657 /// \param ArgumentExpr the expression that is passed as the format string
3658 /// argument in the function call. Used for getting locations when two
3659 /// diagnostics are emitted.
3661 /// \param PDiag the callee should already have provided any strings for the
3662 /// diagnostic message. This function only adds locations and fixits
3665 /// \param Loc primary location for diagnostic. If two diagnostics are
3666 /// required, one will be at Loc and a new SourceLocation will be created for
3669 /// \param IsStringLocation if true, Loc points to the format string should be
3670 /// used for the note. Otherwise, Loc points to the argument list and will
3671 /// be used with PDiag.
3673 /// \param StringRange some or all of the string to highlight. This is
3674 /// templated so it can accept either a CharSourceRange or a SourceRange.
3676 /// \param FixIt optional fix it hint for the format string.
3677 template<typename Range>
3678 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3679 const Expr *ArgumentExpr,
3680 PartialDiagnostic PDiag,
3682 bool IsStringLocation,
3684 ArrayRef<FixItHint> FixIt) {
3685 if (InFunctionCall) {
3686 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3690 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3691 << ArgumentExpr->getSourceRange();
3693 const Sema::SemaDiagnosticBuilder &Note =
3694 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3695 diag::note_format_string_defined);
3697 Note << StringRange;
3702 //===--- CHECK: Printf format string checking ------------------------------===//
3705 class CheckPrintfHandler : public CheckFormatHandler {
3708 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3709 const Expr *origFormatExpr, unsigned firstDataArg,
3710 unsigned numDataArgs, bool isObjC,
3711 const char *beg, bool hasVAListArg,
3712 ArrayRef<const Expr *> Args,
3713 unsigned formatIdx, bool inFunctionCall,
3714 Sema::VariadicCallType CallType,
3715 llvm::SmallBitVector &CheckedVarArgs)
3716 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3717 numDataArgs, beg, hasVAListArg, Args,
3718 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3723 bool HandleInvalidPrintfConversionSpecifier(
3724 const analyze_printf::PrintfSpecifier &FS,
3725 const char *startSpecifier,
3726 unsigned specifierLen) override;
3728 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3729 const char *startSpecifier,
3730 unsigned specifierLen) override;
3731 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3732 const char *StartSpecifier,
3733 unsigned SpecifierLen,
3736 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3737 const char *startSpecifier, unsigned specifierLen);
3738 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3739 const analyze_printf::OptionalAmount &Amt,
3741 const char *startSpecifier, unsigned specifierLen);
3742 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3743 const analyze_printf::OptionalFlag &flag,
3744 const char *startSpecifier, unsigned specifierLen);
3745 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3746 const analyze_printf::OptionalFlag &ignoredFlag,
3747 const analyze_printf::OptionalFlag &flag,
3748 const char *startSpecifier, unsigned specifierLen);
3749 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
3752 void HandleEmptyObjCModifierFlag(const char *startFlag,
3753 unsigned flagLen) override;
3755 void HandleInvalidObjCModifierFlag(const char *startFlag,
3756 unsigned flagLen) override;
3758 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
3759 const char *flagsEnd,
3760 const char *conversionPosition)
3765 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3766 const analyze_printf::PrintfSpecifier &FS,
3767 const char *startSpecifier,
3768 unsigned specifierLen) {
3769 const analyze_printf::PrintfConversionSpecifier &CS =
3770 FS.getConversionSpecifier();
3772 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3773 getLocationOfByte(CS.getStart()),
3774 startSpecifier, specifierLen,
3775 CS.getStart(), CS.getLength());
3778 bool CheckPrintfHandler::HandleAmount(
3779 const analyze_format_string::OptionalAmount &Amt,
3780 unsigned k, const char *startSpecifier,
3781 unsigned specifierLen) {
3783 if (Amt.hasDataArgument()) {
3784 if (!HasVAListArg) {
3785 unsigned argIndex = Amt.getArgIndex();
3786 if (argIndex >= NumDataArgs) {
3787 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3789 getLocationOfByte(Amt.getStart()),
3790 /*IsStringLocation*/true,
3791 getSpecifierRange(startSpecifier, specifierLen));
3792 // Don't do any more checking. We will just emit
3797 // Type check the data argument. It should be an 'int'.
3798 // Although not in conformance with C99, we also allow the argument to be
3799 // an 'unsigned int' as that is a reasonably safe case. GCC also
3800 // doesn't emit a warning for that case.
3801 CoveredArgs.set(argIndex);
3802 const Expr *Arg = getDataArg(argIndex);
3806 QualType T = Arg->getType();
3808 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3809 assert(AT.isValid());
3811 if (!AT.matchesType(S.Context, T)) {
3812 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
3813 << k << AT.getRepresentativeTypeName(S.Context)
3814 << T << Arg->getSourceRange(),
3815 getLocationOfByte(Amt.getStart()),
3816 /*IsStringLocation*/true,
3817 getSpecifierRange(startSpecifier, specifierLen));
3818 // Don't do any more checking. We will just emit
3827 void CheckPrintfHandler::HandleInvalidAmount(
3828 const analyze_printf::PrintfSpecifier &FS,
3829 const analyze_printf::OptionalAmount &Amt,
3831 const char *startSpecifier,
3832 unsigned specifierLen) {
3833 const analyze_printf::PrintfConversionSpecifier &CS =
3834 FS.getConversionSpecifier();
3837 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3838 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3839 Amt.getConstantLength()))
3842 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3843 << type << CS.toString(),
3844 getLocationOfByte(Amt.getStart()),
3845 /*IsStringLocation*/true,
3846 getSpecifierRange(startSpecifier, specifierLen),
3850 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3851 const analyze_printf::OptionalFlag &flag,
3852 const char *startSpecifier,
3853 unsigned specifierLen) {
3854 // Warn about pointless flag with a fixit removal.
3855 const analyze_printf::PrintfConversionSpecifier &CS =
3856 FS.getConversionSpecifier();
3857 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3858 << flag.toString() << CS.toString(),
3859 getLocationOfByte(flag.getPosition()),
3860 /*IsStringLocation*/true,
3861 getSpecifierRange(startSpecifier, specifierLen),
3862 FixItHint::CreateRemoval(
3863 getSpecifierRange(flag.getPosition(), 1)));
3866 void CheckPrintfHandler::HandleIgnoredFlag(
3867 const analyze_printf::PrintfSpecifier &FS,
3868 const analyze_printf::OptionalFlag &ignoredFlag,
3869 const analyze_printf::OptionalFlag &flag,
3870 const char *startSpecifier,
3871 unsigned specifierLen) {
3872 // Warn about ignored flag with a fixit removal.
3873 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3874 << ignoredFlag.toString() << flag.toString(),
3875 getLocationOfByte(ignoredFlag.getPosition()),
3876 /*IsStringLocation*/true,
3877 getSpecifierRange(startSpecifier, specifierLen),
3878 FixItHint::CreateRemoval(
3879 getSpecifierRange(ignoredFlag.getPosition(), 1)));
3882 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3883 // bool IsStringLocation, Range StringRange,
3884 // ArrayRef<FixItHint> Fixit = None);
3886 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
3888 // Warn about an empty flag.
3889 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
3890 getLocationOfByte(startFlag),
3891 /*IsStringLocation*/true,
3892 getSpecifierRange(startFlag, flagLen));
3895 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
3897 // Warn about an invalid flag.
3898 auto Range = getSpecifierRange(startFlag, flagLen);
3899 StringRef flag(startFlag, flagLen);
3900 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
3901 getLocationOfByte(startFlag),
3902 /*IsStringLocation*/true,
3903 Range, FixItHint::CreateRemoval(Range));
3906 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
3907 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
3908 // Warn about using '[...]' without a '@' conversion.
3909 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
3910 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
3911 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
3912 getLocationOfByte(conversionPosition),
3913 /*IsStringLocation*/true,
3914 Range, FixItHint::CreateRemoval(Range));
3917 // Determines if the specified is a C++ class or struct containing
3918 // a member with the specified name and kind (e.g. a CXXMethodDecl named
3920 template<typename MemberKind>
3921 static llvm::SmallPtrSet<MemberKind*, 1>
3922 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3923 const RecordType *RT = Ty->getAs<RecordType>();
3924 llvm::SmallPtrSet<MemberKind*, 1> Results;
3928 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
3929 if (!RD || !RD->getDefinition())
3932 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
3933 Sema::LookupMemberName);
3934 R.suppressDiagnostics();
3936 // We just need to include all members of the right kind turned up by the
3937 // filter, at this point.
3938 if (S.LookupQualifiedName(R, RT->getDecl()))
3939 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3940 NamedDecl *decl = (*I)->getUnderlyingDecl();
3941 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3947 /// Check if we could call '.c_str()' on an object.
3949 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3950 /// allow the call, or if it would be ambiguous).
3951 bool Sema::hasCStrMethod(const Expr *E) {
3952 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3954 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3955 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3957 if ((*MI)->getMinRequiredArguments() == 0)
3962 // Check if a (w)string was passed when a (w)char* was needed, and offer a
3963 // better diagnostic if so. AT is assumed to be valid.
3964 // Returns true when a c_str() conversion method is found.
3965 bool CheckPrintfHandler::checkForCStrMembers(
3966 const analyze_printf::ArgType &AT, const Expr *E) {
3967 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3970 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3972 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3974 const CXXMethodDecl *Method = *MI;
3975 if (Method->getMinRequiredArguments() == 0 &&
3976 AT.matchesType(S.Context, Method->getReturnType())) {
3977 // FIXME: Suggest parens if the expression needs them.
3978 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
3979 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3981 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3990 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
3992 const char *startSpecifier,
3993 unsigned specifierLen) {
3995 using namespace analyze_format_string;
3996 using namespace analyze_printf;
3997 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
3999 if (FS.consumesDataArgument()) {
4002 usesPositionalArgs = FS.usesPositionalArg();
4004 else if (usesPositionalArgs != FS.usesPositionalArg()) {
4005 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4006 startSpecifier, specifierLen);
4011 // First check if the field width, precision, and conversion specifier
4012 // have matching data arguments.
4013 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4014 startSpecifier, specifierLen)) {
4018 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4019 startSpecifier, specifierLen)) {
4023 if (!CS.consumesDataArgument()) {
4024 // FIXME: Technically specifying a precision or field width here
4025 // makes no sense. Worth issuing a warning at some point.
4029 // Consume the argument.
4030 unsigned argIndex = FS.getArgIndex();
4031 if (argIndex < NumDataArgs) {
4032 // The check to see if the argIndex is valid will come later.
4033 // We set the bit here because we may exit early from this
4034 // function if we encounter some other error.
4035 CoveredArgs.set(argIndex);
4038 // FreeBSD kernel extensions.
4039 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4040 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4041 // We need at least two arguments.
4042 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4045 // Claim the second argument.
4046 CoveredArgs.set(argIndex + 1);
4048 // Type check the first argument (int for %b, pointer for %D)
4049 const Expr *Ex = getDataArg(argIndex);
4050 const analyze_printf::ArgType &AT =
4051 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4052 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4053 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4054 EmitFormatDiagnostic(
4055 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4056 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4057 << false << Ex->getSourceRange(),
4058 Ex->getLocStart(), /*IsStringLocation*/false,
4059 getSpecifierRange(startSpecifier, specifierLen));
4061 // Type check the second argument (char * for both %b and %D)
4062 Ex = getDataArg(argIndex + 1);
4063 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4064 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4065 EmitFormatDiagnostic(
4066 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4067 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4068 << false << Ex->getSourceRange(),
4069 Ex->getLocStart(), /*IsStringLocation*/false,
4070 getSpecifierRange(startSpecifier, specifierLen));
4075 // Check for using an Objective-C specific conversion specifier
4076 // in a non-ObjC literal.
4077 if (!ObjCContext && CS.isObjCArg()) {
4078 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4082 // Check for invalid use of field width
4083 if (!FS.hasValidFieldWidth()) {
4084 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
4085 startSpecifier, specifierLen);
4088 // Check for invalid use of precision
4089 if (!FS.hasValidPrecision()) {
4090 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4091 startSpecifier, specifierLen);
4094 // Check each flag does not conflict with any other component.
4095 if (!FS.hasValidThousandsGroupingPrefix())
4096 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
4097 if (!FS.hasValidLeadingZeros())
4098 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4099 if (!FS.hasValidPlusPrefix())
4100 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
4101 if (!FS.hasValidSpacePrefix())
4102 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
4103 if (!FS.hasValidAlternativeForm())
4104 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4105 if (!FS.hasValidLeftJustified())
4106 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4108 // Check that flags are not ignored by another flag
4109 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4110 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4111 startSpecifier, specifierLen);
4112 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4113 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4114 startSpecifier, specifierLen);
4116 // Check the length modifier is valid with the given conversion specifier.
4117 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
4118 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4119 diag::warn_format_nonsensical_length);
4120 else if (!FS.hasStandardLengthModifier())
4121 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
4122 else if (!FS.hasStandardLengthConversionCombination())
4123 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4124 diag::warn_format_non_standard_conversion_spec);
4126 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4127 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4129 // The remaining checks depend on the data arguments.
4133 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
4136 const Expr *Arg = getDataArg(argIndex);
4140 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
4143 static bool requiresParensToAddCast(const Expr *E) {
4144 // FIXME: We should have a general way to reason about operator
4145 // precedence and whether parens are actually needed here.
4146 // Take care of a few common cases where they aren't.
4147 const Expr *Inside = E->IgnoreImpCasts();
4148 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4149 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4151 switch (Inside->getStmtClass()) {
4152 case Stmt::ArraySubscriptExprClass:
4153 case Stmt::CallExprClass:
4154 case Stmt::CharacterLiteralClass:
4155 case Stmt::CXXBoolLiteralExprClass:
4156 case Stmt::DeclRefExprClass:
4157 case Stmt::FloatingLiteralClass:
4158 case Stmt::IntegerLiteralClass:
4159 case Stmt::MemberExprClass:
4160 case Stmt::ObjCArrayLiteralClass:
4161 case Stmt::ObjCBoolLiteralExprClass:
4162 case Stmt::ObjCBoxedExprClass:
4163 case Stmt::ObjCDictionaryLiteralClass:
4164 case Stmt::ObjCEncodeExprClass:
4165 case Stmt::ObjCIvarRefExprClass:
4166 case Stmt::ObjCMessageExprClass:
4167 case Stmt::ObjCPropertyRefExprClass:
4168 case Stmt::ObjCStringLiteralClass:
4169 case Stmt::ObjCSubscriptRefExprClass:
4170 case Stmt::ParenExprClass:
4171 case Stmt::StringLiteralClass:
4172 case Stmt::UnaryOperatorClass:
4179 static std::pair<QualType, StringRef>
4180 shouldNotPrintDirectly(const ASTContext &Context,
4181 QualType IntendedTy,
4183 // Use a 'while' to peel off layers of typedefs.
4184 QualType TyTy = IntendedTy;
4185 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4186 StringRef Name = UserTy->getDecl()->getName();
4187 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4188 .Case("NSInteger", Context.LongTy)
4189 .Case("NSUInteger", Context.UnsignedLongTy)
4190 .Case("SInt32", Context.IntTy)
4191 .Case("UInt32", Context.UnsignedIntTy)
4192 .Default(QualType());
4194 if (!CastTy.isNull())
4195 return std::make_pair(CastTy, Name);
4197 TyTy = UserTy->desugar();
4200 // Strip parens if necessary.
4201 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4202 return shouldNotPrintDirectly(Context,
4203 PE->getSubExpr()->getType(),
4206 // If this is a conditional expression, then its result type is constructed
4207 // via usual arithmetic conversions and thus there might be no necessary
4208 // typedef sugar there. Recurse to operands to check for NSInteger &
4209 // Co. usage condition.
4210 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4211 QualType TrueTy, FalseTy;
4212 StringRef TrueName, FalseName;
4214 std::tie(TrueTy, TrueName) =
4215 shouldNotPrintDirectly(Context,
4216 CO->getTrueExpr()->getType(),
4218 std::tie(FalseTy, FalseName) =
4219 shouldNotPrintDirectly(Context,
4220 CO->getFalseExpr()->getType(),
4221 CO->getFalseExpr());
4223 if (TrueTy == FalseTy)
4224 return std::make_pair(TrueTy, TrueName);
4225 else if (TrueTy.isNull())
4226 return std::make_pair(FalseTy, FalseName);
4227 else if (FalseTy.isNull())
4228 return std::make_pair(TrueTy, TrueName);
4231 return std::make_pair(QualType(), StringRef());
4235 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4236 const char *StartSpecifier,
4237 unsigned SpecifierLen,
4239 using namespace analyze_format_string;
4240 using namespace analyze_printf;
4241 // Now type check the data expression that matches the
4242 // format specifier.
4243 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4248 QualType ExprTy = E->getType();
4249 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4250 ExprTy = TET->getUnderlyingExpr()->getType();
4253 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4255 if (match == analyze_printf::ArgType::Match) {
4259 // Look through argument promotions for our error message's reported type.
4260 // This includes the integral and floating promotions, but excludes array
4261 // and function pointer decay; seeing that an argument intended to be a
4262 // string has type 'char [6]' is probably more confusing than 'char *'.
4263 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4264 if (ICE->getCastKind() == CK_IntegralCast ||
4265 ICE->getCastKind() == CK_FloatingCast) {
4266 E = ICE->getSubExpr();
4267 ExprTy = E->getType();
4269 // Check if we didn't match because of an implicit cast from a 'char'
4270 // or 'short' to an 'int'. This is done because printf is a varargs
4272 if (ICE->getType() == S.Context.IntTy ||
4273 ICE->getType() == S.Context.UnsignedIntTy) {
4274 // All further checking is done on the subexpression.
4275 if (AT.matchesType(S.Context, ExprTy))
4279 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4280 // Special case for 'a', which has type 'int' in C.
4281 // Note, however, that we do /not/ want to treat multibyte constants like
4282 // 'MooV' as characters! This form is deprecated but still exists.
4283 if (ExprTy == S.Context.IntTy)
4284 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4285 ExprTy = S.Context.CharTy;
4288 // Look through enums to their underlying type.
4289 bool IsEnum = false;
4290 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4291 ExprTy = EnumTy->getDecl()->getIntegerType();
4295 // %C in an Objective-C context prints a unichar, not a wchar_t.
4296 // If the argument is an integer of some kind, believe the %C and suggest
4297 // a cast instead of changing the conversion specifier.
4298 QualType IntendedTy = ExprTy;
4300 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4301 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4302 !ExprTy->isCharType()) {
4303 // 'unichar' is defined as a typedef of unsigned short, but we should
4304 // prefer using the typedef if it is visible.
4305 IntendedTy = S.Context.UnsignedShortTy;
4307 // While we are here, check if the value is an IntegerLiteral that happens
4308 // to be within the valid range.
4309 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4310 const llvm::APInt &V = IL->getValue();
4311 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4315 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4316 Sema::LookupOrdinaryName);
4317 if (S.LookupName(Result, S.getCurScope())) {
4318 NamedDecl *ND = Result.getFoundDecl();
4319 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4320 if (TD->getUnderlyingType() == IntendedTy)
4321 IntendedTy = S.Context.getTypedefType(TD);
4326 // Special-case some of Darwin's platform-independence types by suggesting
4327 // casts to primitive types that are known to be large enough.
4328 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
4329 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
4331 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4332 if (!CastTy.isNull()) {
4333 IntendedTy = CastTy;
4334 ShouldNotPrintDirectly = true;
4338 // We may be able to offer a FixItHint if it is a supported type.
4339 PrintfSpecifier fixedFS = FS;
4340 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
4341 S.Context, ObjCContext);
4344 // Get the fix string from the fixed format specifier
4345 SmallString<16> buf;
4346 llvm::raw_svector_ostream os(buf);
4347 fixedFS.toString(os);
4349 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4351 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
4352 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4353 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4354 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4356 // In this case, the specifier is wrong and should be changed to match
4358 EmitFormatDiagnostic(S.PDiag(diag)
4359 << AT.getRepresentativeTypeName(S.Context)
4360 << IntendedTy << IsEnum << E->getSourceRange(),
4362 /*IsStringLocation*/ false, SpecRange,
4363 FixItHint::CreateReplacement(SpecRange, os.str()));
4366 // The canonical type for formatting this value is different from the
4367 // actual type of the expression. (This occurs, for example, with Darwin's
4368 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4369 // should be printed as 'long' for 64-bit compatibility.)
4370 // Rather than emitting a normal format/argument mismatch, we want to
4371 // add a cast to the recommended type (and correct the format string
4373 SmallString<16> CastBuf;
4374 llvm::raw_svector_ostream CastFix(CastBuf);
4376 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4379 SmallVector<FixItHint,4> Hints;
4380 if (!AT.matchesType(S.Context, IntendedTy))
4381 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4383 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4384 // If there's already a cast present, just replace it.
4385 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4386 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4388 } else if (!requiresParensToAddCast(E)) {
4389 // If the expression has high enough precedence,
4390 // just write the C-style cast.
4391 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4394 // Otherwise, add parens around the expression as well as the cast.
4396 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4399 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
4400 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4403 if (ShouldNotPrintDirectly) {
4404 // The expression has a type that should not be printed directly.
4405 // We extract the name from the typedef because we don't want to show
4406 // the underlying type in the diagnostic.
4408 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4409 Name = TypedefTy->getDecl()->getName();
4412 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
4413 << Name << IntendedTy << IsEnum
4414 << E->getSourceRange(),
4415 E->getLocStart(), /*IsStringLocation=*/false,
4418 // In this case, the expression could be printed using a different
4419 // specifier, but we've decided that the specifier is probably correct
4420 // and we should cast instead. Just use the normal warning message.
4421 EmitFormatDiagnostic(
4422 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4423 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
4424 << E->getSourceRange(),
4425 E->getLocStart(), /*IsStringLocation*/false,
4430 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4432 // Since the warning for passing non-POD types to variadic functions
4433 // was deferred until now, we emit a warning for non-POD
4435 switch (S.isValidVarArgType(ExprTy)) {
4436 case Sema::VAK_Valid:
4437 case Sema::VAK_ValidInCXX11: {
4438 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4439 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4440 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4443 EmitFormatDiagnostic(
4444 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4445 << IsEnum << CSR << E->getSourceRange(),
4446 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4449 case Sema::VAK_Undefined:
4450 case Sema::VAK_MSVCUndefined:
4451 EmitFormatDiagnostic(
4452 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
4453 << S.getLangOpts().CPlusPlus11
4456 << AT.getRepresentativeTypeName(S.Context)
4458 << E->getSourceRange(),
4459 E->getLocStart(), /*IsStringLocation*/false, CSR);
4460 checkForCStrMembers(AT, E);
4463 case Sema::VAK_Invalid:
4464 if (ExprTy->isObjCObjectType())
4465 EmitFormatDiagnostic(
4466 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4467 << S.getLangOpts().CPlusPlus11
4470 << AT.getRepresentativeTypeName(S.Context)
4472 << E->getSourceRange(),
4473 E->getLocStart(), /*IsStringLocation*/false, CSR);
4475 // FIXME: If this is an initializer list, suggest removing the braces
4476 // or inserting a cast to the target type.
4477 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4478 << isa<InitListExpr>(E) << ExprTy << CallType
4479 << AT.getRepresentativeTypeName(S.Context)
4480 << E->getSourceRange();
4484 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4485 "format string specifier index out of range");
4486 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
4492 //===--- CHECK: Scanf format string checking ------------------------------===//
4495 class CheckScanfHandler : public CheckFormatHandler {
4497 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4498 const Expr *origFormatExpr, unsigned firstDataArg,
4499 unsigned numDataArgs, const char *beg, bool hasVAListArg,
4500 ArrayRef<const Expr *> Args,
4501 unsigned formatIdx, bool inFunctionCall,
4502 Sema::VariadicCallType CallType,
4503 llvm::SmallBitVector &CheckedVarArgs)
4504 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4505 numDataArgs, beg, hasVAListArg,
4506 Args, formatIdx, inFunctionCall, CallType,
4510 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4511 const char *startSpecifier,
4512 unsigned specifierLen) override;
4514 bool HandleInvalidScanfConversionSpecifier(
4515 const analyze_scanf::ScanfSpecifier &FS,
4516 const char *startSpecifier,
4517 unsigned specifierLen) override;
4519 void HandleIncompleteScanList(const char *start, const char *end) override;
4523 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4525 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4526 getLocationOfByte(end), /*IsStringLocation*/true,
4527 getSpecifierRange(start, end - start));
4530 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4531 const analyze_scanf::ScanfSpecifier &FS,
4532 const char *startSpecifier,
4533 unsigned specifierLen) {
4535 const analyze_scanf::ScanfConversionSpecifier &CS =
4536 FS.getConversionSpecifier();
4538 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4539 getLocationOfByte(CS.getStart()),
4540 startSpecifier, specifierLen,
4541 CS.getStart(), CS.getLength());
4544 bool CheckScanfHandler::HandleScanfSpecifier(
4545 const analyze_scanf::ScanfSpecifier &FS,
4546 const char *startSpecifier,
4547 unsigned specifierLen) {
4549 using namespace analyze_scanf;
4550 using namespace analyze_format_string;
4552 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
4554 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4555 // be used to decide if we are using positional arguments consistently.
4556 if (FS.consumesDataArgument()) {
4559 usesPositionalArgs = FS.usesPositionalArg();
4561 else if (usesPositionalArgs != FS.usesPositionalArg()) {
4562 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4563 startSpecifier, specifierLen);
4568 // Check if the field with is non-zero.
4569 const OptionalAmount &Amt = FS.getFieldWidth();
4570 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4571 if (Amt.getConstantAmount() == 0) {
4572 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4573 Amt.getConstantLength());
4574 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4575 getLocationOfByte(Amt.getStart()),
4576 /*IsStringLocation*/true, R,
4577 FixItHint::CreateRemoval(R));
4581 if (!FS.consumesDataArgument()) {
4582 // FIXME: Technically specifying a precision or field width here
4583 // makes no sense. Worth issuing a warning at some point.
4587 // Consume the argument.
4588 unsigned argIndex = FS.getArgIndex();
4589 if (argIndex < NumDataArgs) {
4590 // The check to see if the argIndex is valid will come later.
4591 // We set the bit here because we may exit early from this
4592 // function if we encounter some other error.
4593 CoveredArgs.set(argIndex);
4596 // Check the length modifier is valid with the given conversion specifier.
4597 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
4598 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4599 diag::warn_format_nonsensical_length);
4600 else if (!FS.hasStandardLengthModifier())
4601 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
4602 else if (!FS.hasStandardLengthConversionCombination())
4603 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4604 diag::warn_format_non_standard_conversion_spec);
4606 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4607 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4609 // The remaining checks depend on the data arguments.
4613 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
4616 // Check that the argument type matches the format specifier.
4617 const Expr *Ex = getDataArg(argIndex);
4621 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
4623 if (!AT.isValid()) {
4627 analyze_format_string::ArgType::MatchKind match =
4628 AT.matchesType(S.Context, Ex->getType());
4629 if (match == analyze_format_string::ArgType::Match) {
4633 ScanfSpecifier fixedFS = FS;
4634 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4635 S.getLangOpts(), S.Context);
4637 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4638 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4639 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4643 // Get the fix string from the fixed format specifier.
4644 SmallString<128> buf;
4645 llvm::raw_svector_ostream os(buf);
4646 fixedFS.toString(os);
4648 EmitFormatDiagnostic(
4649 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4650 << Ex->getType() << false << Ex->getSourceRange(),
4652 /*IsStringLocation*/ false,
4653 getSpecifierRange(startSpecifier, specifierLen),
4654 FixItHint::CreateReplacement(
4655 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4657 EmitFormatDiagnostic(S.PDiag(diag)
4658 << AT.getRepresentativeTypeName(S.Context)
4659 << Ex->getType() << false << Ex->getSourceRange(),
4661 /*IsStringLocation*/ false,
4662 getSpecifierRange(startSpecifier, specifierLen));
4668 void Sema::CheckFormatString(const StringLiteral *FExpr,
4669 const Expr *OrigFormatExpr,
4670 ArrayRef<const Expr *> Args,
4671 bool HasVAListArg, unsigned format_idx,
4672 unsigned firstDataArg, FormatStringType Type,
4673 bool inFunctionCall, VariadicCallType CallType,
4674 llvm::SmallBitVector &CheckedVarArgs) {
4676 // CHECK: is the format string a wide literal?
4677 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
4678 CheckFormatHandler::EmitFormatDiagnostic(
4679 *this, inFunctionCall, Args[format_idx],
4680 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4681 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
4685 // Str - The format string. NOTE: this is NOT null-terminated!
4686 StringRef StrRef = FExpr->getString();
4687 const char *Str = StrRef.data();
4688 // Account for cases where the string literal is truncated in a declaration.
4689 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4690 assert(T && "String literal not of constant array type!");
4691 size_t TypeSize = T->getSize().getZExtValue();
4692 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4693 const unsigned numDataArgs = Args.size() - firstDataArg;
4695 // Emit a warning if the string literal is truncated and does not contain an
4696 // embedded null character.
4697 if (TypeSize <= StrRef.size() &&
4698 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4699 CheckFormatHandler::EmitFormatDiagnostic(
4700 *this, inFunctionCall, Args[format_idx],
4701 PDiag(diag::warn_printf_format_string_not_null_terminated),
4702 FExpr->getLocStart(),
4703 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4707 // CHECK: empty format string?
4708 if (StrLen == 0 && numDataArgs > 0) {
4709 CheckFormatHandler::EmitFormatDiagnostic(
4710 *this, inFunctionCall, Args[format_idx],
4711 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4712 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
4716 if (Type == FST_Printf || Type == FST_NSString ||
4717 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
4718 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
4719 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
4720 Str, HasVAListArg, Args, format_idx,
4721 inFunctionCall, CallType, CheckedVarArgs);
4723 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
4725 Context.getTargetInfo(),
4726 Type == FST_FreeBSDKPrintf))
4728 } else if (Type == FST_Scanf) {
4729 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
4730 Str, HasVAListArg, Args, format_idx,
4731 inFunctionCall, CallType, CheckedVarArgs);
4733 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
4735 Context.getTargetInfo()))
4737 } // TODO: handle other formats
4740 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4741 // Str - The format string. NOTE: this is NOT null-terminated!
4742 StringRef StrRef = FExpr->getString();
4743 const char *Str = StrRef.data();
4744 // Account for cases where the string literal is truncated in a declaration.
4745 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4746 assert(T && "String literal not of constant array type!");
4747 size_t TypeSize = T->getSize().getZExtValue();
4748 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4749 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4751 Context.getTargetInfo());
4754 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4756 // Returns the related absolute value function that is larger, of 0 if one
4758 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4759 switch (AbsFunction) {
4763 case Builtin::BI__builtin_abs:
4764 return Builtin::BI__builtin_labs;
4765 case Builtin::BI__builtin_labs:
4766 return Builtin::BI__builtin_llabs;
4767 case Builtin::BI__builtin_llabs:
4770 case Builtin::BI__builtin_fabsf:
4771 return Builtin::BI__builtin_fabs;
4772 case Builtin::BI__builtin_fabs:
4773 return Builtin::BI__builtin_fabsl;
4774 case Builtin::BI__builtin_fabsl:
4777 case Builtin::BI__builtin_cabsf:
4778 return Builtin::BI__builtin_cabs;
4779 case Builtin::BI__builtin_cabs:
4780 return Builtin::BI__builtin_cabsl;
4781 case Builtin::BI__builtin_cabsl:
4784 case Builtin::BIabs:
4785 return Builtin::BIlabs;
4786 case Builtin::BIlabs:
4787 return Builtin::BIllabs;
4788 case Builtin::BIllabs:
4791 case Builtin::BIfabsf:
4792 return Builtin::BIfabs;
4793 case Builtin::BIfabs:
4794 return Builtin::BIfabsl;
4795 case Builtin::BIfabsl:
4798 case Builtin::BIcabsf:
4799 return Builtin::BIcabs;
4800 case Builtin::BIcabs:
4801 return Builtin::BIcabsl;
4802 case Builtin::BIcabsl:
4807 // Returns the argument type of the absolute value function.
4808 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4813 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4814 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4815 if (Error != ASTContext::GE_None)
4818 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4822 if (FT->getNumParams() != 1)
4825 return FT->getParamType(0);
4828 // Returns the best absolute value function, or zero, based on type and
4829 // current absolute value function.
4830 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4831 unsigned AbsFunctionKind) {
4832 unsigned BestKind = 0;
4833 uint64_t ArgSize = Context.getTypeSize(ArgType);
4834 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4835 Kind = getLargerAbsoluteValueFunction(Kind)) {
4836 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4837 if (Context.getTypeSize(ParamType) >= ArgSize) {
4840 else if (Context.hasSameType(ParamType, ArgType)) {
4849 enum AbsoluteValueKind {
4855 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4856 if (T->isIntegralOrEnumerationType())
4858 if (T->isRealFloatingType())
4859 return AVK_Floating;
4860 if (T->isAnyComplexType())
4863 llvm_unreachable("Type not integer, floating, or complex");
4866 // Changes the absolute value function to a different type. Preserves whether
4867 // the function is a builtin.
4868 static unsigned changeAbsFunction(unsigned AbsKind,
4869 AbsoluteValueKind ValueKind) {
4870 switch (ValueKind) {
4875 case Builtin::BI__builtin_fabsf:
4876 case Builtin::BI__builtin_fabs:
4877 case Builtin::BI__builtin_fabsl:
4878 case Builtin::BI__builtin_cabsf:
4879 case Builtin::BI__builtin_cabs:
4880 case Builtin::BI__builtin_cabsl:
4881 return Builtin::BI__builtin_abs;
4882 case Builtin::BIfabsf:
4883 case Builtin::BIfabs:
4884 case Builtin::BIfabsl:
4885 case Builtin::BIcabsf:
4886 case Builtin::BIcabs:
4887 case Builtin::BIcabsl:
4888 return Builtin::BIabs;
4894 case Builtin::BI__builtin_abs:
4895 case Builtin::BI__builtin_labs:
4896 case Builtin::BI__builtin_llabs:
4897 case Builtin::BI__builtin_cabsf:
4898 case Builtin::BI__builtin_cabs:
4899 case Builtin::BI__builtin_cabsl:
4900 return Builtin::BI__builtin_fabsf;
4901 case Builtin::BIabs:
4902 case Builtin::BIlabs:
4903 case Builtin::BIllabs:
4904 case Builtin::BIcabsf:
4905 case Builtin::BIcabs:
4906 case Builtin::BIcabsl:
4907 return Builtin::BIfabsf;
4913 case Builtin::BI__builtin_abs:
4914 case Builtin::BI__builtin_labs:
4915 case Builtin::BI__builtin_llabs:
4916 case Builtin::BI__builtin_fabsf:
4917 case Builtin::BI__builtin_fabs:
4918 case Builtin::BI__builtin_fabsl:
4919 return Builtin::BI__builtin_cabsf;
4920 case Builtin::BIabs:
4921 case Builtin::BIlabs:
4922 case Builtin::BIllabs:
4923 case Builtin::BIfabsf:
4924 case Builtin::BIfabs:
4925 case Builtin::BIfabsl:
4926 return Builtin::BIcabsf;
4929 llvm_unreachable("Unable to convert function");
4932 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
4933 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4937 switch (FDecl->getBuiltinID()) {
4940 case Builtin::BI__builtin_abs:
4941 case Builtin::BI__builtin_fabs:
4942 case Builtin::BI__builtin_fabsf:
4943 case Builtin::BI__builtin_fabsl:
4944 case Builtin::BI__builtin_labs:
4945 case Builtin::BI__builtin_llabs:
4946 case Builtin::BI__builtin_cabs:
4947 case Builtin::BI__builtin_cabsf:
4948 case Builtin::BI__builtin_cabsl:
4949 case Builtin::BIabs:
4950 case Builtin::BIlabs:
4951 case Builtin::BIllabs:
4952 case Builtin::BIfabs:
4953 case Builtin::BIfabsf:
4954 case Builtin::BIfabsl:
4955 case Builtin::BIcabs:
4956 case Builtin::BIcabsf:
4957 case Builtin::BIcabsl:
4958 return FDecl->getBuiltinID();
4960 llvm_unreachable("Unknown Builtin type");
4963 // If the replacement is valid, emit a note with replacement function.
4964 // Additionally, suggest including the proper header if not already included.
4965 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
4966 unsigned AbsKind, QualType ArgType) {
4967 bool EmitHeaderHint = true;
4968 const char *HeaderName = nullptr;
4969 const char *FunctionName = nullptr;
4970 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4971 FunctionName = "std::abs";
4972 if (ArgType->isIntegralOrEnumerationType()) {
4973 HeaderName = "cstdlib";
4974 } else if (ArgType->isRealFloatingType()) {
4975 HeaderName = "cmath";
4977 llvm_unreachable("Invalid Type");
4980 // Lookup all std::abs
4981 if (NamespaceDecl *Std = S.getStdNamespace()) {
4982 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
4983 R.suppressDiagnostics();
4984 S.LookupQualifiedName(R, Std);
4986 for (const auto *I : R) {
4987 const FunctionDecl *FDecl = nullptr;
4988 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4989 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4991 FDecl = dyn_cast<FunctionDecl>(I);
4996 // Found std::abs(), check that they are the right ones.
4997 if (FDecl->getNumParams() != 1)
5000 // Check that the parameter type can handle the argument.
5001 QualType ParamType = FDecl->getParamDecl(0)->getType();
5002 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5003 S.Context.getTypeSize(ArgType) <=
5004 S.Context.getTypeSize(ParamType)) {
5005 // Found a function, don't need the header hint.
5006 EmitHeaderHint = false;
5012 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
5013 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5016 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5017 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5018 R.suppressDiagnostics();
5019 S.LookupName(R, S.getCurScope());
5021 if (R.isSingleResult()) {
5022 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5023 if (FD && FD->getBuiltinID() == AbsKind) {
5024 EmitHeaderHint = false;
5028 } else if (!R.empty()) {
5034 S.Diag(Loc, diag::note_replace_abs_function)
5035 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
5040 if (!EmitHeaderHint)
5043 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5047 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5051 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5054 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5056 while (ND && ND->isInlineNamespace()) {
5057 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
5060 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5063 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5069 // Warn when using the wrong abs() function.
5070 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5071 const FunctionDecl *FDecl,
5072 IdentifierInfo *FnInfo) {
5073 if (Call->getNumArgs() != 1)
5076 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
5077 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5078 if (AbsKind == 0 && !IsStdAbs)
5081 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5082 QualType ParamType = Call->getArg(0)->getType();
5084 // Unsigned types cannot be negative. Suggest removing the absolute value
5086 if (ArgType->isUnsignedIntegerType()) {
5087 const char *FunctionName =
5088 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
5089 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5090 Diag(Call->getExprLoc(), diag::note_remove_abs)
5092 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5096 // Taking the absolute value of a pointer is very suspicious, they probably
5097 // wanted to index into an array, dereference a pointer, call a function, etc.
5098 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5099 unsigned DiagType = 0;
5100 if (ArgType->isFunctionType())
5102 else if (ArgType->isArrayType())
5105 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5109 // std::abs has overloads which prevent most of the absolute value problems
5114 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5115 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5117 // The argument and parameter are the same kind. Check if they are the right
5119 if (ArgValueKind == ParamValueKind) {
5120 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5123 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5124 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5125 << FDecl << ArgType << ParamType;
5127 if (NewAbsKind == 0)
5130 emitReplacement(*this, Call->getExprLoc(),
5131 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
5135 // ArgValueKind != ParamValueKind
5136 // The wrong type of absolute value function was used. Attempt to find the
5138 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5139 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5140 if (NewAbsKind == 0)
5143 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5144 << FDecl << ParamValueKind << ArgValueKind;
5146 emitReplacement(*this, Call->getExprLoc(),
5147 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
5151 //===--- CHECK: Standard memory functions ---------------------------------===//
5153 /// \brief Takes the expression passed to the size_t parameter of functions
5154 /// such as memcmp, strncat, etc and warns if it's a comparison.
5156 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5157 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5158 IdentifierInfo *FnName,
5159 SourceLocation FnLoc,
5160 SourceLocation RParenLoc) {
5161 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5165 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5166 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5169 SourceRange SizeRange = Size->getSourceRange();
5170 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5171 << SizeRange << FnName;
5172 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
5173 << FnName << FixItHint::CreateInsertion(
5174 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
5175 << FixItHint::CreateRemoval(RParenLoc);
5176 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
5177 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
5178 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5184 /// \brief Determine whether the given type is or contains a dynamic class type
5185 /// (e.g., whether it has a vtable).
5186 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5187 bool &IsContained) {
5188 // Look through array types while ignoring qualifiers.
5189 const Type *Ty = T->getBaseElementTypeUnsafe();
5190 IsContained = false;
5192 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5193 RD = RD ? RD->getDefinition() : nullptr;
5197 if (RD->isDynamicClass())
5200 // Check all the fields. If any bases were dynamic, the class is dynamic.
5201 // It's impossible for a class to transitively contain itself by value, so
5202 // infinite recursion is impossible.
5203 for (auto *FD : RD->fields()) {
5205 if (const CXXRecordDecl *ContainedRD =
5206 getContainedDynamicClass(FD->getType(), SubContained)) {
5215 /// \brief If E is a sizeof expression, returns its argument expression,
5216 /// otherwise returns NULL.
5217 static const Expr *getSizeOfExprArg(const Expr *E) {
5218 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5219 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5220 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5221 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
5226 /// \brief If E is a sizeof expression, returns its argument type.
5227 static QualType getSizeOfArgType(const Expr *E) {
5228 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5229 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5230 if (SizeOf->getKind() == clang::UETT_SizeOf)
5231 return SizeOf->getTypeOfArgument();
5236 /// \brief Check for dangerous or invalid arguments to memset().
5238 /// This issues warnings on known problematic, dangerous or unspecified
5239 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5242 /// \param Call The call expression to diagnose.
5243 void Sema::CheckMemaccessArguments(const CallExpr *Call,
5245 IdentifierInfo *FnName) {
5248 // It is possible to have a non-standard definition of memset. Validate
5249 // we have enough arguments, and if not, abort further checking.
5250 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
5251 if (Call->getNumArgs() < ExpectedNumArgs)
5254 unsigned LastArg = (BId == Builtin::BImemset ||
5255 BId == Builtin::BIstrndup ? 1 : 2);
5256 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
5257 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
5259 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5260 Call->getLocStart(), Call->getRParenLoc()))
5263 // We have special checking when the length is a sizeof expression.
5264 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5265 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5266 llvm::FoldingSetNodeID SizeOfArgID;
5268 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5269 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
5270 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
5272 QualType DestTy = Dest->getType();
5274 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
5275 PointeeTy = DestPtrTy->getPointeeType();
5277 // Never warn about void type pointers. This can be used to suppress
5279 if (PointeeTy->isVoidType())
5282 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5283 // actually comparing the expressions for equality. Because computing the
5284 // expression IDs can be expensive, we only do this if the diagnostic is
5287 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5288 SizeOfArg->getExprLoc())) {
5289 // We only compute IDs for expressions if the warning is enabled, and
5290 // cache the sizeof arg's ID.
5291 if (SizeOfArgID == llvm::FoldingSetNodeID())
5292 SizeOfArg->Profile(SizeOfArgID, Context, true);
5293 llvm::FoldingSetNodeID DestID;
5294 Dest->Profile(DestID, Context, true);
5295 if (DestID == SizeOfArgID) {
5296 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5297 // over sizeof(src) as well.
5298 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
5299 StringRef ReadableName = FnName->getName();
5301 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
5302 if (UnaryOp->getOpcode() == UO_AddrOf)
5303 ActionIdx = 1; // If its an address-of operator, just remove it.
5304 if (!PointeeTy->isIncompleteType() &&
5305 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
5306 ActionIdx = 2; // If the pointee's size is sizeof(char),
5307 // suggest an explicit length.
5309 // If the function is defined as a builtin macro, do not show macro
5311 SourceLocation SL = SizeOfArg->getExprLoc();
5312 SourceRange DSR = Dest->getSourceRange();
5313 SourceRange SSR = SizeOfArg->getSourceRange();
5314 SourceManager &SM = getSourceManager();
5316 if (SM.isMacroArgExpansion(SL)) {
5317 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5318 SL = SM.getSpellingLoc(SL);
5319 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5320 SM.getSpellingLoc(DSR.getEnd()));
5321 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5322 SM.getSpellingLoc(SSR.getEnd()));
5325 DiagRuntimeBehavior(SL, SizeOfArg,
5326 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
5332 DiagRuntimeBehavior(SL, SizeOfArg,
5333 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5341 // Also check for cases where the sizeof argument is the exact same
5342 // type as the memory argument, and where it points to a user-defined
5344 if (SizeOfArgTy != QualType()) {
5345 if (PointeeTy->isRecordType() &&
5346 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5347 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5348 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5349 << FnName << SizeOfArgTy << ArgIdx
5350 << PointeeTy << Dest->getSourceRange()
5351 << LenExpr->getSourceRange());
5355 } else if (DestTy->isArrayType()) {
5359 if (PointeeTy == QualType())
5362 // Always complain about dynamic classes.
5364 if (const CXXRecordDecl *ContainedRD =
5365 getContainedDynamicClass(PointeeTy, IsContained)) {
5367 unsigned OperationType = 0;
5368 // "overwritten" if we're warning about the destination for any call
5369 // but memcmp; otherwise a verb appropriate to the call.
5370 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5371 if (BId == Builtin::BImemcpy)
5373 else if(BId == Builtin::BImemmove)
5375 else if (BId == Builtin::BImemcmp)
5379 DiagRuntimeBehavior(
5380 Dest->getExprLoc(), Dest,
5381 PDiag(diag::warn_dyn_class_memaccess)
5382 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5383 << FnName << IsContained << ContainedRD << OperationType
5384 << Call->getCallee()->getSourceRange());
5385 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5386 BId != Builtin::BImemset)
5387 DiagRuntimeBehavior(
5388 Dest->getExprLoc(), Dest,
5389 PDiag(diag::warn_arc_object_memaccess)
5390 << ArgIdx << FnName << PointeeTy
5391 << Call->getCallee()->getSourceRange());
5395 DiagRuntimeBehavior(
5396 Dest->getExprLoc(), Dest,
5397 PDiag(diag::note_bad_memaccess_silence)
5398 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5404 // A little helper routine: ignore addition and subtraction of integer literals.
5405 // This intentionally does not ignore all integer constant expressions because
5406 // we don't want to remove sizeof().
5407 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5408 Ex = Ex->IgnoreParenCasts();
5411 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5412 if (!BO || !BO->isAdditiveOp())
5415 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5416 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5418 if (isa<IntegerLiteral>(RHS))
5420 else if (isa<IntegerLiteral>(LHS))
5429 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5430 ASTContext &Context) {
5431 // Only handle constant-sized or VLAs, but not flexible members.
5432 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5433 // Only issue the FIXIT for arrays of size > 1.
5434 if (CAT->getSize().getSExtValue() <= 1)
5436 } else if (!Ty->isVariableArrayType()) {
5442 // Warn if the user has made the 'size' argument to strlcpy or strlcat
5443 // be the size of the source, instead of the destination.
5444 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5445 IdentifierInfo *FnName) {
5447 // Don't crash if the user has the wrong number of arguments
5448 unsigned NumArgs = Call->getNumArgs();
5449 if ((NumArgs != 3) && (NumArgs != 4))
5452 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5453 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
5454 const Expr *CompareWithSrc = nullptr;
5456 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5457 Call->getLocStart(), Call->getRParenLoc()))
5460 // Look for 'strlcpy(dst, x, sizeof(x))'
5461 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5462 CompareWithSrc = Ex;
5464 // Look for 'strlcpy(dst, x, strlen(x))'
5465 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
5466 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5467 SizeCall->getNumArgs() == 1)
5468 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5472 if (!CompareWithSrc)
5475 // Determine if the argument to sizeof/strlen is equal to the source
5476 // argument. In principle there's all kinds of things you could do
5477 // here, for instance creating an == expression and evaluating it with
5478 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5479 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5483 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5484 if (!CompareWithSrcDRE ||
5485 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5488 const Expr *OriginalSizeArg = Call->getArg(2);
5489 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5490 << OriginalSizeArg->getSourceRange() << FnName;
5492 // Output a FIXIT hint if the destination is an array (rather than a
5493 // pointer to an array). This could be enhanced to handle some
5494 // pointers if we know the actual size, like if DstArg is 'array+2'
5495 // we could say 'sizeof(array)-2'.
5496 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
5497 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
5500 SmallString<128> sizeString;
5501 llvm::raw_svector_ostream OS(sizeString);
5503 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
5506 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5507 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5511 /// Check if two expressions refer to the same declaration.
5512 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5513 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5514 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5515 return D1->getDecl() == D2->getDecl();
5519 static const Expr *getStrlenExprArg(const Expr *E) {
5520 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5521 const FunctionDecl *FD = CE->getDirectCallee();
5522 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
5524 return CE->getArg(0)->IgnoreParenCasts();
5529 // Warn on anti-patterns as the 'size' argument to strncat.
5530 // The correct size argument should look like following:
5531 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5532 void Sema::CheckStrncatArguments(const CallExpr *CE,
5533 IdentifierInfo *FnName) {
5534 // Don't crash if the user has the wrong number of arguments.
5535 if (CE->getNumArgs() < 3)
5537 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5538 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5539 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5541 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5542 CE->getRParenLoc()))
5545 // Identify common expressions, which are wrongly used as the size argument
5546 // to strncat and may lead to buffer overflows.
5547 unsigned PatternType = 0;
5548 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5550 if (referToTheSameDecl(SizeOfArg, DstArg))
5553 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5555 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5556 if (BE->getOpcode() == BO_Sub) {
5557 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5558 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5559 // - sizeof(dst) - strlen(dst)
5560 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5561 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5563 // - sizeof(src) - (anything)
5564 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5569 if (PatternType == 0)
5572 // Generate the diagnostic.
5573 SourceLocation SL = LenArg->getLocStart();
5574 SourceRange SR = LenArg->getSourceRange();
5575 SourceManager &SM = getSourceManager();
5577 // If the function is defined as a builtin macro, do not show macro expansion.
5578 if (SM.isMacroArgExpansion(SL)) {
5579 SL = SM.getSpellingLoc(SL);
5580 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5581 SM.getSpellingLoc(SR.getEnd()));
5584 // Check if the destination is an array (rather than a pointer to an array).
5585 QualType DstTy = DstArg->getType();
5586 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5588 if (!isKnownSizeArray) {
5589 if (PatternType == 1)
5590 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5592 Diag(SL, diag::warn_strncat_src_size) << SR;
5596 if (PatternType == 1)
5597 Diag(SL, diag::warn_strncat_large_size) << SR;
5599 Diag(SL, diag::warn_strncat_src_size) << SR;
5601 SmallString<128> sizeString;
5602 llvm::raw_svector_ostream OS(sizeString);
5604 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
5607 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
5610 Diag(SL, diag::note_strncat_wrong_size)
5611 << FixItHint::CreateReplacement(SR, OS.str());
5614 //===--- CHECK: Return Address of Stack Variable --------------------------===//
5616 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5618 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5621 /// CheckReturnStackAddr - Check if a return statement returns the address
5622 /// of a stack variable.
5624 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5625 SourceLocation ReturnLoc) {
5627 Expr *stackE = nullptr;
5628 SmallVector<DeclRefExpr *, 8> refVars;
5630 // Perform checking for returned stack addresses, local blocks,
5631 // label addresses or references to temporaries.
5632 if (lhsType->isPointerType() ||
5633 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
5634 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
5635 } else if (lhsType->isReferenceType()) {
5636 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
5640 return; // Nothing suspicious was found.
5642 SourceLocation diagLoc;
5643 SourceRange diagRange;
5644 if (refVars.empty()) {
5645 diagLoc = stackE->getLocStart();
5646 diagRange = stackE->getSourceRange();
5648 // We followed through a reference variable. 'stackE' contains the
5649 // problematic expression but we will warn at the return statement pointing
5650 // at the reference variable. We will later display the "trail" of
5651 // reference variables using notes.
5652 diagLoc = refVars[0]->getLocStart();
5653 diagRange = refVars[0]->getSourceRange();
5656 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
5657 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
5658 << DR->getDecl()->getDeclName() << diagRange;
5659 } else if (isa<BlockExpr>(stackE)) { // local block.
5660 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
5661 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
5662 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
5663 } else { // local temporary.
5664 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
5665 << lhsType->isReferenceType() << diagRange;
5668 // Display the "trail" of reference variables that we followed until we
5669 // found the problematic expression using notes.
5670 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5671 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5672 // If this var binds to another reference var, show the range of the next
5673 // var, otherwise the var binds to the problematic expression, in which case
5674 // show the range of the expression.
5675 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5676 : stackE->getSourceRange();
5677 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5678 << VD->getDeclName() << range;
5682 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5683 /// check if the expression in a return statement evaluates to an address
5684 /// to a location on the stack, a local block, an address of a label, or a
5685 /// reference to local temporary. The recursion is used to traverse the
5686 /// AST of the return expression, with recursion backtracking when we
5687 /// encounter a subexpression that (1) clearly does not lead to one of the
5688 /// above problematic expressions (2) is something we cannot determine leads to
5689 /// a problematic expression based on such local checking.
5691 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
5692 /// the expression that they point to. Such variables are added to the
5693 /// 'refVars' vector so that we know what the reference variable "trail" was.
5695 /// EvalAddr processes expressions that are pointers that are used as
5696 /// references (and not L-values). EvalVal handles all other values.
5697 /// At the base case of the recursion is a check for the above problematic
5700 /// This implementation handles:
5702 /// * pointer-to-pointer casts
5703 /// * implicit conversions from array references to pointers
5704 /// * taking the address of fields
5705 /// * arbitrary interplay between "&" and "*" operators
5706 /// * pointer arithmetic from an address of a stack variable
5707 /// * taking the address of an array element where the array is on the stack
5708 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5710 if (E->isTypeDependent())
5713 // We should only be called for evaluating pointer expressions.
5714 assert((E->getType()->isAnyPointerType() ||
5715 E->getType()->isBlockPointerType() ||
5716 E->getType()->isObjCQualifiedIdType()) &&
5717 "EvalAddr only works on pointers");
5719 E = E->IgnoreParens();
5721 // Our "symbolic interpreter" is just a dispatch off the currently
5722 // viewed AST node. We then recursively traverse the AST by calling
5723 // EvalAddr and EvalVal appropriately.
5724 switch (E->getStmtClass()) {
5725 case Stmt::DeclRefExprClass: {
5726 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5728 // If we leave the immediate function, the lifetime isn't about to end.
5729 if (DR->refersToEnclosingVariableOrCapture())
5732 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5733 // If this is a reference variable, follow through to the expression that
5735 if (V->hasLocalStorage() &&
5736 V->getType()->isReferenceType() && V->hasInit()) {
5737 // Add the reference variable to the "trail".
5738 refVars.push_back(DR);
5739 return EvalAddr(V->getInit(), refVars, ParentDecl);
5745 case Stmt::UnaryOperatorClass: {
5746 // The only unary operator that make sense to handle here
5747 // is AddrOf. All others don't make sense as pointers.
5748 UnaryOperator *U = cast<UnaryOperator>(E);
5750 if (U->getOpcode() == UO_AddrOf)
5751 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
5756 case Stmt::BinaryOperatorClass: {
5757 // Handle pointer arithmetic. All other binary operators are not valid
5759 BinaryOperator *B = cast<BinaryOperator>(E);
5760 BinaryOperatorKind op = B->getOpcode();
5762 if (op != BO_Add && op != BO_Sub)
5765 Expr *Base = B->getLHS();
5767 // Determine which argument is the real pointer base. It could be
5768 // the RHS argument instead of the LHS.
5769 if (!Base->getType()->isPointerType()) Base = B->getRHS();
5771 assert (Base->getType()->isPointerType());
5772 return EvalAddr(Base, refVars, ParentDecl);
5775 // For conditional operators we need to see if either the LHS or RHS are
5776 // valid DeclRefExpr*s. If one of them is valid, we return it.
5777 case Stmt::ConditionalOperatorClass: {
5778 ConditionalOperator *C = cast<ConditionalOperator>(E);
5780 // Handle the GNU extension for missing LHS.
5781 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5782 if (Expr *LHSExpr = C->getLHS()) {
5783 // In C++, we can have a throw-expression, which has 'void' type.
5784 if (!LHSExpr->getType()->isVoidType())
5785 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
5789 // In C++, we can have a throw-expression, which has 'void' type.
5790 if (C->getRHS()->getType()->isVoidType())
5793 return EvalAddr(C->getRHS(), refVars, ParentDecl);
5796 case Stmt::BlockExprClass:
5797 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
5798 return E; // local block.
5801 case Stmt::AddrLabelExprClass:
5802 return E; // address of label.
5804 case Stmt::ExprWithCleanupsClass:
5805 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5808 // For casts, we need to handle conversions from arrays to
5809 // pointer values, and pointer-to-pointer conversions.
5810 case Stmt::ImplicitCastExprClass:
5811 case Stmt::CStyleCastExprClass:
5812 case Stmt::CXXFunctionalCastExprClass:
5813 case Stmt::ObjCBridgedCastExprClass:
5814 case Stmt::CXXStaticCastExprClass:
5815 case Stmt::CXXDynamicCastExprClass:
5816 case Stmt::CXXConstCastExprClass:
5817 case Stmt::CXXReinterpretCastExprClass: {
5818 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5819 switch (cast<CastExpr>(E)->getCastKind()) {
5820 case CK_LValueToRValue:
5822 case CK_BaseToDerived:
5823 case CK_DerivedToBase:
5824 case CK_UncheckedDerivedToBase:
5826 case CK_CPointerToObjCPointerCast:
5827 case CK_BlockPointerToObjCPointerCast:
5828 case CK_AnyPointerToBlockPointerCast:
5829 return EvalAddr(SubExpr, refVars, ParentDecl);
5831 case CK_ArrayToPointerDecay:
5832 return EvalVal(SubExpr, refVars, ParentDecl);
5835 if (SubExpr->getType()->isAnyPointerType() ||
5836 SubExpr->getType()->isBlockPointerType() ||
5837 SubExpr->getType()->isObjCQualifiedIdType())
5838 return EvalAddr(SubExpr, refVars, ParentDecl);
5847 case Stmt::MaterializeTemporaryExprClass:
5848 if (Expr *Result = EvalAddr(
5849 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5850 refVars, ParentDecl))
5855 // Everything else: we simply don't reason about them.
5862 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
5863 /// See the comments for EvalAddr for more details.
5864 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5867 // We should only be called for evaluating non-pointer expressions, or
5868 // expressions with a pointer type that are not used as references but instead
5869 // are l-values (e.g., DeclRefExpr with a pointer type).
5871 // Our "symbolic interpreter" is just a dispatch off the currently
5872 // viewed AST node. We then recursively traverse the AST by calling
5873 // EvalAddr and EvalVal appropriately.
5875 E = E->IgnoreParens();
5876 switch (E->getStmtClass()) {
5877 case Stmt::ImplicitCastExprClass: {
5878 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
5879 if (IE->getValueKind() == VK_LValue) {
5880 E = IE->getSubExpr();
5886 case Stmt::ExprWithCleanupsClass:
5887 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
5889 case Stmt::DeclRefExprClass: {
5890 // When we hit a DeclRefExpr we are looking at code that refers to a
5891 // variable's name. If it's not a reference variable we check if it has
5892 // local storage within the function, and if so, return the expression.
5893 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5895 // If we leave the immediate function, the lifetime isn't about to end.
5896 if (DR->refersToEnclosingVariableOrCapture())
5899 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5900 // Check if it refers to itself, e.g. "int& i = i;".
5901 if (V == ParentDecl)
5904 if (V->hasLocalStorage()) {
5905 if (!V->getType()->isReferenceType())
5908 // Reference variable, follow through to the expression that
5911 // Add the reference variable to the "trail".
5912 refVars.push_back(DR);
5913 return EvalVal(V->getInit(), refVars, V);
5921 case Stmt::UnaryOperatorClass: {
5922 // The only unary operator that make sense to handle here
5923 // is Deref. All others don't resolve to a "name." This includes
5924 // handling all sorts of rvalues passed to a unary operator.
5925 UnaryOperator *U = cast<UnaryOperator>(E);
5927 if (U->getOpcode() == UO_Deref)
5928 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
5933 case Stmt::ArraySubscriptExprClass: {
5934 // Array subscripts are potential references to data on the stack. We
5935 // retrieve the DeclRefExpr* for the array variable if it indeed
5936 // has local storage.
5937 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
5940 case Stmt::OMPArraySectionExprClass: {
5941 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
5945 case Stmt::ConditionalOperatorClass: {
5946 // For conditional operators we need to see if either the LHS or RHS are
5947 // non-NULL Expr's. If one is non-NULL, we return it.
5948 ConditionalOperator *C = cast<ConditionalOperator>(E);
5950 // Handle the GNU extension for missing LHS.
5951 if (Expr *LHSExpr = C->getLHS()) {
5952 // In C++, we can have a throw-expression, which has 'void' type.
5953 if (!LHSExpr->getType()->isVoidType())
5954 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5958 // In C++, we can have a throw-expression, which has 'void' type.
5959 if (C->getRHS()->getType()->isVoidType())
5962 return EvalVal(C->getRHS(), refVars, ParentDecl);
5965 // Accesses to members are potential references to data on the stack.
5966 case Stmt::MemberExprClass: {
5967 MemberExpr *M = cast<MemberExpr>(E);
5969 // Check for indirect access. We only want direct field accesses.
5973 // Check whether the member type is itself a reference, in which case
5974 // we're not going to refer to the member, but to what the member refers to.
5975 if (M->getMemberDecl()->getType()->isReferenceType())
5978 return EvalVal(M->getBase(), refVars, ParentDecl);
5981 case Stmt::MaterializeTemporaryExprClass:
5982 if (Expr *Result = EvalVal(
5983 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5984 refVars, ParentDecl))
5990 // Check that we don't return or take the address of a reference to a
5991 // temporary. This is only useful in C++.
5992 if (!E->isTypeDependent() && E->isRValue())
5995 // Everything else: we simply don't reason about them.
6002 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6003 SourceLocation ReturnLoc,
6005 const AttrVec *Attrs,
6006 const FunctionDecl *FD) {
6007 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6009 // Check if the return value is null but should not be.
6010 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6011 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
6012 CheckNonNullExpr(*this, RetValExp))
6013 Diag(ReturnLoc, diag::warn_null_ret)
6014 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
6016 // C++11 [basic.stc.dynamic.allocation]p4:
6017 // If an allocation function declared with a non-throwing
6018 // exception-specification fails to allocate storage, it shall return
6019 // a null pointer. Any other allocation function that fails to allocate
6020 // storage shall indicate failure only by throwing an exception [...]
6022 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6023 if (Op == OO_New || Op == OO_Array_New) {
6024 const FunctionProtoType *Proto
6025 = FD->getType()->castAs<FunctionProtoType>();
6026 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6027 CheckNonNullExpr(*this, RetValExp))
6028 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6029 << FD << getLangOpts().CPlusPlus11;
6034 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6036 /// Check for comparisons of floating point operands using != and ==.
6037 /// Issue a warning if these are no self-comparisons, as they are not likely
6038 /// to do what the programmer intended.
6039 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
6040 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6041 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
6043 // Special case: check for x == x (which is OK).
6044 // Do not emit warnings for such cases.
6045 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6046 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6047 if (DRL->getDecl() == DRR->getDecl())
6051 // Special case: check for comparisons against literals that can be exactly
6052 // represented by APFloat. In such cases, do not emit a warning. This
6053 // is a heuristic: often comparison against such literals are used to
6054 // detect if a value in a variable has not changed. This clearly can
6055 // lead to false negatives.
6056 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6060 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6064 // Check for comparisons with builtin types.
6065 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
6066 if (CL->getBuiltinCallee())
6069 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
6070 if (CR->getBuiltinCallee())
6073 // Emit the diagnostic.
6074 Diag(Loc, diag::warn_floatingpoint_eq)
6075 << LHS->getSourceRange() << RHS->getSourceRange();
6078 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6079 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
6083 /// Structure recording the 'active' range of an integer-valued
6086 /// The number of bits active in the int.
6089 /// True if the int is known not to have negative values.
6092 IntRange(unsigned Width, bool NonNegative)
6093 : Width(Width), NonNegative(NonNegative)
6096 /// Returns the range of the bool type.
6097 static IntRange forBoolType() {
6098 return IntRange(1, true);
6101 /// Returns the range of an opaque value of the given integral type.
6102 static IntRange forValueOfType(ASTContext &C, QualType T) {
6103 return forValueOfCanonicalType(C,
6104 T->getCanonicalTypeInternal().getTypePtr());
6107 /// Returns the range of an opaque value of a canonical integral type.
6108 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
6109 assert(T->isCanonicalUnqualified());
6111 if (const VectorType *VT = dyn_cast<VectorType>(T))
6112 T = VT->getElementType().getTypePtr();
6113 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6114 T = CT->getElementType().getTypePtr();
6115 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6116 T = AT->getValueType().getTypePtr();
6118 // For enum types, use the known bit width of the enumerators.
6119 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
6120 EnumDecl *Enum = ET->getDecl();
6121 if (!Enum->isCompleteDefinition())
6122 return IntRange(C.getIntWidth(QualType(T, 0)), false);
6124 unsigned NumPositive = Enum->getNumPositiveBits();
6125 unsigned NumNegative = Enum->getNumNegativeBits();
6127 if (NumNegative == 0)
6128 return IntRange(NumPositive, true/*NonNegative*/);
6130 return IntRange(std::max(NumPositive + 1, NumNegative),
6131 false/*NonNegative*/);
6134 const BuiltinType *BT = cast<BuiltinType>(T);
6135 assert(BT->isInteger());
6137 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6140 /// Returns the "target" range of a canonical integral type, i.e.
6141 /// the range of values expressible in the type.
6143 /// This matches forValueOfCanonicalType except that enums have the
6144 /// full range of their type, not the range of their enumerators.
6145 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6146 assert(T->isCanonicalUnqualified());
6148 if (const VectorType *VT = dyn_cast<VectorType>(T))
6149 T = VT->getElementType().getTypePtr();
6150 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6151 T = CT->getElementType().getTypePtr();
6152 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6153 T = AT->getValueType().getTypePtr();
6154 if (const EnumType *ET = dyn_cast<EnumType>(T))
6155 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
6157 const BuiltinType *BT = cast<BuiltinType>(T);
6158 assert(BT->isInteger());
6160 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6163 /// Returns the supremum of two ranges: i.e. their conservative merge.
6164 static IntRange join(IntRange L, IntRange R) {
6165 return IntRange(std::max(L.Width, R.Width),
6166 L.NonNegative && R.NonNegative);
6169 /// Returns the infinum of two ranges: i.e. their aggressive merge.
6170 static IntRange meet(IntRange L, IntRange R) {
6171 return IntRange(std::min(L.Width, R.Width),
6172 L.NonNegative || R.NonNegative);
6176 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
6177 unsigned MaxWidth) {
6178 if (value.isSigned() && value.isNegative())
6179 return IntRange(value.getMinSignedBits(), false);
6181 if (value.getBitWidth() > MaxWidth)
6182 value = value.trunc(MaxWidth);
6184 // isNonNegative() just checks the sign bit without considering
6186 return IntRange(value.getActiveBits(), true);
6189 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6190 unsigned MaxWidth) {
6192 return GetValueRange(C, result.getInt(), MaxWidth);
6194 if (result.isVector()) {
6195 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6196 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6197 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6198 R = IntRange::join(R, El);
6203 if (result.isComplexInt()) {
6204 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6205 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6206 return IntRange::join(R, I);
6209 // This can happen with lossless casts to intptr_t of "based" lvalues.
6210 // Assume it might use arbitrary bits.
6211 // FIXME: The only reason we need to pass the type in here is to get
6212 // the sign right on this one case. It would be nice if APValue
6214 assert(result.isLValue() || result.isAddrLabelDiff());
6215 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
6218 static QualType GetExprType(Expr *E) {
6219 QualType Ty = E->getType();
6220 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6221 Ty = AtomicRHS->getValueType();
6225 /// Pseudo-evaluate the given integer expression, estimating the
6226 /// range of values it might take.
6228 /// \param MaxWidth - the width to which the value will be truncated
6229 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
6230 E = E->IgnoreParens();
6232 // Try a full evaluation first.
6233 Expr::EvalResult result;
6234 if (E->EvaluateAsRValue(result, C))
6235 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
6237 // I think we only want to look through implicit casts here; if the
6238 // user has an explicit widening cast, we should treat the value as
6239 // being of the new, wider type.
6240 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
6241 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
6242 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6244 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
6246 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6247 CE->getCastKind() == CK_BooleanToSignedIntegral;
6249 // Assume that non-integer casts can span the full range of the type.
6251 return OutputTypeRange;
6254 = GetExprRange(C, CE->getSubExpr(),
6255 std::min(MaxWidth, OutputTypeRange.Width));
6257 // Bail out if the subexpr's range is as wide as the cast type.
6258 if (SubRange.Width >= OutputTypeRange.Width)
6259 return OutputTypeRange;
6261 // Otherwise, we take the smaller width, and we're non-negative if
6262 // either the output type or the subexpr is.
6263 return IntRange(SubRange.Width,
6264 SubRange.NonNegative || OutputTypeRange.NonNegative);
6267 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6268 // If we can fold the condition, just take that operand.
6270 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6271 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6272 : CO->getFalseExpr(),
6275 // Otherwise, conservatively merge.
6276 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6277 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6278 return IntRange::join(L, R);
6281 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6282 switch (BO->getOpcode()) {
6284 // Boolean-valued operations are single-bit and positive.
6293 return IntRange::forBoolType();
6295 // The type of the assignments is the type of the LHS, so the RHS
6296 // is not necessarily the same type.
6305 return IntRange::forValueOfType(C, GetExprType(E));
6307 // Simple assignments just pass through the RHS, which will have
6308 // been coerced to the LHS type.
6311 return GetExprRange(C, BO->getRHS(), MaxWidth);
6313 // Operations with opaque sources are black-listed.
6316 return IntRange::forValueOfType(C, GetExprType(E));
6318 // Bitwise-and uses the *infinum* of the two source ranges.
6321 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6322 GetExprRange(C, BO->getRHS(), MaxWidth));
6324 // Left shift gets black-listed based on a judgement call.
6326 // ...except that we want to treat '1 << (blah)' as logically
6327 // positive. It's an important idiom.
6328 if (IntegerLiteral *I
6329 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6330 if (I->getValue() == 1) {
6331 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
6332 return IntRange(R.Width, /*NonNegative*/ true);
6338 return IntRange::forValueOfType(C, GetExprType(E));
6340 // Right shift by a constant can narrow its left argument.
6342 case BO_ShrAssign: {
6343 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6345 // If the shift amount is a positive constant, drop the width by
6348 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6349 shift.isNonNegative()) {
6350 unsigned zext = shift.getZExtValue();
6351 if (zext >= L.Width)
6352 L.Width = (L.NonNegative ? 0 : 1);
6360 // Comma acts as its right operand.
6362 return GetExprRange(C, BO->getRHS(), MaxWidth);
6364 // Black-list pointer subtractions.
6366 if (BO->getLHS()->getType()->isPointerType())
6367 return IntRange::forValueOfType(C, GetExprType(E));
6370 // The width of a division result is mostly determined by the size
6373 // Don't 'pre-truncate' the operands.
6374 unsigned opWidth = C.getIntWidth(GetExprType(E));
6375 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6377 // If the divisor is constant, use that.
6378 llvm::APSInt divisor;
6379 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6380 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6381 if (log2 >= L.Width)
6382 L.Width = (L.NonNegative ? 0 : 1);
6384 L.Width = std::min(L.Width - log2, MaxWidth);
6388 // Otherwise, just use the LHS's width.
6389 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6390 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6393 // The result of a remainder can't be larger than the result of
6396 // Don't 'pre-truncate' the operands.
6397 unsigned opWidth = C.getIntWidth(GetExprType(E));
6398 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6399 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6401 IntRange meet = IntRange::meet(L, R);
6402 meet.Width = std::min(meet.Width, MaxWidth);
6406 // The default behavior is okay for these.
6414 // The default case is to treat the operation as if it were closed
6415 // on the narrowest type that encompasses both operands.
6416 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6417 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6418 return IntRange::join(L, R);
6421 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6422 switch (UO->getOpcode()) {
6423 // Boolean-valued operations are white-listed.
6425 return IntRange::forBoolType();
6427 // Operations with opaque sources are black-listed.
6429 case UO_AddrOf: // should be impossible
6430 return IntRange::forValueOfType(C, GetExprType(E));
6433 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6437 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6438 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6440 if (FieldDecl *BitField = E->getSourceBitField())
6441 return IntRange(BitField->getBitWidthValue(C),
6442 BitField->getType()->isUnsignedIntegerOrEnumerationType());
6444 return IntRange::forValueOfType(C, GetExprType(E));
6447 static IntRange GetExprRange(ASTContext &C, Expr *E) {
6448 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
6451 /// Checks whether the given value, which currently has the given
6452 /// source semantics, has the same value when coerced through the
6453 /// target semantics.
6454 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6455 const llvm::fltSemantics &Src,
6456 const llvm::fltSemantics &Tgt) {
6457 llvm::APFloat truncated = value;
6460 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6461 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6463 return truncated.bitwiseIsEqual(value);
6466 /// Checks whether the given value, which currently has the given
6467 /// source semantics, has the same value when coerced through the
6468 /// target semantics.
6470 /// The value might be a vector of floats (or a complex number).
6471 static bool IsSameFloatAfterCast(const APValue &value,
6472 const llvm::fltSemantics &Src,
6473 const llvm::fltSemantics &Tgt) {
6474 if (value.isFloat())
6475 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6477 if (value.isVector()) {
6478 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6479 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6484 assert(value.isComplexFloat());
6485 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6486 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6489 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
6491 static bool IsZero(Sema &S, Expr *E) {
6492 // Suppress cases where we are comparing against an enum constant.
6493 if (const DeclRefExpr *DR =
6494 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6495 if (isa<EnumConstantDecl>(DR->getDecl()))
6498 // Suppress cases where the '0' value is expanded from a macro.
6499 if (E->getLocStart().isMacroID())
6503 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6506 static bool HasEnumType(Expr *E) {
6507 // Strip off implicit integral promotions.
6508 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6509 if (ICE->getCastKind() != CK_IntegralCast &&
6510 ICE->getCastKind() != CK_NoOp)
6512 E = ICE->getSubExpr();
6515 return E->getType()->isEnumeralType();
6518 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
6519 // Disable warning in template instantiations.
6520 if (!S.ActiveTemplateInstantiations.empty())
6523 BinaryOperatorKind op = E->getOpcode();
6524 if (E->isValueDependent())
6527 if (op == BO_LT && IsZero(S, E->getRHS())) {
6528 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
6529 << "< 0" << "false" << HasEnumType(E->getLHS())
6530 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6531 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
6532 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
6533 << ">= 0" << "true" << HasEnumType(E->getLHS())
6534 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6535 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
6536 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
6537 << "0 >" << "false" << HasEnumType(E->getRHS())
6538 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6539 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
6540 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
6541 << "0 <=" << "true" << HasEnumType(E->getRHS())
6542 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6546 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
6547 Expr *Constant, Expr *Other,
6550 // Disable warning in template instantiations.
6551 if (!S.ActiveTemplateInstantiations.empty())
6554 // TODO: Investigate using GetExprRange() to get tighter bounds
6555 // on the bit ranges.
6556 QualType OtherT = Other->getType();
6557 if (const auto *AT = OtherT->getAs<AtomicType>())
6558 OtherT = AT->getValueType();
6559 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6560 unsigned OtherWidth = OtherRange.Width;
6562 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6564 // 0 values are handled later by CheckTrivialUnsignedComparison().
6565 if ((Value == 0) && (!OtherIsBooleanType))
6568 BinaryOperatorKind op = E->getOpcode();
6571 // Used for diagnostic printout.
6573 LiteralConstant = 0,
6576 } LiteralOrBoolConstant = LiteralConstant;
6578 if (!OtherIsBooleanType) {
6579 QualType ConstantT = Constant->getType();
6580 QualType CommonT = E->getLHS()->getType();
6582 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6584 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6585 "comparison with non-integer type");
6587 bool ConstantSigned = ConstantT->isSignedIntegerType();
6588 bool CommonSigned = CommonT->isSignedIntegerType();
6590 bool EqualityOnly = false;
6593 // The common type is signed, therefore no signed to unsigned conversion.
6594 if (!OtherRange.NonNegative) {
6595 // Check that the constant is representable in type OtherT.
6596 if (ConstantSigned) {
6597 if (OtherWidth >= Value.getMinSignedBits())
6599 } else { // !ConstantSigned
6600 if (OtherWidth >= Value.getActiveBits() + 1)
6603 } else { // !OtherSigned
6604 // Check that the constant is representable in type OtherT.
6605 // Negative values are out of range.
6606 if (ConstantSigned) {
6607 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6609 } else { // !ConstantSigned
6610 if (OtherWidth >= Value.getActiveBits())
6614 } else { // !CommonSigned
6615 if (OtherRange.NonNegative) {
6616 if (OtherWidth >= Value.getActiveBits())
6618 } else { // OtherSigned
6619 assert(!ConstantSigned &&
6620 "Two signed types converted to unsigned types.");
6621 // Check to see if the constant is representable in OtherT.
6622 if (OtherWidth > Value.getActiveBits())
6624 // Check to see if the constant is equivalent to a negative value
6626 if (S.Context.getIntWidth(ConstantT) ==
6627 S.Context.getIntWidth(CommonT) &&
6628 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6630 // The constant value rests between values that OtherT can represent
6631 // after conversion. Relational comparison still works, but equality
6632 // comparisons will be tautological.
6633 EqualityOnly = true;
6637 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6639 if (op == BO_EQ || op == BO_NE) {
6640 IsTrue = op == BO_NE;
6641 } else if (EqualityOnly) {
6643 } else if (RhsConstant) {
6644 if (op == BO_GT || op == BO_GE)
6645 IsTrue = !PositiveConstant;
6646 else // op == BO_LT || op == BO_LE
6647 IsTrue = PositiveConstant;
6649 if (op == BO_LT || op == BO_LE)
6650 IsTrue = !PositiveConstant;
6651 else // op == BO_GT || op == BO_GE
6652 IsTrue = PositiveConstant;
6655 // Other isKnownToHaveBooleanValue
6656 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6657 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6658 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6660 static const struct LinkedConditions {
6661 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6662 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6663 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6664 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6665 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6666 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6669 // Constant on LHS. | Constant on RHS. |
6670 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6671 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6672 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6673 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6674 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6675 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6676 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6679 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6681 enum ConstantValue ConstVal = Zero;
6682 if (Value.isUnsigned() || Value.isNonNegative()) {
6684 LiteralOrBoolConstant =
6685 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6687 } else if (Value == 1) {
6688 LiteralOrBoolConstant =
6689 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6692 LiteralOrBoolConstant = LiteralConstant;
6699 CompareBoolWithConstantResult CmpRes;
6703 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6706 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6709 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6712 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6715 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6718 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6725 if (CmpRes == AFals) {
6727 } else if (CmpRes == ATrue) {
6734 // If this is a comparison to an enum constant, include that
6735 // constant in the diagnostic.
6736 const EnumConstantDecl *ED = nullptr;
6737 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6738 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6740 SmallString<64> PrettySourceValue;
6741 llvm::raw_svector_ostream OS(PrettySourceValue);
6743 OS << '\'' << *ED << "' (" << Value << ")";
6747 S.DiagRuntimeBehavior(
6748 E->getOperatorLoc(), E,
6749 S.PDiag(diag::warn_out_of_range_compare)
6750 << OS.str() << LiteralOrBoolConstant
6751 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6752 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
6755 /// Analyze the operands of the given comparison. Implements the
6756 /// fallback case from AnalyzeComparison.
6757 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
6758 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6759 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6762 /// \brief Implements -Wsign-compare.
6764 /// \param E the binary operator to check for warnings
6765 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
6766 // The type the comparison is being performed in.
6767 QualType T = E->getLHS()->getType();
6769 // Only analyze comparison operators where both sides have been converted to
6771 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6772 return AnalyzeImpConvsInComparison(S, E);
6774 // Don't analyze value-dependent comparisons directly.
6775 if (E->isValueDependent())
6776 return AnalyzeImpConvsInComparison(S, E);
6778 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6779 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
6781 bool IsComparisonConstant = false;
6783 // Check whether an integer constant comparison results in a value
6784 // of 'true' or 'false'.
6785 if (T->isIntegralType(S.Context)) {
6786 llvm::APSInt RHSValue;
6787 bool IsRHSIntegralLiteral =
6788 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6789 llvm::APSInt LHSValue;
6790 bool IsLHSIntegralLiteral =
6791 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6792 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6793 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6794 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6795 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6797 IsComparisonConstant =
6798 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
6799 } else if (!T->hasUnsignedIntegerRepresentation())
6800 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
6802 // We don't do anything special if this isn't an unsigned integral
6803 // comparison: we're only interested in integral comparisons, and
6804 // signed comparisons only happen in cases we don't care to warn about.
6806 // We also don't care about value-dependent expressions or expressions
6807 // whose result is a constant.
6808 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
6809 return AnalyzeImpConvsInComparison(S, E);
6811 // Check to see if one of the (unmodified) operands is of different
6813 Expr *signedOperand, *unsignedOperand;
6814 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6815 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
6816 "unsigned comparison between two signed integer expressions?");
6817 signedOperand = LHS;
6818 unsignedOperand = RHS;
6819 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6820 signedOperand = RHS;
6821 unsignedOperand = LHS;
6823 CheckTrivialUnsignedComparison(S, E);
6824 return AnalyzeImpConvsInComparison(S, E);
6827 // Otherwise, calculate the effective range of the signed operand.
6828 IntRange signedRange = GetExprRange(S.Context, signedOperand);
6830 // Go ahead and analyze implicit conversions in the operands. Note
6831 // that we skip the implicit conversions on both sides.
6832 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6833 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
6835 // If the signed range is non-negative, -Wsign-compare won't fire,
6836 // but we should still check for comparisons which are always true
6838 if (signedRange.NonNegative)
6839 return CheckTrivialUnsignedComparison(S, E);
6841 // For (in)equality comparisons, if the unsigned operand is a
6842 // constant which cannot collide with a overflowed signed operand,
6843 // then reinterpreting the signed operand as unsigned will not
6844 // change the result of the comparison.
6845 if (E->isEqualityOp()) {
6846 unsigned comparisonWidth = S.Context.getIntWidth(T);
6847 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
6849 // We should never be unable to prove that the unsigned operand is
6851 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6853 if (unsignedRange.Width < comparisonWidth)
6857 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6858 S.PDiag(diag::warn_mixed_sign_comparison)
6859 << LHS->getType() << RHS->getType()
6860 << LHS->getSourceRange() << RHS->getSourceRange());
6863 /// Analyzes an attempt to assign the given value to a bitfield.
6865 /// Returns true if there was something fishy about the attempt.
6866 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6867 SourceLocation InitLoc) {
6868 assert(Bitfield->isBitField());
6869 if (Bitfield->isInvalidDecl())
6872 // White-list bool bitfields.
6873 if (Bitfield->getType()->isBooleanType())
6876 // Ignore value- or type-dependent expressions.
6877 if (Bitfield->getBitWidth()->isValueDependent() ||
6878 Bitfield->getBitWidth()->isTypeDependent() ||
6879 Init->isValueDependent() ||
6880 Init->isTypeDependent())
6883 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6886 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
6889 unsigned OriginalWidth = Value.getBitWidth();
6890 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
6892 if (OriginalWidth <= FieldWidth)
6895 // Compute the value which the bitfield will contain.
6896 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
6897 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
6899 // Check whether the stored value is equal to the original value.
6900 TruncatedValue = TruncatedValue.extend(OriginalWidth);
6901 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
6904 // Special-case bitfields of width 1: booleans are naturally 0/1, and
6905 // therefore don't strictly fit into a signed bitfield of width 1.
6906 if (FieldWidth == 1 && Value == 1)
6909 std::string PrettyValue = Value.toString(10);
6910 std::string PrettyTrunc = TruncatedValue.toString(10);
6912 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6913 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6914 << Init->getSourceRange();
6919 /// Analyze the given simple or compound assignment for warning-worthy
6921 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
6922 // Just recurse on the LHS.
6923 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6925 // We want to recurse on the RHS as normal unless we're assigning to
6927 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
6928 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
6929 E->getOperatorLoc())) {
6930 // Recurse, ignoring any implicit conversions on the RHS.
6931 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6932 E->getOperatorLoc());
6936 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6939 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
6940 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
6941 SourceLocation CContext, unsigned diag,
6942 bool pruneControlFlow = false) {
6943 if (pruneControlFlow) {
6944 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6946 << SourceType << T << E->getSourceRange()
6947 << SourceRange(CContext));
6950 S.Diag(E->getExprLoc(), diag)
6951 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6954 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
6955 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
6956 SourceLocation CContext, unsigned diag,
6957 bool pruneControlFlow = false) {
6958 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
6961 /// Diagnose an implicit cast from a literal expression. Does not warn when the
6962 /// cast wouldn't lose information.
6963 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6964 SourceLocation CContext) {
6965 // Try to convert the literal exactly to an integer. If we can, don't warn.
6966 bool isExact = false;
6967 const llvm::APFloat &Value = FL->getValue();
6968 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6969 T->hasUnsignedIntegerRepresentation());
6970 if (Value.convertToInteger(IntegerValue,
6971 llvm::APFloat::rmTowardZero, &isExact)
6972 == llvm::APFloat::opOK && isExact)
6975 // FIXME: Force the precision of the source value down so we don't print
6976 // digits which are usually useless (we don't really care here if we
6977 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6978 // would automatically print the shortest representation, but it's a bit
6979 // tricky to implement.
6980 SmallString<16> PrettySourceValue;
6981 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6982 precision = (precision * 59 + 195) / 196;
6983 Value.toString(PrettySourceValue, precision);
6985 SmallString<16> PrettyTargetValue;
6986 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6987 PrettyTargetValue = Value.isZero() ? "false" : "true";
6989 IntegerValue.toString(PrettyTargetValue);
6991 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
6992 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6993 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
6996 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6997 if (!Range.Width) return "0";
6999 llvm::APSInt ValueInRange = Value;
7000 ValueInRange.setIsSigned(!Range.NonNegative);
7001 ValueInRange = ValueInRange.trunc(Range.Width);
7002 return ValueInRange.toString(10);
7005 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
7006 if (!isa<ImplicitCastExpr>(Ex))
7009 Expr *InnerE = Ex->IgnoreParenImpCasts();
7010 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7011 const Type *Source =
7012 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7013 if (Target->isDependentType())
7016 const BuiltinType *FloatCandidateBT =
7017 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7018 const Type *BoolCandidateType = ToBool ? Target : Source;
7020 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7021 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7024 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7025 SourceLocation CC) {
7026 unsigned NumArgs = TheCall->getNumArgs();
7027 for (unsigned i = 0; i < NumArgs; ++i) {
7028 Expr *CurrA = TheCall->getArg(i);
7029 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7032 bool IsSwapped = ((i > 0) &&
7033 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7034 IsSwapped |= ((i < (NumArgs - 1)) &&
7035 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7037 // Warn on this floating-point to bool conversion.
7038 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7039 CurrA->getType(), CC,
7040 diag::warn_impcast_floating_point_to_bool);
7045 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
7046 SourceLocation CC) {
7047 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7051 // Don't warn on functions which have return type nullptr_t.
7052 if (isa<CallExpr>(E))
7055 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7056 const Expr::NullPointerConstantKind NullKind =
7057 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7058 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7061 // Return if target type is a safe conversion.
7062 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7063 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7066 SourceLocation Loc = E->getSourceRange().getBegin();
7068 // __null is usually wrapped in a macro. Go up a macro if that is the case.
7069 if (NullKind == Expr::NPCK_GNUNull) {
7070 if (Loc.isMacroID()) {
7071 StringRef MacroName =
7072 Lexer::getImmediateMacroName(Loc, S.SourceMgr, S.getLangOpts());
7073 if (MacroName == "NULL")
7074 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
7078 // Only warn if the null and context location are in the same macro expansion.
7079 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7082 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7083 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7084 << FixItHint::CreateReplacement(Loc,
7085 S.getFixItZeroLiteralForType(T, Loc));
7088 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7089 ObjCArrayLiteral *ArrayLiteral);
7090 static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7091 ObjCDictionaryLiteral *DictionaryLiteral);
7093 /// Check a single element within a collection literal against the
7094 /// target element type.
7095 static void checkObjCCollectionLiteralElement(Sema &S,
7096 QualType TargetElementType,
7098 unsigned ElementKind) {
7099 // Skip a bitcast to 'id' or qualified 'id'.
7100 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7101 if (ICE->getCastKind() == CK_BitCast &&
7102 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7103 Element = ICE->getSubExpr();
7106 QualType ElementType = Element->getType();
7107 ExprResult ElementResult(Element);
7108 if (ElementType->getAs<ObjCObjectPointerType>() &&
7109 S.CheckSingleAssignmentConstraints(TargetElementType,
7112 != Sema::Compatible) {
7113 S.Diag(Element->getLocStart(),
7114 diag::warn_objc_collection_literal_element)
7115 << ElementType << ElementKind << TargetElementType
7116 << Element->getSourceRange();
7119 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7120 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7121 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7122 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7125 /// Check an Objective-C array literal being converted to the given
7127 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7128 ObjCArrayLiteral *ArrayLiteral) {
7132 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7136 if (TargetObjCPtr->isUnspecialized() ||
7137 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7138 != S.NSArrayDecl->getCanonicalDecl())
7141 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7142 if (TypeArgs.size() != 1)
7145 QualType TargetElementType = TypeArgs[0];
7146 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7147 checkObjCCollectionLiteralElement(S, TargetElementType,
7148 ArrayLiteral->getElement(I),
7153 /// Check an Objective-C dictionary literal being converted to the given
7155 static void checkObjCDictionaryLiteral(
7156 Sema &S, QualType TargetType,
7157 ObjCDictionaryLiteral *DictionaryLiteral) {
7158 if (!S.NSDictionaryDecl)
7161 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7165 if (TargetObjCPtr->isUnspecialized() ||
7166 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7167 != S.NSDictionaryDecl->getCanonicalDecl())
7170 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7171 if (TypeArgs.size() != 2)
7174 QualType TargetKeyType = TypeArgs[0];
7175 QualType TargetObjectType = TypeArgs[1];
7176 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7177 auto Element = DictionaryLiteral->getKeyValueElement(I);
7178 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7179 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7183 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
7184 SourceLocation CC, bool *ICContext = nullptr) {
7185 if (E->isTypeDependent() || E->isValueDependent()) return;
7187 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7188 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7189 if (Source == Target) return;
7190 if (Target->isDependentType()) return;
7192 // If the conversion context location is invalid don't complain. We also
7193 // don't want to emit a warning if the issue occurs from the expansion of
7194 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7195 // delay this check as long as possible. Once we detect we are in that
7196 // scenario, we just return.
7200 // Diagnose implicit casts to bool.
7201 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7202 if (isa<StringLiteral>(E))
7203 // Warn on string literal to bool. Checks for string literals in logical
7204 // and expressions, for instance, assert(0 && "error here"), are
7205 // prevented by a check in AnalyzeImplicitConversions().
7206 return DiagnoseImpCast(S, E, T, CC,
7207 diag::warn_impcast_string_literal_to_bool);
7208 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7209 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7210 // This covers the literal expressions that evaluate to Objective-C
7212 return DiagnoseImpCast(S, E, T, CC,
7213 diag::warn_impcast_objective_c_literal_to_bool);
7215 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7216 // Warn on pointer to bool conversion that is always true.
7217 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7222 // Check implicit casts from Objective-C collection literals to specialized
7223 // collection types, e.g., NSArray<NSString *> *.
7224 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7225 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7226 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7227 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7229 // Strip vector types.
7230 if (isa<VectorType>(Source)) {
7231 if (!isa<VectorType>(Target)) {
7232 if (S.SourceMgr.isInSystemMacro(CC))
7234 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
7237 // If the vector cast is cast between two vectors of the same size, it is
7238 // a bitcast, not a conversion.
7239 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7242 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7243 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7245 if (auto VecTy = dyn_cast<VectorType>(Target))
7246 Target = VecTy->getElementType().getTypePtr();
7248 // Strip complex types.
7249 if (isa<ComplexType>(Source)) {
7250 if (!isa<ComplexType>(Target)) {
7251 if (S.SourceMgr.isInSystemMacro(CC))
7254 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
7257 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7258 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7261 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7262 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7264 // If the source is floating point...
7265 if (SourceBT && SourceBT->isFloatingPoint()) {
7266 // ...and the target is floating point...
7267 if (TargetBT && TargetBT->isFloatingPoint()) {
7268 // ...then warn if we're dropping FP rank.
7270 // Builtin FP kinds are ordered by increasing FP rank.
7271 if (SourceBT->getKind() > TargetBT->getKind()) {
7272 // Don't warn about float constants that are precisely
7273 // representable in the target type.
7274 Expr::EvalResult result;
7275 if (E->EvaluateAsRValue(result, S.Context)) {
7276 // Value might be a float, a float vector, or a float complex.
7277 if (IsSameFloatAfterCast(result.Val,
7278 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7279 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
7283 if (S.SourceMgr.isInSystemMacro(CC))
7286 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
7289 // ... or possibly if we're increasing rank, too
7290 else if (TargetBT->getKind() > SourceBT->getKind()) {
7291 if (S.SourceMgr.isInSystemMacro(CC))
7294 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
7299 // If the target is integral, always warn.
7300 if (TargetBT && TargetBT->isInteger()) {
7301 if (S.SourceMgr.isInSystemMacro(CC))
7304 Expr *InnerE = E->IgnoreParenImpCasts();
7305 // We also want to warn on, e.g., "int i = -1.234"
7306 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7307 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7308 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7310 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7311 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
7313 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7317 // Detect the case where a call result is converted from floating-point to
7318 // to bool, and the final argument to the call is converted from bool, to
7319 // discover this typo:
7321 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
7323 // FIXME: This is an incredibly special case; is there some more general
7324 // way to detect this class of misplaced-parentheses bug?
7325 if (Target->isBooleanType() && isa<CallExpr>(E)) {
7326 // Check last argument of function call to see if it is an
7327 // implicit cast from a type matching the type the result
7328 // is being cast to.
7329 CallExpr *CEx = cast<CallExpr>(E);
7330 if (unsigned NumArgs = CEx->getNumArgs()) {
7331 Expr *LastA = CEx->getArg(NumArgs - 1);
7332 Expr *InnerE = LastA->IgnoreParenImpCasts();
7333 if (isa<ImplicitCastExpr>(LastA) &&
7334 InnerE->getType()->isBooleanType()) {
7335 // Warn on this floating-point to bool conversion
7336 DiagnoseImpCast(S, E, T, CC,
7337 diag::warn_impcast_floating_point_to_bool);
7344 DiagnoseNullConversion(S, E, T, CC);
7346 if (!Source->isIntegerType() || !Target->isIntegerType())
7349 // TODO: remove this early return once the false positives for constant->bool
7350 // in templates, macros, etc, are reduced or removed.
7351 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7354 IntRange SourceRange = GetExprRange(S.Context, E);
7355 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
7357 if (SourceRange.Width > TargetRange.Width) {
7358 // If the source is a constant, use a default-on diagnostic.
7359 // TODO: this should happen for bitfield stores, too.
7360 llvm::APSInt Value(32);
7361 if (E->isIntegerConstantExpr(Value, S.Context)) {
7362 if (S.SourceMgr.isInSystemMacro(CC))
7365 std::string PrettySourceValue = Value.toString(10);
7366 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
7368 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7369 S.PDiag(diag::warn_impcast_integer_precision_constant)
7370 << PrettySourceValue << PrettyTargetValue
7371 << E->getType() << T << E->getSourceRange()
7372 << clang::SourceRange(CC));
7376 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7377 if (S.SourceMgr.isInSystemMacro(CC))
7380 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
7381 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7382 /* pruneControlFlow */ true);
7383 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
7386 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7387 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7388 SourceRange.Width == TargetRange.Width)) {
7390 if (S.SourceMgr.isInSystemMacro(CC))
7393 unsigned DiagID = diag::warn_impcast_integer_sign;
7395 // Traditionally, gcc has warned about this under -Wsign-compare.
7396 // We also want to warn about it in -Wconversion.
7397 // So if -Wconversion is off, use a completely identical diagnostic
7398 // in the sign-compare group.
7399 // The conditional-checking code will
7401 DiagID = diag::warn_impcast_integer_sign_conditional;
7405 return DiagnoseImpCast(S, E, T, CC, DiagID);
7408 // Diagnose conversions between different enumeration types.
7409 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7410 // type, to give us better diagnostics.
7411 QualType SourceType = E->getType();
7412 if (!S.getLangOpts().CPlusPlus) {
7413 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7414 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7415 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7416 SourceType = S.Context.getTypeDeclType(Enum);
7417 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7421 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7422 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
7423 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7424 TargetEnum->getDecl()->hasNameForLinkage() &&
7425 SourceEnum != TargetEnum) {
7426 if (S.SourceMgr.isInSystemMacro(CC))
7429 return DiagnoseImpCast(S, E, SourceType, T, CC,
7430 diag::warn_impcast_different_enum_types);
7436 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7437 SourceLocation CC, QualType T);
7439 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
7440 SourceLocation CC, bool &ICContext) {
7441 E = E->IgnoreParenImpCasts();
7443 if (isa<ConditionalOperator>(E))
7444 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
7446 AnalyzeImplicitConversions(S, E, CC);
7447 if (E->getType() != T)
7448 return CheckImplicitConversion(S, E, T, CC, &ICContext);
7452 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7453 SourceLocation CC, QualType T) {
7454 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
7456 bool Suspicious = false;
7457 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7458 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
7460 // If -Wconversion would have warned about either of the candidates
7461 // for a signedness conversion to the context type...
7462 if (!Suspicious) return;
7464 // ...but it's currently ignored...
7465 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
7468 // ...then check whether it would have warned about either of the
7469 // candidates for a signedness conversion to the condition type.
7470 if (E->getType() == T) return;
7473 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7474 E->getType(), CC, &Suspicious);
7476 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
7477 E->getType(), CC, &Suspicious);
7480 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7481 /// Input argument E is a logical expression.
7482 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
7483 if (S.getLangOpts().Bool)
7485 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7488 /// AnalyzeImplicitConversions - Find and report any interesting
7489 /// implicit conversions in the given expression. There are a couple
7490 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
7491 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
7492 QualType T = OrigE->getType();
7493 Expr *E = OrigE->IgnoreParenImpCasts();
7495 if (E->isTypeDependent() || E->isValueDependent())
7498 // For conditional operators, we analyze the arguments as if they
7499 // were being fed directly into the output.
7500 if (isa<ConditionalOperator>(E)) {
7501 ConditionalOperator *CO = cast<ConditionalOperator>(E);
7502 CheckConditionalOperator(S, CO, CC, T);
7506 // Check implicit argument conversions for function calls.
7507 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7508 CheckImplicitArgumentConversions(S, Call, CC);
7510 // Go ahead and check any implicit conversions we might have skipped.
7511 // The non-canonical typecheck is just an optimization;
7512 // CheckImplicitConversion will filter out dead implicit conversions.
7513 if (E->getType() != T)
7514 CheckImplicitConversion(S, E, T, CC);
7516 // Now continue drilling into this expression.
7518 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
7519 // The bound subexpressions in a PseudoObjectExpr are not reachable
7520 // as transitive children.
7521 // FIXME: Use a more uniform representation for this.
7522 for (auto *SE : POE->semantics())
7523 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
7524 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
7527 // Skip past explicit casts.
7528 if (isa<ExplicitCastExpr>(E)) {
7529 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
7530 return AnalyzeImplicitConversions(S, E, CC);
7533 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7534 // Do a somewhat different check with comparison operators.
7535 if (BO->isComparisonOp())
7536 return AnalyzeComparison(S, BO);
7538 // And with simple assignments.
7539 if (BO->getOpcode() == BO_Assign)
7540 return AnalyzeAssignment(S, BO);
7543 // These break the otherwise-useful invariant below. Fortunately,
7544 // we don't really need to recurse into them, because any internal
7545 // expressions should have been analyzed already when they were
7546 // built into statements.
7547 if (isa<StmtExpr>(E)) return;
7549 // Don't descend into unevaluated contexts.
7550 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
7552 // Now just recurse over the expression's children.
7553 CC = E->getExprLoc();
7554 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
7555 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
7556 for (Stmt *SubStmt : E->children()) {
7557 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
7561 if (IsLogicalAndOperator &&
7562 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
7563 // Ignore checking string literals that are in logical and operators.
7564 // This is a common pattern for asserts.
7566 AnalyzeImplicitConversions(S, ChildExpr, CC);
7569 if (BO && BO->isLogicalOp()) {
7570 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7571 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
7572 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
7574 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7575 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
7576 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
7579 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7580 if (U->getOpcode() == UO_LNot)
7581 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
7584 } // end anonymous namespace
7586 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7587 // Returns true when emitting a warning about taking the address of a reference.
7588 static bool CheckForReference(Sema &SemaRef, const Expr *E,
7589 PartialDiagnostic PD) {
7590 E = E->IgnoreParenImpCasts();
7592 const FunctionDecl *FD = nullptr;
7594 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7595 if (!DRE->getDecl()->getType()->isReferenceType())
7597 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7598 if (!M->getMemberDecl()->getType()->isReferenceType())
7600 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
7601 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
7603 FD = Call->getDirectCallee();
7608 SemaRef.Diag(E->getExprLoc(), PD);
7610 // If possible, point to location of function.
7612 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7618 // Returns true if the SourceLocation is expanded from any macro body.
7619 // Returns false if the SourceLocation is invalid, is from not in a macro
7620 // expansion, or is from expanded from a top-level macro argument.
7621 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7622 if (Loc.isInvalid())
7625 while (Loc.isMacroID()) {
7626 if (SM.isMacroBodyExpansion(Loc))
7628 Loc = SM.getImmediateMacroCallerLoc(Loc);
7634 /// \brief Diagnose pointers that are always non-null.
7635 /// \param E the expression containing the pointer
7636 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7637 /// compared to a null pointer
7638 /// \param IsEqual True when the comparison is equal to a null pointer
7639 /// \param Range Extra SourceRange to highlight in the diagnostic
7640 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7641 Expr::NullPointerConstantKind NullKind,
7642 bool IsEqual, SourceRange Range) {
7646 // Don't warn inside macros.
7647 if (E->getExprLoc().isMacroID()) {
7648 const SourceManager &SM = getSourceManager();
7649 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7650 IsInAnyMacroBody(SM, Range.getBegin()))
7653 E = E->IgnoreImpCasts();
7655 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7657 if (isa<CXXThisExpr>(E)) {
7658 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7659 : diag::warn_this_bool_conversion;
7660 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7664 bool IsAddressOf = false;
7666 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7667 if (UO->getOpcode() != UO_AddrOf)
7670 E = UO->getSubExpr();
7674 unsigned DiagID = IsCompare
7675 ? diag::warn_address_of_reference_null_compare
7676 : diag::warn_address_of_reference_bool_conversion;
7677 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7679 if (CheckForReference(*this, E, PD)) {
7684 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
7686 llvm::raw_string_ostream S(Str);
7687 E->printPretty(S, nullptr, getPrintingPolicy());
7688 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
7689 : diag::warn_cast_nonnull_to_bool;
7690 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
7691 << E->getSourceRange() << Range << IsEqual;
7694 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
7695 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
7696 if (auto *Callee = Call->getDirectCallee()) {
7697 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
7698 ComplainAboutNonnullParamOrCall(false);
7704 // Expect to find a single Decl. Skip anything more complicated.
7705 ValueDecl *D = nullptr;
7706 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7708 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7709 D = M->getMemberDecl();
7712 // Weak Decls can be null.
7713 if (!D || D->isWeak())
7716 // Check for parameter decl with nonnull attribute
7717 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
7718 if (getCurFunction() &&
7719 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
7720 if (PV->hasAttr<NonNullAttr>()) {
7721 ComplainAboutNonnullParamOrCall(true);
7725 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7726 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
7727 assert(ParamIter != FD->param_end());
7728 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
7730 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7731 if (!NonNull->args_size()) {
7732 ComplainAboutNonnullParamOrCall(true);
7736 for (unsigned ArgNo : NonNull->args()) {
7737 if (ArgNo == ParamNo) {
7738 ComplainAboutNonnullParamOrCall(true);
7747 QualType T = D->getType();
7748 const bool IsArray = T->isArrayType();
7749 const bool IsFunction = T->isFunctionType();
7751 // Address of function is used to silence the function warning.
7752 if (IsAddressOf && IsFunction) {
7757 if (!IsAddressOf && !IsFunction && !IsArray)
7760 // Pretty print the expression for the diagnostic.
7762 llvm::raw_string_ostream S(Str);
7763 E->printPretty(S, nullptr, getPrintingPolicy());
7765 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7766 : diag::warn_impcast_pointer_to_bool;
7773 DiagType = AddressOf;
7774 else if (IsFunction)
7775 DiagType = FunctionPointer;
7777 DiagType = ArrayPointer;
7779 llvm_unreachable("Could not determine diagnostic.");
7780 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7781 << Range << IsEqual;
7786 // Suggest '&' to silence the function warning.
7787 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7788 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7790 // Check to see if '()' fixit should be emitted.
7791 QualType ReturnType;
7792 UnresolvedSet<4> NonTemplateOverloads;
7793 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7794 if (ReturnType.isNull())
7798 // There are two cases here. If there is null constant, the only suggest
7799 // for a pointer return type. If the null is 0, then suggest if the return
7800 // type is a pointer or an integer type.
7801 if (!ReturnType->isPointerType()) {
7802 if (NullKind == Expr::NPCK_ZeroExpression ||
7803 NullKind == Expr::NPCK_ZeroLiteral) {
7804 if (!ReturnType->isIntegerType())
7810 } else { // !IsCompare
7811 // For function to bool, only suggest if the function pointer has bool
7813 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7816 Diag(E->getExprLoc(), diag::note_function_to_function_call)
7817 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
7821 /// Diagnoses "dangerous" implicit conversions within the given
7822 /// expression (which is a full expression). Implements -Wconversion
7823 /// and -Wsign-compare.
7825 /// \param CC the "context" location of the implicit conversion, i.e.
7826 /// the most location of the syntactic entity requiring the implicit
7828 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
7829 // Don't diagnose in unevaluated contexts.
7830 if (isUnevaluatedContext())
7833 // Don't diagnose for value- or type-dependent expressions.
7834 if (E->isTypeDependent() || E->isValueDependent())
7837 // Check for array bounds violations in cases where the check isn't triggered
7838 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7839 // ArraySubscriptExpr is on the RHS of a variable initialization.
7840 CheckArrayAccess(E);
7842 // This is not the right CC for (e.g.) a variable initialization.
7843 AnalyzeImplicitConversions(*this, E, CC);
7846 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7847 /// Input argument E is a logical expression.
7848 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7849 ::CheckBoolLikeConversion(*this, E, CC);
7852 /// Diagnose when expression is an integer constant expression and its evaluation
7853 /// results in integer overflow
7854 void Sema::CheckForIntOverflow (Expr *E) {
7855 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7856 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
7857 else if (auto InitList = dyn_cast<InitListExpr>(E))
7858 for (Expr *E : InitList->inits())
7859 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7860 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
7864 /// \brief Visitor for expressions which looks for unsequenced operations on the
7866 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
7867 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7869 /// \brief A tree of sequenced regions within an expression. Two regions are
7870 /// unsequenced if one is an ancestor or a descendent of the other. When we
7871 /// finish processing an expression with sequencing, such as a comma
7872 /// expression, we fold its tree nodes into its parent, since they are
7873 /// unsequenced with respect to nodes we will visit later.
7874 class SequenceTree {
7876 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7877 unsigned Parent : 31;
7880 SmallVector<Value, 8> Values;
7883 /// \brief A region within an expression which may be sequenced with respect
7884 /// to some other region.
7886 explicit Seq(unsigned N) : Index(N) {}
7888 friend class SequenceTree;
7893 SequenceTree() { Values.push_back(Value(0)); }
7894 Seq root() const { return Seq(0); }
7896 /// \brief Create a new sequence of operations, which is an unsequenced
7897 /// subset of \p Parent. This sequence of operations is sequenced with
7898 /// respect to other children of \p Parent.
7899 Seq allocate(Seq Parent) {
7900 Values.push_back(Value(Parent.Index));
7901 return Seq(Values.size() - 1);
7904 /// \brief Merge a sequence of operations into its parent.
7906 Values[S.Index].Merged = true;
7909 /// \brief Determine whether two operations are unsequenced. This operation
7910 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7911 /// should have been merged into its parent as appropriate.
7912 bool isUnsequenced(Seq Cur, Seq Old) {
7913 unsigned C = representative(Cur.Index);
7914 unsigned Target = representative(Old.Index);
7915 while (C >= Target) {
7918 C = Values[C].Parent;
7924 /// \brief Pick a representative for a sequence.
7925 unsigned representative(unsigned K) {
7926 if (Values[K].Merged)
7927 // Perform path compression as we go.
7928 return Values[K].Parent = representative(Values[K].Parent);
7933 /// An object for which we can track unsequenced uses.
7934 typedef NamedDecl *Object;
7936 /// Different flavors of object usage which we track. We only track the
7937 /// least-sequenced usage of each kind.
7939 /// A read of an object. Multiple unsequenced reads are OK.
7941 /// A modification of an object which is sequenced before the value
7942 /// computation of the expression, such as ++n in C++.
7944 /// A modification of an object which is not sequenced before the value
7945 /// computation of the expression, such as n++.
7948 UK_Count = UK_ModAsSideEffect + 1
7952 Usage() : Use(nullptr), Seq() {}
7954 SequenceTree::Seq Seq;
7958 UsageInfo() : Diagnosed(false) {}
7959 Usage Uses[UK_Count];
7960 /// Have we issued a diagnostic for this variable already?
7963 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7966 /// Sequenced regions within the expression.
7968 /// Declaration modifications and references which we have seen.
7969 UsageInfoMap UsageMap;
7970 /// The region we are currently within.
7971 SequenceTree::Seq Region;
7972 /// Filled in with declarations which were modified as a side-effect
7973 /// (that is, post-increment operations).
7974 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
7975 /// Expressions to check later. We defer checking these to reduce
7977 SmallVectorImpl<Expr *> &WorkList;
7979 /// RAII object wrapping the visitation of a sequenced subexpression of an
7980 /// expression. At the end of this process, the side-effects of the evaluation
7981 /// become sequenced with respect to the value computation of the result, so
7982 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7984 struct SequencedSubexpression {
7985 SequencedSubexpression(SequenceChecker &Self)
7986 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7987 Self.ModAsSideEffect = &ModAsSideEffect;
7989 ~SequencedSubexpression() {
7990 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7992 UsageInfo &U = Self.UsageMap[MI->first];
7993 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7994 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7995 SideEffectUsage = MI->second;
7997 Self.ModAsSideEffect = OldModAsSideEffect;
8000 SequenceChecker &Self;
8001 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8002 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
8005 /// RAII object wrapping the visitation of a subexpression which we might
8006 /// choose to evaluate as a constant. If any subexpression is evaluated and
8007 /// found to be non-constant, this allows us to suppress the evaluation of
8008 /// the outer expression.
8009 class EvaluationTracker {
8011 EvaluationTracker(SequenceChecker &Self)
8012 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8013 Self.EvalTracker = this;
8015 ~EvaluationTracker() {
8016 Self.EvalTracker = Prev;
8018 Prev->EvalOK &= EvalOK;
8021 bool evaluate(const Expr *E, bool &Result) {
8022 if (!EvalOK || E->isValueDependent())
8024 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8029 SequenceChecker &Self;
8030 EvaluationTracker *Prev;
8034 /// \brief Find the object which is produced by the specified expression,
8036 Object getObject(Expr *E, bool Mod) const {
8037 E = E->IgnoreParenCasts();
8038 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8039 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8040 return getObject(UO->getSubExpr(), Mod);
8041 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8042 if (BO->getOpcode() == BO_Comma)
8043 return getObject(BO->getRHS(), Mod);
8044 if (Mod && BO->isAssignmentOp())
8045 return getObject(BO->getLHS(), Mod);
8046 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8047 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8048 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8049 return ME->getMemberDecl();
8050 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8051 // FIXME: If this is a reference, map through to its value.
8052 return DRE->getDecl();
8056 /// \brief Note that an object was modified or used by an expression.
8057 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8058 Usage &U = UI.Uses[UK];
8059 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8060 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8061 ModAsSideEffect->push_back(std::make_pair(O, U));
8066 /// \brief Check whether a modification or use conflicts with a prior usage.
8067 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8072 const Usage &U = UI.Uses[OtherKind];
8073 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8077 Expr *ModOrUse = Ref;
8078 if (OtherKind == UK_Use)
8079 std::swap(Mod, ModOrUse);
8081 SemaRef.Diag(Mod->getExprLoc(),
8082 IsModMod ? diag::warn_unsequenced_mod_mod
8083 : diag::warn_unsequenced_mod_use)
8084 << O << SourceRange(ModOrUse->getExprLoc());
8085 UI.Diagnosed = true;
8088 void notePreUse(Object O, Expr *Use) {
8089 UsageInfo &U = UsageMap[O];
8090 // Uses conflict with other modifications.
8091 checkUsage(O, U, Use, UK_ModAsValue, false);
8093 void notePostUse(Object O, Expr *Use) {
8094 UsageInfo &U = UsageMap[O];
8095 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8096 addUsage(U, O, Use, UK_Use);
8099 void notePreMod(Object O, Expr *Mod) {
8100 UsageInfo &U = UsageMap[O];
8101 // Modifications conflict with other modifications and with uses.
8102 checkUsage(O, U, Mod, UK_ModAsValue, true);
8103 checkUsage(O, U, Mod, UK_Use, false);
8105 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8106 UsageInfo &U = UsageMap[O];
8107 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8108 addUsage(U, O, Use, UK);
8112 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
8113 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8114 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
8118 void VisitStmt(Stmt *S) {
8119 // Skip all statements which aren't expressions for now.
8122 void VisitExpr(Expr *E) {
8123 // By default, just recurse to evaluated subexpressions.
8127 void VisitCastExpr(CastExpr *E) {
8128 Object O = Object();
8129 if (E->getCastKind() == CK_LValueToRValue)
8130 O = getObject(E->getSubExpr(), false);
8139 void VisitBinComma(BinaryOperator *BO) {
8140 // C++11 [expr.comma]p1:
8141 // Every value computation and side effect associated with the left
8142 // expression is sequenced before every value computation and side
8143 // effect associated with the right expression.
8144 SequenceTree::Seq LHS = Tree.allocate(Region);
8145 SequenceTree::Seq RHS = Tree.allocate(Region);
8146 SequenceTree::Seq OldRegion = Region;
8149 SequencedSubexpression SeqLHS(*this);
8151 Visit(BO->getLHS());
8155 Visit(BO->getRHS());
8159 // Forget that LHS and RHS are sequenced. They are both unsequenced
8160 // with respect to other stuff.
8165 void VisitBinAssign(BinaryOperator *BO) {
8166 // The modification is sequenced after the value computation of the LHS
8167 // and RHS, so check it before inspecting the operands and update the
8169 Object O = getObject(BO->getLHS(), true);
8171 return VisitExpr(BO);
8175 // C++11 [expr.ass]p7:
8176 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8179 // Therefore, for a compound assignment operator, O is considered used
8180 // everywhere except within the evaluation of E1 itself.
8181 if (isa<CompoundAssignOperator>(BO))
8184 Visit(BO->getLHS());
8186 if (isa<CompoundAssignOperator>(BO))
8189 Visit(BO->getRHS());
8191 // C++11 [expr.ass]p1:
8192 // the assignment is sequenced [...] before the value computation of the
8193 // assignment expression.
8194 // C11 6.5.16/3 has no such rule.
8195 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8196 : UK_ModAsSideEffect);
8198 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8199 VisitBinAssign(CAO);
8202 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8203 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8204 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8205 Object O = getObject(UO->getSubExpr(), true);
8207 return VisitExpr(UO);
8210 Visit(UO->getSubExpr());
8211 // C++11 [expr.pre.incr]p1:
8212 // the expression ++x is equivalent to x+=1
8213 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8214 : UK_ModAsSideEffect);
8217 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8218 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8219 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8220 Object O = getObject(UO->getSubExpr(), true);
8222 return VisitExpr(UO);
8225 Visit(UO->getSubExpr());
8226 notePostMod(O, UO, UK_ModAsSideEffect);
8229 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8230 void VisitBinLOr(BinaryOperator *BO) {
8231 // The side-effects of the LHS of an '&&' are sequenced before the
8232 // value computation of the RHS, and hence before the value computation
8233 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8234 // as if they were unconditionally sequenced.
8235 EvaluationTracker Eval(*this);
8237 SequencedSubexpression Sequenced(*this);
8238 Visit(BO->getLHS());
8242 if (Eval.evaluate(BO->getLHS(), Result)) {
8244 Visit(BO->getRHS());
8246 // Check for unsequenced operations in the RHS, treating it as an
8247 // entirely separate evaluation.
8249 // FIXME: If there are operations in the RHS which are unsequenced
8250 // with respect to operations outside the RHS, and those operations
8251 // are unconditionally evaluated, diagnose them.
8252 WorkList.push_back(BO->getRHS());
8255 void VisitBinLAnd(BinaryOperator *BO) {
8256 EvaluationTracker Eval(*this);
8258 SequencedSubexpression Sequenced(*this);
8259 Visit(BO->getLHS());
8263 if (Eval.evaluate(BO->getLHS(), Result)) {
8265 Visit(BO->getRHS());
8267 WorkList.push_back(BO->getRHS());
8271 // Only visit the condition, unless we can be sure which subexpression will
8273 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
8274 EvaluationTracker Eval(*this);
8276 SequencedSubexpression Sequenced(*this);
8277 Visit(CO->getCond());
8281 if (Eval.evaluate(CO->getCond(), Result))
8282 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
8284 WorkList.push_back(CO->getTrueExpr());
8285 WorkList.push_back(CO->getFalseExpr());
8289 void VisitCallExpr(CallExpr *CE) {
8290 // C++11 [intro.execution]p15:
8291 // When calling a function [...], every value computation and side effect
8292 // associated with any argument expression, or with the postfix expression
8293 // designating the called function, is sequenced before execution of every
8294 // expression or statement in the body of the function [and thus before
8295 // the value computation of its result].
8296 SequencedSubexpression Sequenced(*this);
8297 Base::VisitCallExpr(CE);
8299 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8302 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
8303 // This is a call, so all subexpressions are sequenced before the result.
8304 SequencedSubexpression Sequenced(*this);
8306 if (!CCE->isListInitialization())
8307 return VisitExpr(CCE);
8309 // In C++11, list initializations are sequenced.
8310 SmallVector<SequenceTree::Seq, 32> Elts;
8311 SequenceTree::Seq Parent = Region;
8312 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8315 Region = Tree.allocate(Parent);
8316 Elts.push_back(Region);
8320 // Forget that the initializers are sequenced.
8322 for (unsigned I = 0; I < Elts.size(); ++I)
8323 Tree.merge(Elts[I]);
8326 void VisitInitListExpr(InitListExpr *ILE) {
8327 if (!SemaRef.getLangOpts().CPlusPlus11)
8328 return VisitExpr(ILE);
8330 // In C++11, list initializations are sequenced.
8331 SmallVector<SequenceTree::Seq, 32> Elts;
8332 SequenceTree::Seq Parent = Region;
8333 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8334 Expr *E = ILE->getInit(I);
8336 Region = Tree.allocate(Parent);
8337 Elts.push_back(Region);
8341 // Forget that the initializers are sequenced.
8343 for (unsigned I = 0; I < Elts.size(); ++I)
8344 Tree.merge(Elts[I]);
8349 void Sema::CheckUnsequencedOperations(Expr *E) {
8350 SmallVector<Expr *, 8> WorkList;
8351 WorkList.push_back(E);
8352 while (!WorkList.empty()) {
8353 Expr *Item = WorkList.pop_back_val();
8354 SequenceChecker(*this, Item, WorkList);
8358 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8360 CheckImplicitConversions(E, CheckLoc);
8361 CheckUnsequencedOperations(E);
8362 if (!IsConstexpr && !E->isValueDependent())
8363 CheckForIntOverflow(E);
8366 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8367 FieldDecl *BitField,
8369 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8372 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8373 SourceLocation Loc) {
8374 if (!PType->isVariablyModifiedType())
8376 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8377 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8380 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8381 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8384 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8385 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8389 const ArrayType *AT = S.Context.getAsArrayType(PType);
8393 if (AT->getSizeModifier() != ArrayType::Star) {
8394 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8398 S.Diag(Loc, diag::err_array_star_in_function_definition);
8401 /// CheckParmsForFunctionDef - Check that the parameters of the given
8402 /// function are appropriate for the definition of a function. This
8403 /// takes care of any checks that cannot be performed on the
8404 /// declaration itself, e.g., that the types of each of the function
8405 /// parameters are complete.
8406 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8407 ParmVarDecl *const *PEnd,
8408 bool CheckParameterNames) {
8409 bool HasInvalidParm = false;
8410 for (; P != PEnd; ++P) {
8411 ParmVarDecl *Param = *P;
8413 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8414 // function declarator that is part of a function definition of
8415 // that function shall not have incomplete type.
8417 // This is also C++ [dcl.fct]p6.
8418 if (!Param->isInvalidDecl() &&
8419 RequireCompleteType(Param->getLocation(), Param->getType(),
8420 diag::err_typecheck_decl_incomplete_type)) {
8421 Param->setInvalidDecl();
8422 HasInvalidParm = true;
8425 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8426 // declaration of each parameter shall include an identifier.
8427 if (CheckParameterNames &&
8428 Param->getIdentifier() == nullptr &&
8429 !Param->isImplicit() &&
8430 !getLangOpts().CPlusPlus)
8431 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
8434 // If the function declarator is not part of a definition of that
8435 // function, parameters may have incomplete type and may use the [*]
8436 // notation in their sequences of declarator specifiers to specify
8437 // variable length array types.
8438 QualType PType = Param->getOriginalType();
8439 // FIXME: This diagnostic should point the '[*]' if source-location
8440 // information is added for it.
8441 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
8443 // MSVC destroys objects passed by value in the callee. Therefore a
8444 // function definition which takes such a parameter must be able to call the
8445 // object's destructor. However, we don't perform any direct access check
8447 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8449 .areArgsDestroyedLeftToRightInCallee()) {
8450 if (!Param->isInvalidDecl()) {
8451 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8452 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8453 if (!ClassDecl->isInvalidDecl() &&
8454 !ClassDecl->hasIrrelevantDestructor() &&
8455 !ClassDecl->isDependentContext()) {
8456 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8457 MarkFunctionReferenced(Param->getLocation(), Destructor);
8458 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8464 // Parameters with the pass_object_size attribute only need to be marked
8465 // constant at function definitions. Because we lack information about
8466 // whether we're on a declaration or definition when we're instantiating the
8467 // attribute, we need to check for constness here.
8468 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
8469 if (!Param->getType().isConstQualified())
8470 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
8471 << Attr->getSpelling() << 1;
8474 return HasInvalidParm;
8477 /// CheckCastAlign - Implements -Wcast-align, which warns when a
8478 /// pointer cast increases the alignment requirements.
8479 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8480 // This is actually a lot of work to potentially be doing on every
8481 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
8482 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
8485 // Ignore dependent types.
8486 if (T->isDependentType() || Op->getType()->isDependentType())
8489 // Require that the destination be a pointer type.
8490 const PointerType *DestPtr = T->getAs<PointerType>();
8491 if (!DestPtr) return;
8493 // If the destination has alignment 1, we're done.
8494 QualType DestPointee = DestPtr->getPointeeType();
8495 if (DestPointee->isIncompleteType()) return;
8496 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8497 if (DestAlign.isOne()) return;
8499 // Require that the source be a pointer type.
8500 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8501 if (!SrcPtr) return;
8502 QualType SrcPointee = SrcPtr->getPointeeType();
8504 // Whitelist casts from cv void*. We already implicitly
8505 // whitelisted casts to cv void*, since they have alignment 1.
8506 // Also whitelist casts involving incomplete types, which implicitly
8508 if (SrcPointee->isIncompleteType()) return;
8510 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8511 if (SrcAlign >= DestAlign) return;
8513 Diag(TRange.getBegin(), diag::warn_cast_align)
8514 << Op->getType() << T
8515 << static_cast<unsigned>(SrcAlign.getQuantity())
8516 << static_cast<unsigned>(DestAlign.getQuantity())
8517 << TRange << Op->getSourceRange();
8520 static const Type* getElementType(const Expr *BaseExpr) {
8521 const Type* EltType = BaseExpr->getType().getTypePtr();
8522 if (EltType->isAnyPointerType())
8523 return EltType->getPointeeType().getTypePtr();
8524 else if (EltType->isArrayType())
8525 return EltType->getBaseElementTypeUnsafe();
8529 /// \brief Check whether this array fits the idiom of a size-one tail padded
8530 /// array member of a struct.
8532 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
8533 /// commonly used to emulate flexible arrays in C89 code.
8534 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8535 const NamedDecl *ND) {
8536 if (Size != 1 || !ND) return false;
8538 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8539 if (!FD) return false;
8541 // Don't consider sizes resulting from macro expansions or template argument
8542 // substitution to form C89 tail-padded arrays.
8544 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
8546 TypeLoc TL = TInfo->getTypeLoc();
8547 // Look through typedefs.
8548 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8549 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
8550 TInfo = TDL->getTypeSourceInfo();
8553 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8554 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
8555 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8561 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
8562 if (!RD) return false;
8563 if (RD->isUnion()) return false;
8564 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8565 if (!CRD->isStandardLayout()) return false;
8568 // See if this is the last field decl in the record.
8570 while ((D = D->getNextDeclInContext()))
8571 if (isa<FieldDecl>(D))
8576 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
8577 const ArraySubscriptExpr *ASE,
8578 bool AllowOnePastEnd, bool IndexNegated) {
8579 IndexExpr = IndexExpr->IgnoreParenImpCasts();
8580 if (IndexExpr->isValueDependent())
8583 const Type *EffectiveType = getElementType(BaseExpr);
8584 BaseExpr = BaseExpr->IgnoreParenCasts();
8585 const ConstantArrayType *ArrayTy =
8586 Context.getAsConstantArrayType(BaseExpr->getType());
8591 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
8596 const NamedDecl *ND = nullptr;
8597 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8598 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8599 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8600 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8602 if (index.isUnsigned() || !index.isNegative()) {
8603 llvm::APInt size = ArrayTy->getSize();
8604 if (!size.isStrictlyPositive())
8607 const Type* BaseType = getElementType(BaseExpr);
8608 if (BaseType != EffectiveType) {
8609 // Make sure we're comparing apples to apples when comparing index to size
8610 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8611 uint64_t array_typesize = Context.getTypeSize(BaseType);
8612 // Handle ptrarith_typesize being zero, such as when casting to void*
8613 if (!ptrarith_typesize) ptrarith_typesize = 1;
8614 if (ptrarith_typesize != array_typesize) {
8615 // There's a cast to a different size type involved
8616 uint64_t ratio = array_typesize / ptrarith_typesize;
8617 // TODO: Be smarter about handling cases where array_typesize is not a
8618 // multiple of ptrarith_typesize
8619 if (ptrarith_typesize * ratio == array_typesize)
8620 size *= llvm::APInt(size.getBitWidth(), ratio);
8624 if (size.getBitWidth() > index.getBitWidth())
8625 index = index.zext(size.getBitWidth());
8626 else if (size.getBitWidth() < index.getBitWidth())
8627 size = size.zext(index.getBitWidth());
8629 // For array subscripting the index must be less than size, but for pointer
8630 // arithmetic also allow the index (offset) to be equal to size since
8631 // computing the next address after the end of the array is legal and
8632 // commonly done e.g. in C++ iterators and range-based for loops.
8633 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
8636 // Also don't warn for arrays of size 1 which are members of some
8637 // structure. These are often used to approximate flexible arrays in C89
8639 if (IsTailPaddedMemberArray(*this, size, ND))
8642 // Suppress the warning if the subscript expression (as identified by the
8643 // ']' location) and the index expression are both from macro expansions
8644 // within a system header.
8646 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8647 ASE->getRBracketLoc());
8648 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8649 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8650 IndexExpr->getLocStart());
8651 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
8656 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
8658 DiagID = diag::warn_array_index_exceeds_bounds;
8660 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8661 PDiag(DiagID) << index.toString(10, true)
8662 << size.toString(10, true)
8663 << (unsigned)size.getLimitedValue(~0U)
8664 << IndexExpr->getSourceRange());
8666 unsigned DiagID = diag::warn_array_index_precedes_bounds;
8668 DiagID = diag::warn_ptr_arith_precedes_bounds;
8669 if (index.isNegative()) index = -index;
8672 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8673 PDiag(DiagID) << index.toString(10, true)
8674 << IndexExpr->getSourceRange());
8678 // Try harder to find a NamedDecl to point at in the note.
8679 while (const ArraySubscriptExpr *ASE =
8680 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8681 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8682 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8683 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8684 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8685 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8689 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8690 PDiag(diag::note_array_index_out_of_bounds)
8691 << ND->getDeclName());
8694 void Sema::CheckArrayAccess(const Expr *expr) {
8695 int AllowOnePastEnd = 0;
8697 expr = expr->IgnoreParenImpCasts();
8698 switch (expr->getStmtClass()) {
8699 case Stmt::ArraySubscriptExprClass: {
8700 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
8701 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
8702 AllowOnePastEnd > 0);
8705 case Stmt::OMPArraySectionExprClass: {
8706 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
8707 if (ASE->getLowerBound())
8708 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
8709 /*ASE=*/nullptr, AllowOnePastEnd > 0);
8712 case Stmt::UnaryOperatorClass: {
8713 // Only unwrap the * and & unary operators
8714 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8715 expr = UO->getSubExpr();
8716 switch (UO->getOpcode()) {
8728 case Stmt::ConditionalOperatorClass: {
8729 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8730 if (const Expr *lhs = cond->getLHS())
8731 CheckArrayAccess(lhs);
8732 if (const Expr *rhs = cond->getRHS())
8733 CheckArrayAccess(rhs);
8742 //===--- CHECK: Objective-C retain cycles ----------------------------------//
8745 struct RetainCycleOwner {
8746 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
8752 void setLocsFrom(Expr *e) {
8753 Loc = e->getExprLoc();
8754 Range = e->getSourceRange();
8759 /// Consider whether capturing the given variable can possibly lead to
8761 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
8762 // In ARC, it's captured strongly iff the variable has __strong
8763 // lifetime. In MRR, it's captured strongly if the variable is
8764 // __block and has an appropriate type.
8765 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8768 owner.Variable = var;
8770 owner.setLocsFrom(ref);
8774 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
8776 e = e->IgnoreParens();
8777 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8778 switch (cast->getCastKind()) {
8780 case CK_LValueBitCast:
8781 case CK_LValueToRValue:
8782 case CK_ARCReclaimReturnedObject:
8783 e = cast->getSubExpr();
8791 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8792 ObjCIvarDecl *ivar = ref->getDecl();
8793 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8796 // Try to find a retain cycle in the base.
8797 if (!findRetainCycleOwner(S, ref->getBase(), owner))
8800 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8801 owner.Indirect = true;
8805 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8806 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8807 if (!var) return false;
8808 return considerVariable(var, ref, owner);
8811 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8812 if (member->isArrow()) return false;
8814 // Don't count this as an indirect ownership.
8815 e = member->getBase();
8819 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8820 // Only pay attention to pseudo-objects on property references.
8821 ObjCPropertyRefExpr *pre
8822 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8824 if (!pre) return false;
8825 if (pre->isImplicitProperty()) return false;
8826 ObjCPropertyDecl *property = pre->getExplicitProperty();
8827 if (!property->isRetaining() &&
8828 !(property->getPropertyIvarDecl() &&
8829 property->getPropertyIvarDecl()->getType()
8830 .getObjCLifetime() == Qualifiers::OCL_Strong))
8833 owner.Indirect = true;
8834 if (pre->isSuperReceiver()) {
8835 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8836 if (!owner.Variable)
8838 owner.Loc = pre->getLocation();
8839 owner.Range = pre->getSourceRange();
8842 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8854 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8855 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8856 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
8857 Context(Context), Variable(variable), Capturer(nullptr),
8858 VarWillBeReased(false) {}
8859 ASTContext &Context;
8862 bool VarWillBeReased;
8864 void VisitDeclRefExpr(DeclRefExpr *ref) {
8865 if (ref->getDecl() == Variable && !Capturer)
8869 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8870 if (Capturer) return;
8871 Visit(ref->getBase());
8872 if (Capturer && ref->isFreeIvar())
8876 void VisitBlockExpr(BlockExpr *block) {
8877 // Look inside nested blocks
8878 if (block->getBlockDecl()->capturesVariable(Variable))
8879 Visit(block->getBlockDecl()->getBody());
8882 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8883 if (Capturer) return;
8884 if (OVE->getSourceExpr())
8885 Visit(OVE->getSourceExpr());
8887 void VisitBinaryOperator(BinaryOperator *BinOp) {
8888 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8890 Expr *LHS = BinOp->getLHS();
8891 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8892 if (DRE->getDecl() != Variable)
8894 if (Expr *RHS = BinOp->getRHS()) {
8895 RHS = RHS->IgnoreParenCasts();
8898 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8905 /// Check whether the given argument is a block which captures a
8907 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8908 assert(owner.Variable && owner.Loc.isValid());
8910 e = e->IgnoreParenCasts();
8912 // Look through [^{...} copy] and Block_copy(^{...}).
8913 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8914 Selector Cmd = ME->getSelector();
8915 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8916 e = ME->getInstanceReceiver();
8919 e = e->IgnoreParenCasts();
8921 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8922 if (CE->getNumArgs() == 1) {
8923 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
8925 const IdentifierInfo *FnI = Fn->getIdentifier();
8926 if (FnI && FnI->isStr("_Block_copy")) {
8927 e = CE->getArg(0)->IgnoreParenCasts();
8933 BlockExpr *block = dyn_cast<BlockExpr>(e);
8934 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
8937 FindCaptureVisitor visitor(S.Context, owner.Variable);
8938 visitor.Visit(block->getBlockDecl()->getBody());
8939 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
8942 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8943 RetainCycleOwner &owner) {
8945 assert(owner.Variable && owner.Loc.isValid());
8947 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8948 << owner.Variable << capturer->getSourceRange();
8949 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8950 << owner.Indirect << owner.Range;
8953 /// Check for a keyword selector that starts with the word 'add' or
8955 static bool isSetterLikeSelector(Selector sel) {
8956 if (sel.isUnarySelector()) return false;
8958 StringRef str = sel.getNameForSlot(0);
8959 while (!str.empty() && str.front() == '_') str = str.substr(1);
8960 if (str.startswith("set"))
8961 str = str.substr(3);
8962 else if (str.startswith("add")) {
8963 // Specially whitelist 'addOperationWithBlock:'.
8964 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8966 str = str.substr(3);
8971 if (str.empty()) return true;
8972 return !isLowercase(str.front());
8975 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8976 ObjCMessageExpr *Message) {
8977 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
8978 Message->getReceiverInterface(),
8979 NSAPI::ClassId_NSMutableArray);
8980 if (!IsMutableArray) {
8984 Selector Sel = Message->getSelector();
8986 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8987 S.NSAPIObj->getNSArrayMethodKind(Sel);
8992 NSAPI::NSArrayMethodKind MK = *MKOpt;
8995 case NSAPI::NSMutableArr_addObject:
8996 case NSAPI::NSMutableArr_insertObjectAtIndex:
8997 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8999 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9010 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9011 ObjCMessageExpr *Message) {
9012 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9013 Message->getReceiverInterface(),
9014 NSAPI::ClassId_NSMutableDictionary);
9015 if (!IsMutableDictionary) {
9019 Selector Sel = Message->getSelector();
9021 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9022 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9027 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9030 case NSAPI::NSMutableDict_setObjectForKey:
9031 case NSAPI::NSMutableDict_setValueForKey:
9032 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9042 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
9043 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9044 Message->getReceiverInterface(),
9045 NSAPI::ClassId_NSMutableSet);
9047 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9048 Message->getReceiverInterface(),
9049 NSAPI::ClassId_NSMutableOrderedSet);
9050 if (!IsMutableSet && !IsMutableOrderedSet) {
9054 Selector Sel = Message->getSelector();
9056 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9061 NSAPI::NSSetMethodKind MK = *MKOpt;
9064 case NSAPI::NSMutableSet_addObject:
9065 case NSAPI::NSOrderedSet_setObjectAtIndex:
9066 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9067 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9069 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9076 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9077 if (!Message->isInstanceMessage()) {
9081 Optional<int> ArgOpt;
9083 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9084 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9085 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9089 int ArgIndex = *ArgOpt;
9091 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9092 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9093 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9096 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
9097 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9098 if (ArgRE->isObjCSelfExpr()) {
9099 Diag(Message->getSourceRange().getBegin(),
9100 diag::warn_objc_circular_container)
9101 << ArgRE->getDecl()->getName() << StringRef("super");
9105 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9107 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9108 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9111 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9112 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9113 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9114 ValueDecl *Decl = ReceiverRE->getDecl();
9115 Diag(Message->getSourceRange().getBegin(),
9116 diag::warn_objc_circular_container)
9117 << Decl->getName() << Decl->getName();
9118 if (!ArgRE->isObjCSelfExpr()) {
9119 Diag(Decl->getLocation(),
9120 diag::note_objc_circular_container_declared_here)
9125 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9126 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9127 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9128 ObjCIvarDecl *Decl = IvarRE->getDecl();
9129 Diag(Message->getSourceRange().getBegin(),
9130 diag::warn_objc_circular_container)
9131 << Decl->getName() << Decl->getName();
9132 Diag(Decl->getLocation(),
9133 diag::note_objc_circular_container_declared_here)
9142 /// Check a message send to see if it's likely to cause a retain cycle.
9143 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9144 // Only check instance methods whose selector looks like a setter.
9145 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9148 // Try to find a variable that the receiver is strongly owned by.
9149 RetainCycleOwner owner;
9150 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
9151 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
9154 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9155 owner.Variable = getCurMethodDecl()->getSelfDecl();
9156 owner.Loc = msg->getSuperLoc();
9157 owner.Range = msg->getSuperLoc();
9160 // Check whether the receiver is captured by any of the arguments.
9161 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9162 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9163 return diagnoseRetainCycle(*this, capturer, owner);
9166 /// Check a property assign to see if it's likely to cause a retain cycle.
9167 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9168 RetainCycleOwner owner;
9169 if (!findRetainCycleOwner(*this, receiver, owner))
9172 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9173 diagnoseRetainCycle(*this, capturer, owner);
9176 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9177 RetainCycleOwner Owner;
9178 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
9181 // Because we don't have an expression for the variable, we have to set the
9182 // location explicitly here.
9183 Owner.Loc = Var->getLocation();
9184 Owner.Range = Var->getSourceRange();
9186 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9187 diagnoseRetainCycle(*this, Capturer, Owner);
9190 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9191 Expr *RHS, bool isProperty) {
9192 // Check if RHS is an Objective-C object literal, which also can get
9193 // immediately zapped in a weak reference. Note that we explicitly
9194 // allow ObjCStringLiterals, since those are designed to never really die.
9195 RHS = RHS->IgnoreParenImpCasts();
9197 // This enum needs to match with the 'select' in
9198 // warn_objc_arc_literal_assign (off-by-1).
9199 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9200 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9203 S.Diag(Loc, diag::warn_arc_literal_assign)
9205 << (isProperty ? 0 : 1)
9206 << RHS->getSourceRange();
9211 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9212 Qualifiers::ObjCLifetime LT,
9213 Expr *RHS, bool isProperty) {
9214 // Strip off any implicit cast added to get to the one ARC-specific.
9215 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9216 if (cast->getCastKind() == CK_ARCConsumeObject) {
9217 S.Diag(Loc, diag::warn_arc_retained_assign)
9218 << (LT == Qualifiers::OCL_ExplicitNone)
9219 << (isProperty ? 0 : 1)
9220 << RHS->getSourceRange();
9223 RHS = cast->getSubExpr();
9226 if (LT == Qualifiers::OCL_Weak &&
9227 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9233 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9234 QualType LHS, Expr *RHS) {
9235 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9237 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9240 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9246 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9247 Expr *LHS, Expr *RHS) {
9249 // PropertyRef on LHS type need be directly obtained from
9250 // its declaration as it has a PseudoType.
9251 ObjCPropertyRefExpr *PRE
9252 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9253 if (PRE && !PRE->isImplicitProperty()) {
9254 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9256 LHSType = PD->getType();
9259 if (LHSType.isNull())
9260 LHSType = LHS->getType();
9262 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9264 if (LT == Qualifiers::OCL_Weak) {
9265 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
9266 getCurFunction()->markSafeWeakUse(LHS);
9269 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9272 // FIXME. Check for other life times.
9273 if (LT != Qualifiers::OCL_None)
9277 if (PRE->isImplicitProperty())
9279 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9283 unsigned Attributes = PD->getPropertyAttributes();
9284 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
9285 // when 'assign' attribute was not explicitly specified
9286 // by user, ignore it and rely on property type itself
9287 // for lifetime info.
9288 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9289 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9290 LHSType->isObjCRetainableType())
9293 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9294 if (cast->getCastKind() == CK_ARCConsumeObject) {
9295 Diag(Loc, diag::warn_arc_retained_property_assign)
9296 << RHS->getSourceRange();
9299 RHS = cast->getSubExpr();
9302 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
9303 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9309 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9312 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9313 SourceLocation StmtLoc,
9314 const NullStmt *Body) {
9315 // Do not warn if the body is a macro that expands to nothing, e.g:
9321 if (Body->hasLeadingEmptyMacro())
9324 // Get line numbers of statement and body.
9325 bool StmtLineInvalid;
9326 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
9328 if (StmtLineInvalid)
9331 bool BodyLineInvalid;
9332 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9334 if (BodyLineInvalid)
9337 // Warn if null statement and body are on the same line.
9338 if (StmtLine != BodyLine)
9343 } // Unnamed namespace
9345 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9348 // Since this is a syntactic check, don't emit diagnostic for template
9349 // instantiations, this just adds noise.
9350 if (CurrentInstantiationScope)
9353 // The body should be a null statement.
9354 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9358 // Do the usual checks.
9359 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9362 Diag(NBody->getSemiLoc(), DiagID);
9363 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9366 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9367 const Stmt *PossibleBody) {
9368 assert(!CurrentInstantiationScope); // Ensured by caller
9370 SourceLocation StmtLoc;
9373 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9374 StmtLoc = FS->getRParenLoc();
9375 Body = FS->getBody();
9376 DiagID = diag::warn_empty_for_body;
9377 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9378 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9379 Body = WS->getBody();
9380 DiagID = diag::warn_empty_while_body;
9382 return; // Neither `for' nor `while'.
9384 // The body should be a null statement.
9385 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9389 // Skip expensive checks if diagnostic is disabled.
9390 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
9393 // Do the usual checks.
9394 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9397 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9398 // noise level low, emit diagnostics only if for/while is followed by a
9399 // CompoundStmt, e.g.:
9400 // for (int i = 0; i < n; i++);
9404 // or if for/while is followed by a statement with more indentation
9405 // than for/while itself:
9406 // for (int i = 0; i < n; i++);
9408 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9409 if (!ProbableTypo) {
9410 bool BodyColInvalid;
9411 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9412 PossibleBody->getLocStart(),
9417 bool StmtColInvalid;
9418 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9424 if (BodyCol > StmtCol)
9425 ProbableTypo = true;
9429 Diag(NBody->getSemiLoc(), DiagID);
9430 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9434 //===--- CHECK: Warn on self move with std::move. -------------------------===//
9436 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9437 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9438 SourceLocation OpLoc) {
9440 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9443 if (!ActiveTemplateInstantiations.empty())
9446 // Strip parens and casts away.
9447 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9448 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9450 // Check for a call expression
9451 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9452 if (!CE || CE->getNumArgs() != 1)
9455 // Check for a call to std::move
9456 const FunctionDecl *FD = CE->getDirectCallee();
9457 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9458 !FD->getIdentifier()->isStr("move"))
9461 // Get argument from std::move
9462 RHSExpr = CE->getArg(0);
9464 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9465 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9467 // Two DeclRefExpr's, check that the decls are the same.
9468 if (LHSDeclRef && RHSDeclRef) {
9469 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9471 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9472 RHSDeclRef->getDecl()->getCanonicalDecl())
9475 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9476 << LHSExpr->getSourceRange()
9477 << RHSExpr->getSourceRange();
9481 // Member variables require a different approach to check for self moves.
9482 // MemberExpr's are the same if every nested MemberExpr refers to the same
9483 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9484 // the base Expr's are CXXThisExpr's.
9485 const Expr *LHSBase = LHSExpr;
9486 const Expr *RHSBase = RHSExpr;
9487 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9488 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9489 if (!LHSME || !RHSME)
9492 while (LHSME && RHSME) {
9493 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9494 RHSME->getMemberDecl()->getCanonicalDecl())
9497 LHSBase = LHSME->getBase();
9498 RHSBase = RHSME->getBase();
9499 LHSME = dyn_cast<MemberExpr>(LHSBase);
9500 RHSME = dyn_cast<MemberExpr>(RHSBase);
9503 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9504 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9505 if (LHSDeclRef && RHSDeclRef) {
9506 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9508 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9509 RHSDeclRef->getDecl()->getCanonicalDecl())
9512 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9513 << LHSExpr->getSourceRange()
9514 << RHSExpr->getSourceRange();
9518 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9519 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9520 << LHSExpr->getSourceRange()
9521 << RHSExpr->getSourceRange();
9524 //===--- Layout compatibility ----------------------------------------------//
9528 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9530 /// \brief Check if two enumeration types are layout-compatible.
9531 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9532 // C++11 [dcl.enum] p8:
9533 // Two enumeration types are layout-compatible if they have the same
9535 return ED1->isComplete() && ED2->isComplete() &&
9536 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9539 /// \brief Check if two fields are layout-compatible.
9540 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9541 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9544 if (Field1->isBitField() != Field2->isBitField())
9547 if (Field1->isBitField()) {
9548 // Make sure that the bit-fields are the same length.
9549 unsigned Bits1 = Field1->getBitWidthValue(C);
9550 unsigned Bits2 = Field2->getBitWidthValue(C);
9559 /// \brief Check if two standard-layout structs are layout-compatible.
9560 /// (C++11 [class.mem] p17)
9561 bool isLayoutCompatibleStruct(ASTContext &C,
9564 // If both records are C++ classes, check that base classes match.
9565 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9566 // If one of records is a CXXRecordDecl we are in C++ mode,
9567 // thus the other one is a CXXRecordDecl, too.
9568 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9569 // Check number of base classes.
9570 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9573 // Check the base classes.
9574 for (CXXRecordDecl::base_class_const_iterator
9575 Base1 = D1CXX->bases_begin(),
9576 BaseEnd1 = D1CXX->bases_end(),
9577 Base2 = D2CXX->bases_begin();
9580 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9583 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9584 // If only RD2 is a C++ class, it should have zero base classes.
9585 if (D2CXX->getNumBases() > 0)
9589 // Check the fields.
9590 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9591 Field2End = RD2->field_end(),
9592 Field1 = RD1->field_begin(),
9593 Field1End = RD1->field_end();
9594 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9595 if (!isLayoutCompatible(C, *Field1, *Field2))
9598 if (Field1 != Field1End || Field2 != Field2End)
9604 /// \brief Check if two standard-layout unions are layout-compatible.
9605 /// (C++11 [class.mem] p18)
9606 bool isLayoutCompatibleUnion(ASTContext &C,
9609 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
9610 for (auto *Field2 : RD2->fields())
9611 UnmatchedFields.insert(Field2);
9613 for (auto *Field1 : RD1->fields()) {
9614 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9615 I = UnmatchedFields.begin(),
9616 E = UnmatchedFields.end();
9618 for ( ; I != E; ++I) {
9619 if (isLayoutCompatible(C, Field1, *I)) {
9620 bool Result = UnmatchedFields.erase(*I);
9630 return UnmatchedFields.empty();
9633 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9634 if (RD1->isUnion() != RD2->isUnion())
9638 return isLayoutCompatibleUnion(C, RD1, RD2);
9640 return isLayoutCompatibleStruct(C, RD1, RD2);
9643 /// \brief Check if two types are layout-compatible in C++11 sense.
9644 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9645 if (T1.isNull() || T2.isNull())
9648 // C++11 [basic.types] p11:
9649 // If two types T1 and T2 are the same type, then T1 and T2 are
9650 // layout-compatible types.
9651 if (C.hasSameType(T1, T2))
9654 T1 = T1.getCanonicalType().getUnqualifiedType();
9655 T2 = T2.getCanonicalType().getUnqualifiedType();
9657 const Type::TypeClass TC1 = T1->getTypeClass();
9658 const Type::TypeClass TC2 = T2->getTypeClass();
9663 if (TC1 == Type::Enum) {
9664 return isLayoutCompatible(C,
9665 cast<EnumType>(T1)->getDecl(),
9666 cast<EnumType>(T2)->getDecl());
9667 } else if (TC1 == Type::Record) {
9668 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9671 return isLayoutCompatible(C,
9672 cast<RecordType>(T1)->getDecl(),
9673 cast<RecordType>(T2)->getDecl());
9680 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9683 /// \brief Given a type tag expression find the type tag itself.
9685 /// \param TypeExpr Type tag expression, as it appears in user's code.
9687 /// \param VD Declaration of an identifier that appears in a type tag.
9689 /// \param MagicValue Type tag magic value.
9690 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9691 const ValueDecl **VD, uint64_t *MagicValue) {
9696 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9698 switch (TypeExpr->getStmtClass()) {
9699 case Stmt::UnaryOperatorClass: {
9700 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9701 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9702 TypeExpr = UO->getSubExpr();
9708 case Stmt::DeclRefExprClass: {
9709 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9710 *VD = DRE->getDecl();
9714 case Stmt::IntegerLiteralClass: {
9715 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9716 llvm::APInt MagicValueAPInt = IL->getValue();
9717 if (MagicValueAPInt.getActiveBits() <= 64) {
9718 *MagicValue = MagicValueAPInt.getZExtValue();
9724 case Stmt::BinaryConditionalOperatorClass:
9725 case Stmt::ConditionalOperatorClass: {
9726 const AbstractConditionalOperator *ACO =
9727 cast<AbstractConditionalOperator>(TypeExpr);
9729 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9731 TypeExpr = ACO->getTrueExpr();
9733 TypeExpr = ACO->getFalseExpr();
9739 case Stmt::BinaryOperatorClass: {
9740 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9741 if (BO->getOpcode() == BO_Comma) {
9742 TypeExpr = BO->getRHS();
9754 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
9756 /// \param TypeExpr Expression that specifies a type tag.
9758 /// \param MagicValues Registered magic values.
9760 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9763 /// \param TypeInfo Information about the corresponding C type.
9765 /// \returns true if the corresponding C type was found.
9766 bool GetMatchingCType(
9767 const IdentifierInfo *ArgumentKind,
9768 const Expr *TypeExpr, const ASTContext &Ctx,
9769 const llvm::DenseMap<Sema::TypeTagMagicValue,
9770 Sema::TypeTagData> *MagicValues,
9771 bool &FoundWrongKind,
9772 Sema::TypeTagData &TypeInfo) {
9773 FoundWrongKind = false;
9775 // Variable declaration that has type_tag_for_datatype attribute.
9776 const ValueDecl *VD = nullptr;
9778 uint64_t MagicValue;
9780 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9784 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
9785 if (I->getArgumentKind() != ArgumentKind) {
9786 FoundWrongKind = true;
9789 TypeInfo.Type = I->getMatchingCType();
9790 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9791 TypeInfo.MustBeNull = I->getMustBeNull();
9800 llvm::DenseMap<Sema::TypeTagMagicValue,
9801 Sema::TypeTagData>::const_iterator I =
9802 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9803 if (I == MagicValues->end())
9806 TypeInfo = I->second;
9809 } // unnamed namespace
9811 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9812 uint64_t MagicValue, QualType Type,
9813 bool LayoutCompatible,
9815 if (!TypeTagForDatatypeMagicValues)
9816 TypeTagForDatatypeMagicValues.reset(
9817 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9819 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9820 (*TypeTagForDatatypeMagicValues)[Magic] =
9821 TypeTagData(Type, LayoutCompatible, MustBeNull);
9825 bool IsSameCharType(QualType T1, QualType T2) {
9826 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9830 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9834 BuiltinType::Kind T1Kind = BT1->getKind();
9835 BuiltinType::Kind T2Kind = BT2->getKind();
9837 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9838 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9839 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9840 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9842 } // unnamed namespace
9844 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9845 const Expr * const *ExprArgs) {
9846 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9847 bool IsPointerAttr = Attr->getIsPointer();
9849 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9850 bool FoundWrongKind;
9851 TypeTagData TypeInfo;
9852 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9853 TypeTagForDatatypeMagicValues.get(),
9854 FoundWrongKind, TypeInfo)) {
9856 Diag(TypeTagExpr->getExprLoc(),
9857 diag::warn_type_tag_for_datatype_wrong_kind)
9858 << TypeTagExpr->getSourceRange();
9862 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9863 if (IsPointerAttr) {
9864 // Skip implicit cast of pointer to `void *' (as a function argument).
9865 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
9866 if (ICE->getType()->isVoidPointerType() &&
9867 ICE->getCastKind() == CK_BitCast)
9868 ArgumentExpr = ICE->getSubExpr();
9870 QualType ArgumentType = ArgumentExpr->getType();
9872 // Passing a `void*' pointer shouldn't trigger a warning.
9873 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9876 if (TypeInfo.MustBeNull) {
9877 // Type tag with matching void type requires a null pointer.
9878 if (!ArgumentExpr->isNullPointerConstant(Context,
9879 Expr::NPC_ValueDependentIsNotNull)) {
9880 Diag(ArgumentExpr->getExprLoc(),
9881 diag::warn_type_safety_null_pointer_required)
9882 << ArgumentKind->getName()
9883 << ArgumentExpr->getSourceRange()
9884 << TypeTagExpr->getSourceRange();
9889 QualType RequiredType = TypeInfo.Type;
9891 RequiredType = Context.getPointerType(RequiredType);
9893 bool mismatch = false;
9894 if (!TypeInfo.LayoutCompatible) {
9895 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9897 // C++11 [basic.fundamental] p1:
9898 // Plain char, signed char, and unsigned char are three distinct types.
9900 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9901 // char' depending on the current char signedness mode.
9903 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9904 RequiredType->getPointeeType())) ||
9905 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9909 mismatch = !isLayoutCompatible(Context,
9910 ArgumentType->getPointeeType(),
9911 RequiredType->getPointeeType());
9913 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9916 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
9917 << ArgumentType << ArgumentKind
9918 << TypeInfo.LayoutCompatible << RequiredType
9919 << ArgumentExpr->getSourceRange()
9920 << TypeTagExpr->getSourceRange();