Lines Matching +full:docs +full:- +full:clang +full:- +full:man
1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
12 //===----------------------------------------------------------------------===//
15 #include "clang/AST/APValue.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/IgnoreExpr.h"
31 #include "clang/AST/NSAPI.h"
32 #include "clang/AST/NonTrivialTypeVisitor.h"
33 #include "clang/AST/OperationKinds.h"
34 #include "clang/AST/RecordLayout.h"
35 #include "clang/AST/Stmt.h"
36 #include "clang/AST/TemplateBase.h"
37 #include "clang/AST/Type.h"
38 #include "clang/AST/TypeLoc.h"
39 #include "clang/AST/UnresolvedSet.h"
40 #include "clang/Basic/AddressSpaces.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetInfo.h"
53 #include "clang/Basic/TypeTraits.h"
54 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
55 #include "clang/Sema/Initialization.h"
56 #include "clang/Sema/Lookup.h"
57 #include "clang/Sema/Ownership.h"
58 #include "clang/Sema/Scope.h"
59 #include "clang/Sema/ScopeInfo.h"
60 #include "clang/Sema/Sema.h"
61 #include "clang/Sema/SemaAMDGPU.h"
62 #include "clang/Sema/SemaARM.h"
63 #include "clang/Sema/SemaBPF.h"
64 #include "clang/Sema/SemaHLSL.h"
65 #include "clang/Sema/SemaHexagon.h"
66 #include "clang/Sema/SemaLoongArch.h"
67 #include "clang/Sema/SemaMIPS.h"
68 #include "clang/Sema/SemaNVPTX.h"
69 #include "clang/Sema/SemaObjC.h"
70 #include "clang/Sema/SemaOpenCL.h"
71 #include "clang/Sema/SemaPPC.h"
72 #include "clang/Sema/SemaRISCV.h"
73 #include "clang/Sema/SemaSPIRV.h"
74 #include "clang/Sema/SemaSystemZ.h"
75 #include "clang/Sema/SemaWasm.h"
76 #include "clang/Sema/SemaX86.h"
115 using namespace clang;
120 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
130 unsigned ArgCount = Call->getNumArgs();
134 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
136 << /*is non object*/ 0 << Call->getSourceRange();
140 unsigned ArgCount = Call->getNumArgs();
143 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
145 << /*is non object*/ 0 << Call->getSourceRange();
155 unsigned ArgCount = Call->getNumArgs();
164 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
165 Call->getArg(ArgCount - 1)->getEndLoc());
169 << /*is non object*/ 0 << Call->getArg(1)->getSourceRange();
175 for (unsigned I = 0; I < Call->getNumArgs(); ++I) {
176 Expr *Arg = Call->getArg(I);
178 if (Arg->isValueDependent())
181 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
182 int DiagMsgKind = -1;
186 else if (ArgString->find('$') != std::string::npos)
190 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
191 << DiagMsgKind << Arg->getSourceRange();
200 if (Value->isTypeDependent())
214 /// and the second argument is a non-wide string literal.
220 Expr *ValArg = TheCall->getArg(0);
221 QualType Ty = ValArg->getType();
222 if (!Ty->isIntegerType()) {
223 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
224 << ValArg->getSourceRange();
229 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
231 if (!Literal || !Literal->isOrdinary()) {
232 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
233 << StrArg->getSourceRange();
237 TheCall->setType(Ty);
243 if (TheCall->getNumArgs() < 1) {
244 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
245 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
246 << TheCall->getCallee()->getSourceRange();
251 for (Expr *Arg : TheCall->arguments()) {
252 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
253 if (!Literal || !Literal->isWide()) {
254 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
255 << Arg->getSourceRange();
269 ExprResult Arg(TheCall->getArg(0));
270 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
274 TheCall->setArg(0, Arg.get());
275 TheCall->setType(ResultType);
284 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
288 TheCall->setArg(0, Arg.get());
290 Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext()));
293 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
294 << TheCall->getSourceRange();
299 TheCall->getBeginLoc());
308 TheCall->setType(TheCall->getArg(0)->getType());
314 /// type (but not a function pointer) and that the alignment is a power-of-two.
319 clang::Expr *Source = TheCall->getArg(0);
323 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
325 QualType SrcTy = Source->getType();
327 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
330 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
331 SrcTy->isFunctionPointerType()) {
334 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
339 clang::Expr *AlignOp = TheCall->getArg(1);
340 if (!IsValidIntegerType(AlignOp->getType())) {
341 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
342 << AlignOp->getType();
346 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
348 if (!AlignOp->isValueDependent() &&
349 AlignOp->EvaluateAsInt(AlignResult, S.Context,
355 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
359 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
364 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
368 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
378 TheCall->setArg(0, SrcArg.get());
381 S.Context, AlignOp->getType(), false),
385 TheCall->setArg(1, AlignArg.get());
389 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
405 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
406 Lexer::getImmediateMacroName(TheCall->getExprLoc(),
412 // bool, a bit-precise type, or an enumeration type.
413 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
414 return (BT->getKind() >= BuiltinType::Short &&
415 BT->getKind() <= BuiltinType::Int128) || (
416 BT->getKind() >= BuiltinType::UShort &&
417 BT->getKind() <= BuiltinType::UInt128) ||
418 BT->getKind() == BuiltinType::UChar ||
419 BT->getKind() == BuiltinType::SChar;
425 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
427 TheCall->setArg(I, Arg.get());
429 QualType Ty = Arg.get()->getType();
430 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
432 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
433 << CkdOperation << Ty << Arg.get()->getSourceRange();
438 // Third argument should be a pointer to a non-const integer.
442 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
444 TheCall->setArg(2, Arg.get());
446 QualType Ty = Arg.get()->getType();
447 const auto *PtrTy = Ty->getAs<PointerType>();
449 !PtrTy->getPointeeType()->isIntegerType() ||
450 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
451 PtrTy->getPointeeType().isConstQualified()) {
452 S.Diag(Arg.get()->getBeginLoc(),
454 << CkdOperation << Ty << Arg.get()->getSourceRange();
459 // Disallow signed bit-precise integer args larger than 128 bits to mul
463 const auto Arg = TheCall->getArg(I);
465 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
466 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
468 return S.Diag(Arg->getBeginLoc(),
481 SourceLocation Loc = TheCall->getBeginLoc();
494 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
495 Inner->getObjectKind(), Inner);
509 assert(TheCall->getNumArgs() >= 2);
510 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
511 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
524 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
525 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
553 if (auto *BT = T->getAs<BuiltinType>()) {
554 switch (BT->getKind()) {
576 // Wrap double-quotes around a '%s' specifier and limit its maximum
592 if (T->isPointerType()) {
620 // triggering re-evaluation.
622 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
629 for (const auto &Base : CXXRD->bases()) {
637 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
646 for (auto *D : RD->decls()) {
648 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
649 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
654 getTypeString(FD->getType()),
655 getStringLiteral(FD->getName())};
657 if (FD->isBitField()) {
661 FD->getBitWidthValue());
674 DeclarationNameInfo(FD->getDeclName(), Loc));
678 auto *InnerRD = FD->getType()->getAsRecordDecl();
680 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
687 if (appendFormatSpecifier(FD->getType(), Format)) {
714 TheCall->setType(Wrapper->getType());
715 TheCall->setValueKind(Wrapper->getValueKind());
725 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
728 TheCall->setArg(0, PtrArgResult.get());
731 QualType PtrArgType = PtrArgResult.get()->getType();
732 if (!PtrArgType->isPointerType() ||
733 !PtrArgType->getPointeeType()->isRecordType()) {
734 S.Diag(PtrArgResult.get()->getBeginLoc(),
736 << 1 << TheCall->getDirectCallee() << PtrArgType;
739 QualType Pointee = PtrArgType->getPointeeType();
740 const RecordDecl *RD = Pointee->getAsRecordDecl();
743 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
748 QualType FnArgType = TheCall->getArg(1)->getType();
749 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
750 !FnArgType->isBlockPointerType() &&
751 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
752 auto *BT = FnArgType->getAs<BuiltinType>();
753 switch (BT ? BT->getKind() : BuiltinType::Void) {
764 S.Diag(TheCall->getArg(1)->getBeginLoc(),
766 << 2 << TheCall->getDirectCallee() << FnArgType;
774 // correct code generation, but it means that when we pretty-print the call
775 // arguments in our diagnostics we will produce '(&s)->n' instead of the
776 // incorrect '&s->n'.
779 ParenExpr(PtrArg->getBeginLoc(),
780 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
791 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
792 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
793 Expr *Call = BuiltinCall->getArg(0);
794 Expr *Chain = BuiltinCall->getArg(1);
796 if (Call->getStmtClass() != Stmt::CallExprClass) {
798 << Call->getSourceRange();
803 if (CE->getCallee()->getType()->isBlockPointerType()) {
805 << Call->getSourceRange();
809 const Decl *TargetDecl = CE->getCalleeDecl();
811 if (FD->getBuiltinID()) {
813 << Call->getSourceRange();
817 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
819 << Call->getSourceRange();
826 if (!ChainResult.get()->getType()->isPointerType()) {
828 << Chain->getSourceRange();
832 QualType ReturnTy = CE->getCallReturnType(S.Context);
833 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
841 BuiltinCall->setType(CE->getType());
842 BuiltinCall->setValueKind(CE->getValueKind());
843 BuiltinCall->setObjectKind(CE->getObjectKind());
844 BuiltinCall->setCallee(Builtin);
845 BuiltinCall->setArg(1, ChainResult.get());
902 unsigned DestSize = DestSizeAPS->getZExtValue();
968 // Floating point number in the form '[-]d.ddde[+-]dd'.
978 // Floating point number in the form '[-]0xh.hhhhp±dd'.
985 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
998 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1027 // (prefix_width <= FieldWidth - formatted_length) holds,
1034 // the result of converting a floating-point number always contains a
1035 // decimal-point
1052 Size -= SpecifierLen;
1072 // See man 3 printf for default precision value based on the specifier.
1120 Format && (Format->isOrdinary() || Format->isUTF8())) {
1121 FormatStrRef = Format->getString();
1123 Context.getAsConstantArrayType(Format->getType());
1125 size_t TypeSize = T->getZExtSize();
1127 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1135 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1142 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1144 UseDecl = DABAttr->getFunction();
1149 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1157 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1164 unsigned DABIndices = DABAttr->argIndices_size();
1166 ? DABAttr->argIndices_begin()[Index]
1167 : Index - DABIndices + FD->getNumParams();
1168 if (NewIndex >= TheCall->getNumArgs())
1174 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1180 Expr *SizeArg = TheCall->getArg(NewIndex);
1181 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1189 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1195 if (Index < FD->getNumParams()) {
1197 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1198 BOSType = POS->getType();
1206 if (NewIndex >= TheCall->getNumArgs())
1209 const Expr *ObjArg = TheCall->getArg(NewIndex);
1211 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1219 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1225 const Expr *ObjArg = TheCall->getArg(NewIndex);
1227 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1282 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1294 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1317 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1354 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1356 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1382 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1396 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1406 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1425 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1427 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1446 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1447 SourceSize->toString(SourceStr, /*Radix=*/10);
1448 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1463 while (S && !S->isSEHExceptScope())
1464 S = S->getParent();
1465 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1466 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1467 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1468 << DRE->getDecl()->getIdentifier();
1478 QualType RT = TheCall->getType();
1479 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1482 RT = RT->getPointeeType();
1484 TheCall->setType(S.Context.getPointerType(RT));
1508 return S.checkPointerAuthEnabled(E->getExprLoc(), E->getSourceRange());
1516 // Value-dependent expressions are okay; wait for template instantiation.
1517 if (Arg->isValueDependent())
1525 // Attempt to constant-evaluate the expression.
1526 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1528 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1529 << 0 << Arg->getSourceRange();
1541 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1542 << Value << Arg->getSourceRange();
1546 Result = KeyValue->getZExtValue();
1554 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1567 if (Arg->hasPlaceholderType()) {
1584 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1585 ExpectedTy = Arg->getType().getUnqualifiedType();
1586 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1589 Arg->getType()->isIntegralOrUnscopedEnumerationType()) {
1594 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1600 << Arg->getType() << Arg->getSourceRange();
1604 // Convert to that type. This should just be an lvalue-to-rvalue
1610 // Warn about null pointers for non-generic sign and auth operations.
1612 Arg->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull)) {
1613 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1616 << Arg->getSourceRange();
1643 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1653 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1654 if (Call->getBuiltinCallee() ==
1656 Pointer = Call->getArg(0);
1657 Integer = Call->getArg(1);
1661 if (Arg->getType()->isPointerType())
1670 assert(Pointer->getType()->isPointerType());
1674 // never really be feasible and we'll have to catch it at link-time.
1682 assert(Integer->getType()->isIntegerType());
1683 if (!Integer->isEvaluatable(S.Context))
1688 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1697 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1698 checkPointerAuthKey(S, Call->getArgs()[1]))
1701 Call->setType(Call->getArgs()[0]->getType());
1710 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1711 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1714 Call->setType(S.Context.getUIntPtrType());
1723 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1724 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1727 Call->setType(S.Context.getUIntPtrType());
1738 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1739 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1740 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1744 Call->setType(Call->getArgs()[0]->getType());
1753 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1754 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1755 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1756 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1757 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1760 Call->setType(Call->getArgs()[0]->getType());
1768 // We've already performed normal call type-checking.
1769 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1771 // Operand must be an ordinary or UTF-8 string literal.
1773 if (!Literal || Literal->getCharByteWidth() != 1) {
1774 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1775 << (Literal ? 1 : 0) << Arg->getSourceRange();
1792 QualType ArgTy = TheCall->getArg(0)->getType();
1793 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1794 return S.Context.getPointerType(Ty->getElementType());
1795 if (ArgTy->isFunctionType()) {
1801 TheCall->setType(ParamTy);
1803 auto DiagSelect = [&]() -> std::optional<unsigned> {
1804 if (!ParamTy->isPointerType())
1806 if (ParamTy->isFunctionPointerType())
1808 if (ParamTy->isVoidPointerType())
1813 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1814 << *DiagSelect << TheCall->getSourceRange();
1824 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1828 assert(ParamTy->getPointeeType()->isObjectType() &&
1829 "Unhandled non-object pointer case");
1834 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1837 TheCall->setArg(0, Arg.get());
1846 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1849 QualType ParamTy = Arg.get()->getType();
1850 TheCall->setArg(0, Arg.get());
1851 TheCall->setType(S.Context.BoolTy);
1855 if (const auto *PT = ParamTy->getAs<PointerType>()) {
1857 if (PT->getPointeeType()->isFunctionType()) {
1858 S.Diag(TheCall->getArg(0)->getExprLoc(),
1865 if (PT->getPointeeType()->isVariableArrayType()) {
1866 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
1871 S.Diag(TheCall->getArg(0)->getExprLoc(),
1888 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1889 << TheCall->getSourceRange();
1904 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1905 << TheCall->getSourceRange();
1973 if (!ArgTy->getAs<VectorType>() &&
1985 if (auto *VecTy = EltTy->getAs<VectorType>())
1986 EltTy = VecTy->getElementType();
1988 if (!EltTy->isRealFloatingType()) {
1996 /// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2008 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2009 (!IsCPUSupports && TInfo->supportsCpuIs()));
2014 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2015 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2016 return S.Diag(TheCall->getBeginLoc(),
2020 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2022 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2025 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2026 << Arg->getSourceRange();
2029 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2030 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2031 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2032 << Arg->getSourceRange();
2035 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2036 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2037 << Arg->getSourceRange();
2047 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2052 TheCall->setArg(0, Arg);
2054 QualType ArgTy = Arg->getType();
2056 if (!ArgTy->isUnsignedIntegerType()) {
2057 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2071 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2076 TheCall->setArg(0, Arg0);
2078 QualType Arg0Ty = Arg0->getType();
2080 if (!Arg0Ty->isUnsignedIntegerType()) {
2081 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2086 if (TheCall->getNumArgs() > 1) {
2087 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2092 TheCall->setArg(1, Arg1);
2094 QualType Arg1Ty = Arg1->getType();
2096 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2097 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2126 if (ArgNo < TheCall->getNumArgs() &&
2142 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2143 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2154 assert(TheCall->getNumArgs() == 1 &&
2156 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2194 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2264 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2265 << TheCall->getDirectCallee();
2299 TheCall->setType(Context.IntTy);
2308 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
2310 TheCall->setArg(0, Arg.get());
2311 TheCall->setType(Context.IntTy);
2422 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
2423 << TheCall->getCallee()->getSourceRange();
2429 clang::Expr *SizeOp = TheCall->getArg(2);
2433 if (SizeOp->isValueDependent())
2435 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
2436 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2437 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
2442 clang::Expr *SizeOp = TheCall->getArg(2);
2446 if (SizeOp->isValueDependent())
2448 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
2449 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2456 #include "clang/Basic/Builtins.inc"
2501 const Expr *ProbArg = TheCall->getArg(2);
2505 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2507 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2508 << ProbArg->getSourceRange();
2519 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2520 << ProbArg->getSourceRange();
2550 TheCall->getBeginLoc(),
2551 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2555 TheCall->setType(Context.VoidPtrTy);
2569 QualType Param = FDecl->getParamDecl(0)->getType();
2570 QualType Result = FDecl->getReturnType();
2573 if (!(Param->isReferenceType() &&
2574 (ReturnsPointer ? Result->isAnyPointerType()
2575 : Result->isReferenceType()) &&
2576 Context.hasSameUnqualifiedType(Param->getPointeeType(),
2577 Result->getPointeeType()))) {
2578 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
2603 // OpenCL v2.0, s6.13.16 - Pipe functions
2648 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2675 // -Wframe-address warning if non-zero passed to builtin
2678 if (!TheCall->getArg(0)->isValueDependent() &&
2679 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2681 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2685 << TheCall->getSourceRange();
2701 QualType ArgTy = TheCall->getArg(0)->getType();
2704 if (auto *VecTy = EltTy->getAs<VectorType>())
2705 EltTy = VecTy->getElementType();
2706 if (EltTy->isUnsignedIntegerType()) {
2707 Diag(TheCall->getArg(0)->getBeginLoc(),
2743 QualType ArgTy = TheCall->getArg(0)->getType();
2744 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
2774 const Expr *Arg = TheCall->getArg(0);
2775 QualType ArgTy = Arg->getType();
2778 if (auto *VecTy = EltTy->getAs<VectorType>())
2779 EltTy = VecTy->getElementType();
2781 if (!EltTy->isIntegerType()) {
2782 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2799 const Expr *Arg = TheCall->getArg(0);
2800 QualType ArgTy = Arg->getType();
2803 if (auto *VecTy = EltTy->getAs<VectorType>())
2804 EltTy = VecTy->getElementType();
2806 if (!EltTy->isIntegerType()) {
2807 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2818 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
2819 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
2823 QualType MagnitudeTy = Magnitude.get()->getType();
2824 QualType SignTy = Sign.get()->getType();
2825 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
2827 checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),
2833 return Diag(Sign.get()->getBeginLoc(),
2838 TheCall->setArg(0, Magnitude.get());
2839 TheCall->setArg(1, Sign.get());
2840 TheCall->setType(Magnitude.get()->getType());
2848 const Expr *Arg = TheCall->getArg(0);
2849 const auto *TyA = Arg->getType()->getAs<VectorType>();
2853 ElTy = TyA->getElementType();
2854 else if (Arg->getType()->isSizelessVectorType())
2855 ElTy = Arg->getType()->getSizelessVectorEltType(Context);
2858 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2859 << 1 << /* vector ty*/ 4 << Arg->getType();
2863 TheCall->setType(ElTy);
2871 const Expr *Arg = TheCall->getArg(0);
2872 const auto *TyA = Arg->getType()->getAs<VectorType>();
2876 ElTy = TyA->getElementType();
2877 else if (Arg->getType()->isSizelessVectorType())
2878 ElTy = Arg->getType()->getSizelessVectorEltType(Context);
2880 if (ElTy.isNull() || !ElTy->isFloatingType()) {
2881 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2882 << 1 << /* vector of floating points */ 9 << Arg->getType();
2886 TheCall->setType(ElTy);
2891 // TODO: ADD/MUL should support floating-point types.
2900 const Expr *Arg = TheCall->getArg(0);
2901 const auto *TyA = Arg->getType()->getAs<VectorType>();
2905 ElTy = TyA->getElementType();
2906 else if (Arg->getType()->isSizelessVectorType())
2907 ElTy = Arg->getType()->getSizelessVectorEltType(Context);
2909 if (ElTy.isNull() || !ElTy->isIntegerType()) {
2910 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2911 << 1 << /* vector of integers */ 6 << Arg->getType();
2915 TheCall->setType(ElTy);
2935 if (TheCall->getNumArgs() != 1)
2937 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2940 auto *D = DRE->getDecl();
2943 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2944 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2947 Diag(TheCall->getBeginLoc(),
2964 Expr *Arg = TheCall->getArg(0);
2966 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) {
2967 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2968 << Arg->getSourceRange();
3006 Expr *Arg = TheCall->getArg(ArgNum);
3007 if (Arg->isTypeDependent() || Arg->isValueDependent())
3010 // Check constant-ness first.
3018 return Diag(TheCall->getBeginLoc(),
3020 << ArgNum << Arg->getSourceRange();
3025 if (Format->getFirstArg() == 0)
3026 FSI->ArgPassingKind = FAPK_VAList;
3028 FSI->ArgPassingKind = FAPK_Variadic;
3030 FSI->ArgPassingKind = FAPK_Fixed;
3031 FSI->FormatIdx = Format->getFormatIdx() - 1;
3032 FSI->FirstDataArg =
3033 FSI->ArgPassingKind == FAPK_VAList ? 0 : Format->getFirstArg() - 1;
3039 if(FSI->FormatIdx == 0)
3041 --FSI->FormatIdx;
3042 if (FSI->FirstDataArg != 0)
3043 --FSI->FirstDataArg;
3053 // const-evaluate them or not.
3060 // If the expression has non-null type, it doesn't evaluate to null.
3061 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3068 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3069 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
3071 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3072 Expr = ILE->getInit(0);
3076 return (!Expr->isValueDependent() &&
3077 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3087 << ArgExpr->getSourceRange());
3090 /// Determine whether the given type has a non-null nullability annotation.
3092 if (auto nullability = type->getNullability())
3112 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3113 if (!NonNull->args_size()) {
3116 if (S.isValidPointerAttrType(Arg->getType()))
3121 for (const ParamIdx &Idx : NonNull->args()) {
3137 parms = FD->parameters();
3139 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3145 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
3153 // If we have a non-function, non-method declaration but no
3157 QualType type = VD->getType().getNonReferenceType();
3158 if (auto pointerType = type->getAs<PointerType>())
3159 type = pointerType->getPointeeType();
3160 else if (auto blockType = type->getAs<BlockPointerType>())
3161 type = blockType->getPointeeType();
3165 Proto = type->getAs<FunctionProtoType>();
3169 // Fill in non-null argument information from the nullability
3173 for (auto paramType : Proto->getParamTypes()) {
3186 // Check for non-null arguments.
3190 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
3199 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
3205 if (ParamTy->isPointerType())
3206 ArgTy = ArgTy->getPointeeType();
3209 ParamTy = ParamTy->getPointeeType();
3213 if (ArgTy.isNull() || ParamTy->isDependentType() ||
3214 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
3215 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
3234 auto GetArgAt = [&](int Idx) -> const Expr * {
3240 return Args[Idx - IsMemberFunction];
3248 for (int CapturingParamIdx : Attr->params()) {
3260 for (unsigned I = 0; I < FD->getNumParams(); ++I)
3261 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
3265 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
3269 for (TypeLoc TL = TSI->getTypeLoc();
3281 if (CurContext->isDependentContext())
3287 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3300 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3301 unsigned NumParams = Proto ? Proto->getNumParams()
3303 ? cast<FunctionDecl>(FDecl)->getNumParams()
3305 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3323 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3331 const auto *FT = FDecl->getFunctionType();
3333 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
3338 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
3339 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
3344 if (Arg->containsErrors())
3348 FDecl->hasLinkage() &&
3349 FDecl->getFormalLinkage() != Linkage::Internal &&
3351 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
3353 QualType ParamTy = Proto->getParamType(ArgIdx);
3354 if (ParamTy->isSizelessVectorType())
3356 QualType ArgTy = Arg->getType();
3357 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
3364 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
3376 // If the call requires a streaming-mode change and has scalable vector
3378 // non-streaming vector lengths may be different.
3380 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
3409 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
3410 if (Attr && Attr->isNewZA())
3412 if (Attr && Attr->isNewZT0())
3414 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
3417 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3421 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3440 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
3441 auto *AA = FDecl->getAttr<AllocAlignAttr>();
3442 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
3443 if (!Arg->isValueDependent()) {
3445 if (Arg->EvaluateAsInt(Align, Context)) {
3448 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
3449 << Arg->getSourceRange();
3452 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
3453 << Arg->getSourceRange() << Sema::MaximumAlignment;
3463 if (ConceptDecl *Decl = AutoT->getTypeConstraintConcept()) {
3473 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3478 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
3491 TheCall->getCallee());
3492 Expr** Args = TheCall->getArgs();
3493 unsigned NumArgs = TheCall->getNumArgs();
3496 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
3502 --NumArgs;
3503 } else if (IsMemberFunction && !FDecl->isStatic() &&
3504 !FDecl->hasCXXExplicitFunctionObjectParameter())
3506 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3509 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
3511 QualType ThisType = ImplicitThis->getType();
3512 if (!ThisType->isPointerType()) {
3513 assert(!ThisType->isReferenceType());
3518 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
3520 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
3525 IsMemberFunction, TheCall->getRParenLoc(),
3526 TheCall->getCallee()->getSourceRange(), CallType);
3528 IdentifierInfo *FnInfo = FDecl->getIdentifier();
3535 if (FDecl->getBuiltinID() == 0)
3536 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
3545 unsigned CMId = FDecl->getMemoryFunctionKind();
3572 Ty = V->getType().getNonReferenceType();
3574 Ty = F->getType().getNonReferenceType();
3578 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3579 !Ty->isFunctionProtoType())
3583 if (!Proto || !Proto->isVariadic()) {
3585 } else if (Ty->isBlockPointerType()) {
3587 } else { // Ty->isFunctionPointerType()
3592 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3593 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3594 TheCall->getCallee()->getSourceRange(), CallType);
3601 TheCall->getCallee());
3603 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3604 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3605 TheCall->getCallee()->getSourceRange(), CallType);
3650 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3651 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
3652 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
3653 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
3661 // All the non-OpenCL operations take one of the following forms.
3883 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
3897 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3900 << Ptr->getType() << 0 << Ptr->getSourceRange();
3905 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3908 if (!AtomTy->isAtomicType()) {
3910 << Ptr->getType() << Ptr->getSourceRange();
3916 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3917 << Ptr->getSourceRange();
3920 ValType = AtomTy->castAs<AtomicType>()->getValueType();
3924 << Ptr->getType() << Ptr->getSourceRange();
3931 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
3937 << Ptr->getType() << 1 << Ptr->getSourceRange();
3942 // non-const pointer type, including void* and pointers to incomplete
3946 pointerType->getPointeeType().getCVRQualifiers());
3948 pointerType = PointerQT->getAs<PointerType>();
3953 // For an arithmetic operation, the implied arithmetic must be well-formed.
3958 unsigned AllowedType) -> bool {
3959 if (ValType->isIntegerType())
3961 if (ValType->isPointerType())
3963 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
3966 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
3979 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3982 if (IsC11 && ValType->isPointerType() &&
3983 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
3987 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3991 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3996 !AtomTy->isScalarType()) {
3997 // For GNU atomics, require a trivially-copyable type. This is not part of
3999 // other atomics which generally all require a trivially-copyable type. This
4002 << Ptr->getType() << Ptr->getSourceRange();
4018 << ValType << Ptr->getSourceRange();
4023 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4040 ByValType = Ptr->getType();
4085 // The first argument's non-CV pointer type is used to deduce the type of
4087 // - weak flag (always converted to bool)
4088 // - memory order (always converted to int)
4089 // - scope (always converted to int)
4101 // The second argument is the non-atomic operand. For arithmetic, this
4103 // passed by address. For the rest, GNU uses by-address and C11 uses
4104 // by-value.
4106 if (Form == Arithmetic && ValType->isPointerType())
4122 // Keep address space of non-atomic pointer type.
4124 ValArg->getType()->getAs<PointerType>()) {
4125 AS = PtrTy->getPointeeType().getAddressSpace();
4133 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4201 SubExprs[1]->getIntegerConstantExpr(Context);
4202 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
4203 Diag(SubExprs[1]->getBeginLoc(),
4206 << SubExprs[1]->getSourceRange();
4210 SubExprs[3]->getIntegerConstantExpr(Context)) {
4216 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
4217 Diag(SubExprs[3]->getBeginLoc(),
4219 << /*failure=*/2 << SubExprs[3]->getSourceRange();
4226 auto *Scope = Args[Args.size() - 1];
4228 Scope->getIntegerConstantExpr(Context)) {
4229 if (!ScopeModel->isValid(Result->getZExtValue()))
4230 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4231 << Scope->getSourceRange();
4246 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4253 if (ValType->isBitIntType()) {
4254 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
4261 /// checkBuiltinArgument - Given a call to a builtin function, perform
4262 /// normal type-checking on the given argument, updating the call in
4264 /// type-checking for some of its arguments but not necessarily all of
4269 FunctionDecl *Fn = E->getDirectCallee();
4272 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4276 ExprResult Arg = E->getArg(ArgIndex);
4281 E->setArg(ArgIndex, Arg.get());
4287 Expr *Callee = TheCall->getCallee();
4288 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4289 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4292 if (TheCall->getNumArgs() < 1) {
4293 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4294 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
4295 << Callee->getSourceRange();
4304 Expr *FirstArg = TheCall->getArg(0);
4309 TheCall->setArg(0, FirstArg);
4311 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4313 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4314 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4318 QualType ValType = pointerType->getPointeeType();
4319 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4320 !ValType->isBlockPointerType()) {
4321 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4322 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4327 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4328 << FirstArg->getType() << FirstArg->getSourceRange();
4341 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4342 << ValType << FirstArg->getSourceRange();
4392 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4393 << FirstArg->getType() << FirstArg->getSourceRange();
4401 unsigned BuiltinID = FDecl->getBuiltinID();
4569 if (TheCall->getNumArgs() < 1+NumFixed) {
4570 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4571 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
4572 << Callee->getSourceRange();
4576 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
4577 << Callee->getSourceRange();
4580 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
4581 << Callee->getSourceRange();
4594 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
4602 // The first argument --- the pointer --- has a fixed type; we
4606 ExprResult Arg = TheCall->getArg(i+1);
4609 // can fail in some cases (1i -> int**), check for this error case now.
4621 // for things like 45.123 -> char, etc.
4623 TheCall->setArg(i+1, Arg.get());
4628 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
4629 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
4630 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
4634 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4637 TheCall->setCallee(PromotedCall.get());
4642 TheCall->setType(ResultType);
4644 // Prohibit problematic uses of bit-precise integer types with atomic
4647 const auto *BitIntValType = ValType->getAs<BitIntType>();
4648 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
4649 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
4659 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4660 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4661 unsigned BuiltinID = FDecl->getBuiltinID();
4676 Expr *PointerArg = TheCall->getArg(numArgs - 1);
4683 TheCall->setArg(numArgs - 1, PointerArg);
4685 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4687 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
4688 << PointerArg->getType() << PointerArg->getSourceRange();
4692 QualType ValType = pointerType->getPointeeType();
4696 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4697 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4698 !ValType->isVectorType()) {
4699 Diag(DRE->getBeginLoc(),
4701 << PointerArg->getType() << PointerArg->getSourceRange();
4706 TheCall->setType(ValType);
4710 ExprResult ValArg = TheCall->getArg(0);
4717 TheCall->setArg(0, ValArg.get());
4718 TheCall->setType(Context.VoidTy);
4722 /// CheckObjCString - Checks that the format string argument to the os_log()
4725 Arg = Arg->IgnoreParenCasts();
4729 Literal = ObjcLiteral->getString();
4733 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
4735 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
4736 << Arg->getSourceRange());
4759 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
4763 return S.Diag(Fn->getBeginLoc(),
4766 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
4772 return S.Diag(Fn->getBeginLoc(),
4780 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
4786 // Determine whether the current function, block, or obj-c method is variadic
4792 IsVariadic = Block->isVariadic();
4793 Params = Block->parameters();
4795 IsVariadic = FD->isVariadic();
4796 Params = FD->parameters();
4798 IsVariadic = MD->isVariadic();
4800 Params = MD->parameters();
4803 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
4807 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
4812 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
4823 Expr *Fn = TheCall->getCallee();
4834 // Type-check the first argument normally.
4848 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
4850 TheCall->getArg(1)->getIntegerConstantExpr(Context);
4861 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
4864 Type = PV->getType();
4865 ParamLoc = PV->getLocation();
4867 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
4872 Diag(TheCall->getArg(1)->getBeginLoc(),
4874 else if (IsCRegister || Type->isReferenceType() ||
4875 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4880 if (!Type->isEnumeralType())
4882 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
4884 Context.typesAreCompatible(ED->getPromotionType(), Type));
4887 if (Type->isReferenceType()) Reason = 1;
4889 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
4897 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
4901 return Arg->getType()
4904 ->getPointeeType()
4915 Expr *Func = Call->getCallee();
4917 if (Call->getNumArgs() < 3)
4918 return Diag(Call->getEndLoc(),
4920 << 0 /*function call*/ << 3 << Call->getNumArgs()
4923 // Type-check the first argument normally.
4933 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4934 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4936 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4937 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4941 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
4942 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
4943 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
4946 << 2 << Arg1->getType() << ConstCharPtrTy;
4949 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4950 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
4951 << Arg2->getType() << SizeTy << 1 /* different class */
4954 << 3 << Arg2->getType() << SizeTy;
4964 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
4965 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
4966 << 1 << 0 << TheCall->getSourceRange();
4968 ExprResult OrigArg0 = TheCall->getArg(0);
4969 ExprResult OrigArg1 = TheCall->getArg(1);
4974 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
4981 TheCall->setArg(0, OrigArg0.get());
4982 TheCall->setArg(1, OrigArg1.get());
4984 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4989 if (Res.isNull() || !Res->isRealFloatingType())
4990 return Diag(OrigArg0.get()->getBeginLoc(),
4992 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4993 << SourceRange(OrigArg0.get()->getBeginLoc(),
4994 OrigArg1.get()->getEndLoc());
5004 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
5008 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5009 << 0 << 0 << TheCall->getSourceRange();
5013 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5014 << 1 << 0 << TheCall->getSourceRange();
5018 // Find out position of floating-point argument.
5019 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5021 // We can count on all parameters preceding the floating-point just being int.
5024 Expr *Arg = TheCall->getArg(i);
5026 if (Arg->isTypeDependent())
5034 TheCall->setArg(i, Res.get());
5037 Expr *OrigArg = TheCall->getArg(FPArgNo);
5039 if (OrigArg->isTypeDependent())
5044 // type how it is, but do normal L->Rvalue conversions.
5058 TheCall->setArg(FPArgNo, OrigArg);
5061 QualType ElementTy = OrigArg->getType();
5064 if (ElementTy->isVectorType() && IsFPClass) {
5066 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
5069 // This operation requires a non-_Complex floating-point number.
5070 if (!ElementTy->isRealFloatingType())
5071 return Diag(OrigArg->getBeginLoc(),
5073 << OrigArg->getType() << OrigArg->getSourceRange();
5088 TheCall->setType(ResultTy);
5100 Expr *Arg = TheCall->getArg(I);
5101 QualType T = Arg->getType();
5102 if (T->isDependentType()) {
5109 if (!T->isRealFloatingType()) {
5110 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5111 << Arg->getType() << Arg->getSourceRange();
5117 TheCall->setArg(I, Converted.get());
5121 TheCall->setType(Context.DependentTy);
5125 Expr *Real = TheCall->getArg(0);
5126 Expr *Imag = TheCall->getArg(1);
5127 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
5128 return Diag(Real->getBeginLoc(),
5130 << Real->getType() << Imag->getType()
5131 << Real->getSourceRange() << Imag->getSourceRange();
5137 if (Real->getType()->isFloat16Type())
5138 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
5140 if (Real->getType()->isHalfType())
5141 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
5144 TheCall->setType(Context.getComplexType(Real->getType()));
5148 /// BuiltinShuffleVector - Handle __builtin_shufflevector.
5151 if (TheCall->getNumArgs() < 2)
5152 return ExprError(Diag(TheCall->getEndLoc(),
5154 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5155 << /*is non object*/ 0 << TheCall->getSourceRange());
5160 QualType resType = TheCall->getArg(0)->getType();
5163 if (!TheCall->getArg(0)->isTypeDependent() &&
5164 !TheCall->getArg(1)->isTypeDependent()) {
5165 QualType LHSType = TheCall->getArg(0)->getType();
5166 QualType RHSType = TheCall->getArg(1)->getType();
5168 if (!LHSType->isVectorType() || !RHSType->isVectorType())
5170 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5171 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false
5172 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5173 TheCall->getArg(1)->getEndLoc()));
5175 numElements = LHSType->castAs<VectorType>()->getNumElements();
5176 unsigned numResElements = TheCall->getNumArgs() - 2;
5181 if (TheCall->getNumArgs() == 2) {
5182 if (!RHSType->hasIntegerRepresentation() ||
5183 RHSType->castAs<VectorType>()->getNumElements() != numElements)
5184 return ExprError(Diag(TheCall->getBeginLoc(),
5186 << TheCall->getDirectCallee()
5188 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5189 TheCall->getArg(1)->getEndLoc()));
5191 return ExprError(Diag(TheCall->getBeginLoc(),
5193 << TheCall->getDirectCallee()
5195 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5196 TheCall->getArg(1)->getEndLoc()));
5198 QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5204 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5205 if (TheCall->getArg(i)->isTypeDependent() ||
5206 TheCall->getArg(i)->isValueDependent())
5210 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
5211 return ExprError(Diag(TheCall->getBeginLoc(),
5213 << TheCall->getArg(i)->getSourceRange());
5215 // Allow -1 which will be translated to undef in the IR.
5216 if (Result->isSigned() && Result->isAllOnes())
5219 if (Result->getActiveBits() > 64 ||
5220 Result->getZExtValue() >= numElements * 2)
5221 return ExprError(Diag(TheCall->getBeginLoc(),
5223 << TheCall->getArg(i)->getSourceRange());
5228 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5229 exprs.push_back(TheCall->getArg(i));
5230 TheCall->setArg(i, nullptr);
5234 TheCall->getCallee()->getBeginLoc(),
5235 TheCall->getRParenLoc());
5243 QualType DstTy = TInfo->getType();
5244 QualType SrcTy = E->getType();
5246 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5249 << E->getSourceRange());
5250 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5255 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5256 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5257 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5261 << E->getSourceRange());
5269 unsigned NumArgs = TheCall->getNumArgs();
5272 return Diag(TheCall->getEndLoc(),
5275 << TheCall->getSourceRange();
5288 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
5289 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5292 Expr *Arg = TheCall->getArg(0);
5293 if (Arg->isInstantiationDependent())
5296 QualType ArgTy = Arg->getType();
5297 if (!ArgTy->hasFloatingRepresentation())
5298 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
5300 if (Arg->isLValue()) {
5302 TheCall->setArg(0, FirstArg.get());
5304 TheCall->setType(TheCall->getArg(0)->getType());
5309 Expr *Arg = TheCall->getArg(0);
5310 if (Arg->isInstantiationDependent()) return false;
5312 if (Arg->HasSideEffects(Context))
5313 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5314 << Arg->getSourceRange()
5315 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5322 Expr *Arg = TheCall->getArg(1);
5325 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5327 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5328 if (UE->getKind() == UETT_AlignOf ||
5329 UE->getKind() == UETT_PreferredAlignOf)
5330 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5331 << Arg->getSourceRange();
5333 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5336 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5337 << Arg->getSourceRange();
5340 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5341 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5344 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5345 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5355 unsigned NumArgs = TheCall->getNumArgs();
5356 Expr *FirstArg = TheCall->getArg(0);
5361 if (!FirstArgResult.get()->getType()->isPointerType()) {
5362 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
5363 << TheCall->getSourceRange();
5366 TheCall->setArg(0, FirstArgResult.get());
5370 Expr *SecondArg = TheCall->getArg(1);
5373 if (!SecondArg->isValueDependent()) {
5379 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5380 << SecondArg->getSourceRange();
5383 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5384 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
5388 Expr *ThirdArg = TheCall->getArg(2);
5391 TheCall->setArg(2, ThirdArg);
5399 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5402 unsigned NumArgs = TheCall->getNumArgs();
5405 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5407 << /*is non object*/ 0 << TheCall->getSourceRange();
5410 return Diag(TheCall->getEndLoc(),
5413 << /*is non object*/ 0 << TheCall->getSourceRange();
5419 ExprResult Arg(TheCall->getArg(i));
5425 TheCall->setArg(i, Arg.get());
5432 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5435 TheCall->setArg(i, Arg.get());
5443 TheCall->getArg(i), VariadicFunction, nullptr);
5446 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5448 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5450 << TheCall->getSourceRange();
5452 TheCall->setArg(i, Arg.get());
5456 // Check formatting specifiers. NOTE: We're only doing this for the non-size
5460 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5463 VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
5470 TheCall->setType(Context.getSizeType());
5472 TheCall->setType(Context.VoidPtrTy);
5479 Expr *Arg = TheCall->getArg(ArgNum);
5480 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5481 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5483 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5486 if (!(R = Arg->getIntegerConstantExpr(Context)))
5487 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5488 << FDecl->getDeclName() << Arg->getSourceRange();
5500 Expr *Arg = TheCall->getArg(ArgNum);
5501 if (Arg->isTypeDependent() || Arg->isValueDependent())
5504 // Check constant-ness first.
5510 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
5511 << toString(Result, 10) << Low << High << Arg->getSourceRange();
5515 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
5518 << Arg->getSourceRange());
5529 Expr *Arg = TheCall->getArg(ArgNum);
5530 if (Arg->isTypeDependent() || Arg->isValueDependent())
5533 // Check constant-ness first.
5538 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
5539 << Num << Arg->getSourceRange();
5548 Expr *Arg = TheCall->getArg(ArgNum);
5549 if (Arg->isTypeDependent() || Arg->isValueDependent())
5552 // Check constant-ness first.
5556 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
5558 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
5561 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
5562 << Arg->getSourceRange();
5592 Expr *Arg = TheCall->getArg(ArgNum);
5593 if (Arg->isTypeDependent() || Arg->isValueDependent())
5596 // Check constant-ness first.
5607 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
5608 << Arg->getSourceRange();
5616 Expr *Arg = TheCall->getArg(ArgNum);
5617 if (Arg->isTypeDependent() || Arg->isValueDependent())
5620 // Check constant-ness first.
5633 return Diag(TheCall->getBeginLoc(),
5635 << Arg->getSourceRange();
5640 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
5641 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5643 Expr *Arg = TheCall->getArg(1);
5651 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
5652 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
5659 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
5660 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5668 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
5673 // Specifically a pointer to a flexible array member:'ptr->array'. This
5676 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
5677 if (!isa<PointerType>(Arg->getType()) && !Arg->getType()->isArrayType())
5678 return Diag(Arg->getBeginLoc(),
5680 << Arg->getSourceRange();
5682 if (Arg->HasSideEffects(Context))
5683 return Diag(Arg->getBeginLoc(),
5685 << Arg->getSourceRange();
5688 if (!ME->isFlexibleArrayMemberLike(
5690 return Diag(Arg->getBeginLoc(),
5692 << Arg->getSourceRange();
5695 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
5696 CATy && CATy->getKind() == CountAttributedType::CountedBy) {
5697 const auto *FAMDecl = cast<FieldDecl>(ME->getMemberDecl());
5698 if (const FieldDecl *CountFD = FAMDecl->findCountedByField()) {
5699 TheCall->setType(Context.getPointerType(CountFD->getType()));
5704 return Diag(Arg->getBeginLoc(),
5706 << Arg->getSourceRange();
5709 TheCall->setType(Context.getPointerType(Context.VoidTy));
5718 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
5719 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
5725 Diag(E->getExprLoc(),
5727 << 0 << E->getSourceRange();
5730 Diag(E->getExprLoc(),
5732 << 1 << E->getSourceRange();
5735 Diag(E->getExprLoc(),
5737 << 2 << E->getSourceRange();
5740 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
5741 << 0 << E->getSourceRange();
5744 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
5745 << 1 << E->getSourceRange();
5755 enum { Unknown = -1, AllCovered = -2 };
5863 return FExpr->getString().drop_front(Offset);
5867 return FExpr->getByteLength() - getCharByteWidth() * Offset;
5870 unsigned getLength() const { return FExpr->getLength() - Offset; }
5871 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5873 StringLiteralKind getKind() const { return FExpr->getKind(); }
5875 QualType getType() const { return FExpr->getType(); }
5877 bool isAscii() const { return FExpr->isOrdinary(); }
5878 bool isWide() const { return FExpr->isWide(); }
5879 bool isUTF8() const { return FExpr->isUTF8(); }
5880 bool isUTF16() const { return FExpr->isUTF16(); }
5881 bool isUTF32() const { return FExpr->isUTF32(); }
5882 bool isPascal() const { return FExpr->isPascal(); }
5888 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5893 return FExpr->getBeginLoc().getLocWithOffset(Offset);
5896 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
5929 if (E->isTypeDependent() || E->isValueDependent())
5932 E = E->IgnoreParenCasts();
5934 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
5935 // Technically -Wformat-nonliteral does not warn about this case.
5941 switch (E->getStmtClass()) {
5944 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
5953 // The expression is a literal if both sub-expressions were, and it was
5954 // completely checked only if both sub-expressions were checked.
5958 // Determine whether it is necessary to check both sub-expressions, for
5964 if (C->getCond()->EvaluateAsBooleanCondition(
5980 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, APK, format_idx,
5990 S, C->getFalseExpr(), Args, APK, format_idx, firstDataArg, Type,
5998 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6002 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6019 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6021 QualType T = DR->getType();
6024 isConstant = AT->getElementType().isConstant(S.Context);
6025 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6027 PT->getPointeeType().isConstant(S.Context);
6028 } else if (T->isObjCObjectPointerType()) {
6035 if (const Expr *Init = VD->getAnyInitializer()) {
6038 if (InitList->isStringLiteralInit())
6039 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6085 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
6086 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
6089 IsCXXMember = MD->isInstance();
6092 if (const FunctionType *FnTy = D->getFunctionType())
6093 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
6095 IsVariadic = BD->isVariadic();
6097 IsVariadic = OMD->isVariadic();
6104 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx &&
6132 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6135 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6136 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6150 unsigned BuiltinID = FD->getBuiltinID();
6153 const Expr *Arg = CE->getArg(0);
6170 if (const auto *MD = ME->getMethodDecl()) {
6171 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6172 // As a special case heuristic, if we're using the method -[NSBundle
6180 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6181 IFace->getIdentifier()->isStr("NSBundle") &&
6182 MD->getSelector().isKeywordSelector(
6187 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6202 StrE = ObjCFExpr->getString();
6207 if (Offset.isNegative() || Offset > StrE->getLength()) {
6225 if (BinOp->isAdditiveOp()) {
6228 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6231 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6236 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6241 E = BinOp->getRHS();
6246 E = BinOp->getLHS();
6256 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6257 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6259 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6264 E = ASE->getBase();
6277 // If this expression can be evaluated at compile-time,
6283 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
6292 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6326 // CHECK: printf/scanf-like function is called with no format string.
6332 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6365 // so it is safe to pass a non-literal string.
6373 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6377 // If there are no arguments specified, warn with -Wformat-security, otherwise
6378 // warn only with -Wformat-nonliteral.
6381 << OrigFormatExpr->getSourceRange();
6399 << OrigFormatExpr->getSourceRange();
6512 return OrigFormatExpr->getSourceRange();
6518 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
6520 // Advance the end SourceLocation by one due to half-open ranges.
6527 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6557 << FixedLM->toString()
6558 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6591 << FixedLM->toString()
6592 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6619 << FixedCS->toString()
6620 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
6701 SourceLocation Loc = ArgExpr->getBeginLoc();
6708 PDiag << E->getSourceRange();
6713 DiagnosticExprs[0]->getSourceRange());
6740 // If the specifier in non-printable, it could be the first byte of a UTF-8
6741 // sequence. In that case, print the UTF-8 code point. If not, print the byte
6853 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6854 << ArgumentExpr->getSourceRange();
6865 //===--- CHECK: Printf format string checking -----------------------------===//
6981 QualType T = Arg->getType();
6989 << T << Arg->getSourceRange(),
7080 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7094 const RecordType *RT = Ty->getAs<RecordType>();
7099 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7100 if (!RD || !RD->getDefinition())
7109 if (S.LookupQualifiedName(R, RT->getDecl()))
7111 NamedDecl *decl = (*I)->getUnderlyingDecl();
7120 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7126 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7129 if ((*MI)->getMinRequiredArguments() == 0)
7142 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7147 if (Method->getMinRequiredArguments() == 0 &&
7148 AT.matchesType(S.Context, Method->getReturnType())) {
7150 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7151 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7222 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7225 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7226 << false << Ex->getSourceRange(),
7227 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7233 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7236 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7237 << false << Ex->getSourceRange(),
7238 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7244 // Check for using an Objective-C specific conversion specifier
7245 // in a non-ObjC literal.
7342 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7378 const Expr *Inside = E->IgnoreImpCasts();
7380 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7382 switch (Inside->getStmtClass()) {
7416 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7417 StringRef Name = UserTy->getDecl()->getName();
7429 TyTy = UserTy->desugar();
7435 PE->getSubExpr()->getType(),
7436 PE->getSubExpr());
7448 CO->getTrueExpr()->getType(),
7449 CO->getTrueExpr());
7452 CO->getFalseExpr()->getType(),
7453 CO->getFalseExpr());
7467 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
7471 QualType From = ICE->getSubExpr()->getType();
7472 QualType To = ICE->getType();
7475 if (ICE->getCastKind() == CK_IntegralCast &&
7481 if (const auto *VecTy = From->getAs<ExtVectorType>())
7482 From = VecTy->getElementType();
7483 if (const auto *VecTy = To->getAs<ExtVectorType>())
7484 To = VecTy->getElementType();
7486 return ICE->getCastKind() == CK_FloatingCast &&
7517 QualType ExprTy = E->getType();
7519 ExprTy = TET->getUnderlyingExpr()->getType();
7525 if (ExprTy->canDecayToPointerType())
7529 // -Wformat diagnostics, this is fine from a type perspective, but it still
7532 E->isKnownToHaveBooleanValue()) {
7540 E->getExprLoc(), false, CSR);
7545 // dumping raw class data (like is-a pointer), not actual data.
7547 ExprTy->isObjCObjectPointerType()) {
7551 E->getExprLoc(), false, CSR);
7559 Match = handleFormatSignedness(Match, S.getDiagnostics(), E->getExprLoc());
7573 E = ICE->getSubExpr();
7574 ExprTy = E->getType();
7579 if (ICE->getType() == S.Context.IntTy ||
7580 ICE->getType() == S.Context.UnsignedIntTy) {
7587 // might introduce new unexpected warnings from -Wformat-signedness.
7590 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
7603 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
7615 // For NSLog in ObjC, just preserve -Wformat behavior
7631 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7632 IntendedTy = EnumTy->getDecl()->getIntegerType();
7633 if (EnumTy->isUnscopedEnumerationType()) {
7643 // %C in an Objective-C context prints a unichar, not a wchar_t.
7648 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7649 !ExprTy->isCharType()) {
7657 const llvm::APInt &V = IL->getValue();
7662 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
7667 if (TD->getUnderlyingType() == IntendedTy)
7673 // Special-case some of Darwin's platform-independence types by suggesting
7713 llvm_unreachable("expected non-matching");
7729 << IntendedTy << IsEnum << E->getSourceRange(),
7730 E->getBeginLoc(),
7736 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
7737 // should be printed as 'long' for 64-bit compatibility.)
7750 E->getExprLoc());
7756 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
7761 // just write the C-style cast.
7763 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7768 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7772 SourceLocation EndLoc = S.SourceMgr.getSpellingLoc(E->getEndLoc());
7783 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
7784 Name = TypedefTy->getDecl()->getName();
7791 << E->getSourceRange(),
7792 E->getBeginLoc(), /*IsStringLocation=*/false,
7806 << IsEnum << E->getSourceRange(),
7807 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
7813 // Since the warning for passing non-POD types to variadic functions
7814 // was deferred until now, we emit a warning for non-POD
7826 llvm_unreachable("expected non-matching");
7840 << IsEnum << CSR << E->getSourceRange(),
7841 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7853 << E->getSourceRange(),
7854 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7862 else if (ExprTy->isObjCObjectType())
7867 << E->getSourceRange(),
7868 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7872 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
7874 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
7887 << E->getSourceRange(),
7888 E->getBeginLoc(), false, CSR);
7899 //===--- CHECK: Scanf format string checking ------------------------------===//
7936 getSpecifierRange(start, end - start));
7975 // Check if the field with is non-zero.
8036 AT.matchesType(S.Context, Ex->getType());
8037 Match = handleFormatSignedness(Match, S.getDiagnostics(), Ex->getExprLoc());
8043 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8058 << Ex->getType() << false << Ex->getSourceRange(),
8059 Ex->getBeginLoc(),
8067 << Ex->getType() << false << Ex->getSourceRange(),
8068 Ex->getBeginLoc(),
8084 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8087 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8088 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8092 // Str - The format string. NOTE: this is NOT null-terminated!
8093 StringRef StrRef = FExpr->getString();
8097 S.Context.getAsConstantArrayType(FExpr->getType());
8099 size_t TypeSize = T->getZExtSize();
8100 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8101 const unsigned numDataArgs = Args.size() - firstDataArg;
8114 FExpr->getBeginLoc(),
8115 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8123 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8124 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8154 // Str - The format string. NOTE: this is NOT null-terminated!
8155 StringRef StrRef = FExpr->getString();
8158 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8160 size_t TypeSize = T->getZExtSize();
8161 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8167 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8231 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8235 if (FT->getNumParams() != 1)
8238 return FT->getParamType(0);
8269 if (T->isIntegralOrEnumerationType())
8271 if (T->isRealFloatingType())
8273 if (T->isAnyComplexType())
8346 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8350 switch (FDecl->getBuiltinID()) {
8371 return FDecl->getBuiltinID();
8383 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8385 if (ArgType->isIntegralOrEnumerationType()) {
8387 } else if (ArgType->isRealFloatingType()) {
8402 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8410 if (FDecl->getNumParams() != 1)
8414 QualType ParamType = FDecl->getParamDecl(0)->getType();
8436 if (FD && FD->getBuiltinID() == AbsKind) {
8465 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8467 if (!FDecl->isInStdNamespace())
8493 if (FDecl->getName() != "infinity")
8497 const CXXRecordDecl *RDecl = MDecl->getParent();
8498 if (RDecl->getName() != "numeric_limits")
8502 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
8503 return NSDecl->isStdNamespace();
8511 if (!FDecl->getIdentifier())
8514 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
8517 IsInfOrNanFunction(FDecl->getName(), MathCheck::NaN))) {
8518 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
8519 << 1 << 0 << Call->getSourceRange();
8526 IsInfOrNanFunction(FDecl->getName(), MathCheck::Inf))) {
8527 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
8528 << 0 << 0 << Call->getSourceRange();
8534 if (Call->getNumArgs() != 1)
8542 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8543 QualType ParamType = Call->getArg(0)->getType();
8547 if (ArgType->isUnsignedIntegerType()) {
8550 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8551 Diag(Call->getExprLoc(), diag::note_remove_abs)
8553 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8559 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8561 if (ArgType->isFunctionType())
8563 else if (ArgType->isArrayType())
8566 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8585 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8591 emitReplacement(*this, Call->getExprLoc(),
8592 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8604 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8607 emitReplacement(*this, Call->getExprLoc(),
8608 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8611 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8618 if (Call->getExprLoc().isMacroID()) return;
8621 if (Call->getNumArgs() != 2) return;
8623 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8625 if (ArgList->size() != 1) return;
8628 const auto& TA = ArgList->get(0);
8631 if (!ArgType->isUnsignedIntegerType()) return;
8634 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8637 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
8639 if (Num->getValue() != 0) return false;
8643 const Expr *FirstArg = Call->getArg(0);
8644 const Expr *SecondArg = Call->getArg(1);
8651 SourceRange FirstRange = FirstArg->getSourceRange();
8652 SourceRange SecondRange = SecondArg->getSourceRange();
8656 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8657 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8663 SecondRange.getBegin().getLocWithOffset(-1));
8669 Diag(Call->getExprLoc(), diag::note_remove_max_call)
8670 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8674 //===--- CHECK: Standard memory functions ---------------------------------===//
8689 if (!Size->isComparisonOp() && !Size->isLogicalOp())
8692 SourceRange SizeRange = Size->getSourceRange();
8693 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8698 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
8713 const Type *Ty = T->getBaseElementTypeUnsafe();
8716 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8717 RD = RD ? RD->getDefinition() : nullptr;
8718 if (!RD || RD->isInvalidDecl())
8721 if (RD->isDynamicClass())
8727 for (auto *FD : RD->fields()) {
8730 getContainedDynamicClass(FD->getType(), SubContained)) {
8741 if (Unary->getKind() == UETT_SizeOf)
8750 if (!SizeOf->isArgumentType())
8751 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
8758 return SizeOf->getTypeOfArgument();
8788 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8789 visit(FD->getType(), FD->getLocation());
8830 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8831 visit(FD->getType(), FD->getLocation());
8856 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
8859 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
8862 return doesExprLikelyComputeSize(BO->getLHS()) ||
8863 doesExprLikelyComputeSize(BO->getRHS());
8896 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
8900 cast<IntegerLiteral>(E)->getValue() == 0) ||
8902 cast<CharacterLiteral>(E)->getValue() == 0);
8906 SourceLocation CallLoc = Call->getRParenLoc();
8909 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
8911 SourceLocation DiagLoc = SizeArg->getExprLoc();
8920 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
8931 doesExprLikelyComputeSize(Call->getArg(1)) &&
8932 !doesExprLikelyComputeSize(Call->getArg(2))) {
8933 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
8945 // It is possible to have a non-standard definition of memset. Validate
8949 if (Call->getNumArgs() < ExpectedNumArgs)
8956 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
8959 Call->getBeginLoc(), Call->getRParenLoc()))
8973 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8974 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
8978 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
8979 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
8981 QualType DestTy = Dest->getType();
8983 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
8984 PointeeTy = DestPtrTy->getPointeeType();
8988 if (PointeeTy->isVoidType())
8991 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
8997 SizeOfArg->getExprLoc())) {
9001 SizeOfArg->Profile(SizeOfArgID, Context, true);
9003 Dest->Profile(DestID, Context, true);
9008 StringRef ReadableName = FnName->getName();
9011 if (UnaryOp->getOpcode() == UO_AddrOf)
9012 ActionIdx = 1; // If its an address-of operator, just remove it.
9013 if (!PointeeTy->isIncompleteType() &&
9020 SourceLocation SL = SizeOfArg->getExprLoc();
9021 SourceRange DSR = Dest->getSourceRange();
9022 SourceRange SSR = SizeOfArg->getSourceRange();
9051 // type as the memory argument, and where it points to a user-defined
9054 if (PointeeTy->isRecordType() &&
9056 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9059 << PointeeTy << Dest->getSourceRange()
9060 << LenExpr->getSourceRange());
9064 } else if (DestTy->isArrayType()) {
9089 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9093 << Call->getCallee()->getSourceRange());
9097 Dest->getExprLoc(), Dest,
9100 << Call->getCallee()->getSourceRange());
9101 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9108 RT->isIncompleteType() ||
9109 RT->desugar().isTriviallyCopyableType(Context);
9112 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9113 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9121 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9125 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9126 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9134 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9144 Dest->getExprLoc(), Dest,
9155 Ex = Ex->IgnoreParenCasts();
9159 if (!BO || !BO->isAdditiveOp())
9162 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9163 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9178 // Only handle constant-sized or VLAs, but not flexible members.
9181 if (CAT->getZExtSize() <= 1)
9183 } else if (!Ty->isVariableArrayType()) {
9193 unsigned NumArgs = Call->getNumArgs();
9197 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9198 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9202 Call->getBeginLoc(), Call->getRParenLoc()))
9211 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9212 SizeCall->getNumArgs() == 1)
9213 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9230 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9233 const Expr *OriginalSizeArg = Call->getArg(2);
9234 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9235 << OriginalSizeArg->getSourceRange() << FnName;
9240 // we could say 'sizeof(array)-2'.
9241 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9242 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9248 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9251 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9252 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9260 return D1->getDecl() == D2->getDecl();
9266 const FunctionDecl *FD = CE->getDirectCallee();
9267 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9269 return CE->getArg(0)->IgnoreParenCasts();
9277 if (CE->getNumArgs() < 3)
9279 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9280 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9281 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9283 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9284 CE->getRParenLoc()))
9291 // - sizeof(dst)
9294 // - sizeof(src)
9298 if (BE->getOpcode() == BO_Sub) {
9299 const Expr *L = BE->getLHS()->IgnoreParenCasts();
9300 const Expr *R = BE->getRHS()->IgnoreParenCasts();
9301 // - sizeof(dst) - strlen(dst)
9305 // - sizeof(src) - (anything)
9315 SourceLocation SL = LenArg->getBeginLoc();
9316 SourceRange SR = LenArg->getSourceRange();
9327 QualType DstTy = DstArg->getType();
9346 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9347 OS << ") - ";
9349 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9350 OS << ") - 1";
9360 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
9368 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
9369 const Decl *D = Lvalue->getDecl();
9371 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
9375 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
9377 Lvalue->getMemberDecl());
9383 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
9387 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
9393 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
9397 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
9406 clang::CastKind Kind = Cast->getCastKind();
9407 if (Kind == clang::CK_BitCast &&
9408 !Cast->getSubExpr()->getType()->isFunctionPointerType())
9410 if (Kind == clang::CK_IntegralToPointer &&
9412 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
9415 switch (Cast->getCastKind()) {
9416 case clang::CK_BitCast:
9417 case clang::CK_IntegralToPointer:
9418 case clang::CK_FunctionToPointerDecay:
9420 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
9427 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
9434 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
9437 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
9439 switch (UnaryExpr->getOpcode()) {
9449 if (Lvalue->getType()->isArrayType())
9453 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
9454 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
9459 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
9465 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
9480 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9483 // If an allocation function declared with a non-throwing
9484 // exception-specification fails to allocate storage, it shall return
9488 OverloadedOperatorKind Op = FD->getOverloadedOperator();
9491 = FD->getType()->castAs<FunctionProtoType>();
9492 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9499 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
9503 // PPC MMA non-pointer types are not allowed as return type. Checking the type
9506 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
9518 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
9519 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
9524 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
9525 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
9526 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
9527 TargetTy->isFloatingPoint()) {
9529 llvm::APFloat TargetC = FPLiteral->getValue();
9537 << LHS->getSourceRange() << RHS->getSourceRange();
9543 // Match a more general floating-point equality comparison (-Wfloat-equal).
9544 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9545 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9551 if (DRL->getDecl() == DRR->getDecl())
9560 if (FLL->isExact())
9564 if (FLR->isExact())
9569 if (CL->getBuiltinCallee())
9573 if (CR->getBuiltinCallee())
9578 << LHS->getSourceRange() << RHS->getSourceRange();
9581 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9582 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9586 /// Structure recording the 'active' range of an integer-valued
9603 return NonNegative ? Width : Width - 1;
9614 T->getCanonicalTypeInternal().getTypePtr());
9619 assert(T->isCanonicalUnqualified());
9622 T = VT->getElementType().getTypePtr();
9624 T = CT->getElementType().getTypePtr();
9626 T = AT->getValueType().getTypePtr();
9631 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9634 EnumDecl *Enum = ET->getDecl();
9637 if (Enum->isFixed()) {
9639 !ET->isSignedIntegerOrEnumerationType());
9642 unsigned NumPositive = Enum->getNumPositiveBits();
9643 unsigned NumNegative = Enum->getNumNegativeBits();
9653 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9656 assert(BT->isInteger());
9658 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9667 assert(T->isCanonicalUnqualified());
9670 T = VT->getElementType().getTypePtr();
9672 T = CT->getElementType().getTypePtr();
9674 T = AT->getValueType().getTypePtr();
9676 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9679 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9682 assert(BT->isInteger());
9684 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9694 /// Return the range of a bitwise-AND of the two ranges.
9718 // We need a 1-bit-wider range if:
9731 // -2^L * -2^R = 2^(L + R)
9790 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9794 QualType Ty = E->getType();
9795 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9796 Ty = AtomicRHS->getValueType();
9817 E = E->IgnoreParens();
9821 if (E->EvaluateAsRValue(result, C, InConstantContext))
9828 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9829 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
9834 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9835 CE->getCastKind() == CK_BooleanToSignedIntegral;
9837 // Assume that non-integer casts can span the full range of the type.
9842 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
9848 if (SubRange->Width >= OutputTypeRange.Width)
9851 // Otherwise, we take the smaller width, and we're non-negative if
9853 return IntRange(SubRange->Width,
9854 SubRange->NonNegative || OutputTypeRange.NonNegative);
9860 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9862 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
9868 Expr *TrueExpr = CO->getTrueExpr();
9869 if (TrueExpr->getType()->isVoidType())
9877 Expr *FalseExpr = CO->getFalseExpr();
9878 if (FalseExpr->getType()->isVoidType())
9892 switch (BO->getOpcode()) {
9896 // Boolean-valued operations are single-bit and positive.
9923 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
9926 // Operations with opaque sources are black-listed.
9931 // Bitwise-and uses the *infinum* of the two source ranges.
9937 // Left shift gets black-listed based on a judgement call.
9942 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9943 if (I->getValue() == 1) {
9957 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
9964 BO->getRHS()->getIntegerConstantExpr(C)) {
9965 if (shift->isNonNegative()) {
9966 if (shift->uge(L->Width))
9967 L->Width = (L->NonNegative ? 0 : 1);
9969 L->Width -= shift->getZExtValue();
9978 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
9987 if (BO->getLHS()->getType()->isPointerType())
10001 // Don't 'pre-truncate' the operands.
10004 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
10010 BO->getRHS()->getIntegerConstantExpr(C)) {
10011 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10012 if (log2 >= L->Width)
10013 L->Width = (L->NonNegative ? 0 : 1);
10015 L->Width = std::min(L->Width - log2, MaxWidth);
10021 // could be -1.
10023 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
10027 return IntRange(L->Width, L->NonNegative && R->NonNegative);
10044 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
10049 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
10055 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
10061 switch (UO->getOpcode()) {
10062 // Boolean-valued operations are white-listed.
10066 // Operations with opaque sources are black-listed.
10072 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
10078 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
10081 if (const auto *BitField = E->getSourceBitField())
10082 return IntRange(BitField->getBitWidthValue(),
10083 BitField->getType()->isUnsignedIntegerOrEnumerationType());
10085 if (GetExprType(E)->isVoidType())
10142 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10143 if (isa<EnumConstantDecl>(DR->getDecl()))
10148 // and Objective-C.
10149 SourceLocation BeginLoc = E->getBeginLoc();
10161 return E->getType()->isIntegerType() &&
10162 (!E->getType()->isSignedIntegerType() ||
10163 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10170 /// |-----------| . . . |-----------|
10188 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10239 case -1: return Less;
10243 case -1: return InRange;
10294 if (ICE->getCastKind() != CK_IntegralCast &&
10295 ICE->getCastKind() != CK_NoOp)
10297 E = ICE->getSubExpr();
10300 return E->getType()->isEnumeralType();
10312 return BL->getValue() ? ConstantValueKind::LiteralTrue
10326 Constant = Constant->IgnoreParenImpCasts();
10327 Other = Other->IgnoreParenImpCasts();
10331 // - If the constant is outside the range of representable values of
10334 // - If the constant is the maximum / minimum in-range value. For an
10336 if (Constant->getType()->isEnumeralType() &&
10337 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10345 QualType OtherT = Other->getType();
10346 if (const auto *AT = OtherT->getAs<AtomicType>())
10347 OtherT = AT->getValueType();
10353 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
10354 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10359 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10368 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10379 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
10387 // Don't warn if the non-constant operand actually always evaluates to the
10389 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
10392 // Suppress the diagnostic for an in-range comparison if the constant comes
10402 // A comparison of an unsigned bit-field against 0 is really a type problem,
10403 // even though at the type level the bit-field might promote to 'signed int'.
10404 if (Other->refersToBitField() && InRange && Value == 0 &&
10405 Other->getType()->isUnsignedIntegerOrEnumerationType())
10412 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10420 Constant->IgnoreParenImpCasts())) {
10421 OS << (BL->getValue() ? "YES" : "NO");
10427 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
10428 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
10429 << E->getOpcodeStr() << OS.str() << *Result
10430 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10435 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10441 // FIXME: We use a somewhat different formatting for the in-range cases and
10444 if (!InRange || Other->isKnownToHaveBooleanValue()) {
10447 E->getOperatorLoc(), E,
10452 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10463 S.Diag(E->getOperatorLoc(), Diag)
10464 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10465 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10474 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10475 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10478 /// Implements -Wsign-compare.
10483 QualType T = E->getLHS()->getType();
10487 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10490 // Don't analyze value-dependent comparisons directly.
10491 if (E->isValueDependent())
10494 Expr *LHS = E->getLHS();
10495 Expr *RHS = E->getRHS();
10497 if (T->isIntegralType(S.Context)) {
10499 RHS->getIntegerConstantExpr(S.Context);
10501 LHS->getIntegerConstantExpr(S.Context);
10522 if (!T->hasUnsignedIntegerRepresentation()) {
10529 LHS = LHS->IgnoreParenImpCasts();
10530 RHS = RHS->IgnoreParenImpCasts();
10536 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10537 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10538 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10539 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10545 if (LHS->getType()->hasSignedIntegerRepresentation()) {
10546 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10550 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10566 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10567 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10569 // If the signed range is non-negative, -Wsign-compare won't fire.
10570 if (signedRange->NonNegative)
10577 if (E->isEqualityOp()) {
10586 // non-negative.
10587 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
10589 if (unsignedRange->Width < comparisonWidth)
10593 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10595 << LHS->getType() << RHS->getType()
10596 << LHS->getSourceRange() << RHS->getSourceRange());
10604 assert(Bitfield->isBitField());
10605 if (Bitfield->isInvalidDecl())
10608 // White-list bool bitfields.
10609 QualType BitfieldType = Bitfield->getType();
10610 if (BitfieldType->isBooleanType())
10613 if (BitfieldType->isEnumeralType()) {
10614 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10619 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10620 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10621 BitfieldEnumDecl->getNumNegativeBits() == 0) {
10627 // Ignore value- or type-dependent expressions.
10628 if (Bitfield->getBitWidth()->isValueDependent() ||
10629 Bitfield->getBitWidth()->isTypeDependent() ||
10630 Init->isValueDependent() ||
10631 Init->isTypeDependent())
10634 Expr *OriginalInit = Init->IgnoreParenImpCasts();
10635 unsigned FieldWidth = Bitfield->getBitWidthValue();
10638 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10643 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10644 EnumDecl *ED = EnumTy->getDecl();
10645 bool SignedBitfield = BitfieldType->isSignedIntegerType();
10650 bool SignedEnum = ED->getNumNegativeBits() > 0;
10661 ED->getNumPositiveBits() == FieldWidth) {
10667 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10669 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10670 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10677 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10678 ED->getNumNegativeBits())
10679 : ED->getNumPositiveBits();
10683 Expr *WidthExpr = Bitfield->getBitWidth();
10686 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10687 << BitsNeeded << ED << WidthExpr->getSourceRange();
10700 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
10701 // to a one-bit bit-field to see if the value came from a macro named 'true'.
10704 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
10712 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10720 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10733 << PrettyValue << PrettyTrunc << OriginalInit->getType()
10734 << Init->getSourceRange();
10739 /// Analyze the given simple or compound assignment for warning-worthy
10743 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10747 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10748 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10749 E->getOperatorLoc())) {
10751 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10752 E->getOperatorLoc());
10756 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10758 // Diagnose implicitly sequentially-consistent atomic assignment.
10759 if (E->getLHS()->getType()->isAtomicType())
10760 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10768 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10770 << SourceType << T << E->getSourceRange()
10774 S.Diag(E->getExprLoc(), diag)
10775 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10782 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10788 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10791 Expr *InnerE = E->IgnoreParenImpCasts();
10792 // We also want to warn on, e.g., "int i = -1.234"
10794 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10795 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10802 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10807 << E->getType());
10817 T->hasUnsignedIntegerRepresentation());
10843 // Conversion of a floating-point value to a non-bool integer where the
10857 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
10861 // Warn on non-zero to zero conversion.
10887 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10889 << E->getType() << T.getUnqualifiedType()
10891 << E->getSourceRange() << SourceRange(CContext));
10893 S.Diag(E->getExprLoc(), DiagID)
10894 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10895 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10900 /// floating-point precision.
10905 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10906 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10908 if (E->getLHS()->getType()->isAtomicType())
10909 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10912 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10914 ->getComputationResultType()
10915 ->getAs<BuiltinType>();
10918 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10921 if (ResultBT->isInteger())
10922 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10923 E->getExprLoc(), diag::warn_impcast_float_integer);
10925 if (!ResultBT->isFloatingPoint())
10931 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10933 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10951 Expr *InnerE = Ex->IgnoreParenImpCasts();
10952 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10954 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10955 if (Target->isDependentType())
10962 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10963 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10968 unsigned NumArgs = TheCall->getNumArgs();
10970 Expr *CurrA = TheCall->getArg(i);
10975 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10976 IsSwapped |= ((i < (NumArgs - 1)) &&
10977 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10979 // Warn on this floating-point to bool conversion.
10980 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10981 CurrA->getType(), CC,
10990 E->getExprLoc()))
10998 const Expr *NewE = E->IgnoreParenImpCasts();
11000 bool HasNullPtrType = NewE->getType()->isNullPtrType();
11005 if (T->isAnyPointerType() || T->isBlockPointerType() ||
11006 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11009 SourceLocation Loc = E->getSourceRange().getBegin();
11036 // Don't warn on char array initialization or for non-decimal values.
11042 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11044 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11051 if (CC.isValid() && T->isCharType()) {
11065 if (UO->getOpcode() == UO_Minus)
11066 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11074 E = E->IgnoreParenImpCasts();
11075 SourceLocation ExprLoc = E->getExprLoc();
11078 BinaryOperator::Opcode Opc = BO->getOpcode();
11082 const auto *LHS = getIntegerLiteral(BO->getLHS());
11083 const auto *RHS = getIntegerLiteral(BO->getRHS());
11084 if (LHS && LHS->getValue() == 0)
11086 else if (!E->isValueDependent() && LHS && RHS &&
11087 RHS->getValue().isNonNegative() &&
11088 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11091 else if (E->getType()->isSignedIntegerType())
11097 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11098 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11101 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11102 (RHS->getValue() == 0 || RHS->getValue() == 1))
11105 if (LHS->getValue() != 0 && RHS->getValue() != 0)
11112 if (E->isTypeDependent() || E->isValueDependent()) return;
11114 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
11117 if (Target->isDependentType()) return;
11127 if (Source->isAtomicType())
11128 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11131 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11140 // This covers the literal expressions that evaluate to Objective-C
11145 if (Source->isPointerType() || Source->canDecayToPointerType()) {
11155 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
11157 if (E->EvaluateAsInt(Result, getASTContext(), Expr::SE_AllowSideEffects)) {
11167 // Check implicit casts from Objective-C collection literals to specialized
11176 if (Target->isSveVLSBuiltinType() &&
11183 if (Target->isRVVVLSBuiltinType() &&
11195 Target->castAs<VectorType>()->getNumElements() <
11196 Source->castAs<VectorType>()->getNumElements()) {
11209 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11210 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11213 Target = VecTy->getElementType().getTypePtr();
11218 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11227 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11228 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11235 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
11238 // Handle conversion from scalable to fixed when msve-vector-bits is
11251 Source = SourceBT->getSveEltType(Context).getTypePtr();
11254 if (TargetBT && TargetBT->isSveVLSBuiltinType())
11255 Target = TargetBT->getSveEltType(Context).getTypePtr();
11258 if (SourceBT && SourceBT->isFloatingPoint()) {
11260 if (TargetBT && TargetBT->isFloatingPoint()) {
11269 if (E->EvaluateAsRValue(result, Context)) {
11294 if (TargetBT && TargetBT->isInteger()) {
11301 // Detect the case where a call result is converted from floating-point to
11308 // way to detect this class of misplaced-parentheses bug?
11309 if (Target->isBooleanType() && isa<CallExpr>(E)) {
11314 if (unsigned NumArgs = CEx->getNumArgs()) {
11315 Expr *LastA = CEx->getArg(NumArgs - 1);
11316 Expr *InnerE = LastA->IgnoreParenImpCasts();
11318 InnerE->getType()->isBooleanType()) {
11319 // Warn on this floating-point to bool conversion
11329 if (Source->isFixedPointType()) {
11330 if (Target->isUnsaturatedFixedPointType()) {
11332 if (E->EvaluateAsFixedPoint(Result, Context, Expr::SE_AllowSideEffects,
11338 DiagRuntimeBehavior(E->getExprLoc(), E,
11341 << E->getSourceRange()
11342 << clang::SourceRange(CC));
11346 } else if (Target->isIntegerType()) {
11349 E->EvaluateAsFixedPoint(Result, Context, Expr::SE_AllowSideEffects)) {
11354 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
11358 DiagRuntimeBehavior(E->getExprLoc(), E,
11361 << E->getSourceRange()
11362 << clang::SourceRange(CC));
11367 } else if (Target->isUnsaturatedFixedPointType()) {
11368 if (Source->isIntegerType()) {
11371 E->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) {
11379 DiagRuntimeBehavior(E->getExprLoc(), E,
11382 << E->getSourceRange()
11383 << clang::SourceRange(CC));
11391 // initialization-list syntax, we might lose accuracy if the floating
11393 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11394 TargetBT->isFloatingType() && !IsListInit) {
11401 unsigned int SourcePrecision = SourceRange->Width;
11412 E->getIntegerConstantExpr(Context)) {
11420 *SourceInt, SourceBT->isSignedInteger(),
11425 SourceInt->toString(PrettySourceValue, 10);
11430 E->getExprLoc(), E,
11432 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11433 << E->getSourceRange() << clang::SourceRange(CC));
11447 if (Target->isBooleanType())
11450 if (!Source->isIntegerType() || !Target->isIntegerType())
11453 // TODO: remove this early return once the false positives for constant->bool
11455 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11458 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
11459 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11462 << E->getType());
11473 if (LikelySourceRange->Width > TargetRange.Width) {
11474 // If the source is a constant, use a default-on diagnostic.
11477 if (E->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects,
11488 DiagRuntimeBehavior(E->getExprLoc(), E,
11491 << E->getType() << T << E->getSourceRange()
11496 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11500 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
11509 if (UO->getOpcode() == UO_Minus)
11510 if (Source->isUnsignedIntegerType()) {
11511 if (Target->isUnsignedIntegerType())
11514 if (Target->isSignedIntegerType())
11520 if (TargetRange.Width == LikelySourceRange->Width &&
11521 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
11522 Source->isSignedIntegerType()) {
11528 if (E->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects) &&
11535 Diag(E->getExprLoc(),
11537 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11538 << E->getSourceRange() << SourceRange(CC));
11543 // Fall through for non-constants to give a sign conversion warning.
11547 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
11548 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
11549 LikelySourceRange->Width == TargetRange.Width))) {
11553 if (SourceBT && SourceBT->isInteger() && TargetBT &&
11554 TargetBT->isInteger() &&
11555 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
11561 // Traditionally, gcc has warned about this under -Wsign-compare.
11562 // We also want to warn about it in -Wconversion.
11563 // So if -Wconversion is off, use a completely identical diagnostic
11564 // in the sign-compare group.
11565 // The conditional-checking code will
11577 QualType SourceType = E->getEnumCoercedType(Context);
11580 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11581 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11582 if (SourceEnum->getDecl()->hasNameForLinkage() &&
11583 TargetEnum->getDecl()->hasNameForLinkage() &&
11598 E = E->IgnoreParenImpCasts();
11600 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
11607 if (E->getType() != T)
11613 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11615 Expr *TrueExpr = E->getTrueExpr();
11617 TrueExpr = BCO->getCommon();
11621 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11623 if (T->isBooleanType())
11626 // If -Wconversion would have warned about either of the candidates
11636 if (E->getType() == T) return;
11639 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
11642 S.CheckImplicitConversion(E->getFalseExpr()->IgnoreParenImpCasts(),
11643 E->getType(), CC, &Suspicious);
11649 // Run the bool-like conversion checks only for C since there bools are
11654 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11656 S.CheckImplicitConversion(E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11675 QualType T = OrigE->getType();
11676 Expr *E = OrigE->IgnoreParenImpCasts();
11679 // If so, we do not issue warnings for implicit int-float conversion
11684 if (E->isTypeDependent() || E->isValueDependent())
11693 if (auto *Src = OVE->getSourceExpr())
11697 if (UO->getOpcode() == UO_Not &&
11698 UO->getSubExpr()->isKnownToHaveBooleanValue())
11699 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11700 << OrigE->getSourceRange() << T->isBooleanType()
11701 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11704 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
11705 BO->getLHS()->isKnownToHaveBooleanValue() &&
11706 BO->getRHS()->isKnownToHaveBooleanValue() &&
11707 BO->getLHS()->HasSideEffects(S.Context) &&
11708 BO->getRHS()->HasSideEffects(S.Context)) {
11711 SourceLocation BLoc = BO->getOperatorLoc();
11713 StringRef SR = clang::Lexer::getSourceText(
11714 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
11721 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
11722 << (BO->getOpcode() == BO_And ? "&" : "|")
11723 << OrigE->getSourceRange()
11725 BO->getOperatorLoc(),
11726 (BO->getOpcode() == BO_And ? "&&" : "||"));
11727 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
11743 // The non-canonical typecheck is just an optimization;
11745 if (SourceExpr->getType() != T)
11754 for (auto *SE : POE->semantics())
11756 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
11761 E = CE->getSubExpr()->IgnoreParenImpCasts();
11762 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11763 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11769 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
11773 if (OutArgE->isInOut())
11775 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
11776 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
11782 if (BO->isComparisonOp())
11786 if (BO->getOpcode() == BO_Assign)
11789 if (BO->isAssignmentOp())
11793 // These break the otherwise-useful invariant below. Fortunately,
11803 CC = E->getExprLoc();
11805 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11806 for (Stmt *SubStmt : E->children()) {
11812 if (ChildExpr == CSE->getOperand())
11819 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11826 if (BO && BO->isLogicalOp()) {
11827 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11829 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11831 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11833 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11837 if (U->getOpcode() == UO_LNot) {
11838 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11839 } else if (U->getOpcode() != UO_AddrOf) {
11840 if (U->getSubExpr()->getType()->isAtomicType())
11841 S.Diag(U->getSubExpr()->getBeginLoc(),
11847 /// AnalyzeImplicitConversions - Find and report any interesting
11849 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11862 E = E->IgnoreParenImpCasts();
11867 if (!DRE->getDecl()->getType()->isReferenceType())
11870 if (!M->getMemberDecl()->getType()->isReferenceType())
11873 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11875 FD = Call->getDirectCallee();
11880 SemaRef.Diag(E->getExprLoc(), PD);
11884 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11892 // expansion, or is from expanded from a top-level macro argument.
11913 if (E->getExprLoc().isMacroID()) {
11915 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11919 E = E->IgnoreImpCasts();
11926 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11932 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
11933 if (UO->getOpcode() != UO_AddrOf)
11936 E = UO->getSubExpr();
11943 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11954 E->printPretty(S, nullptr, getPrintingPolicy());
11957 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11958 << E->getSourceRange() << Range << IsEqual;
11959 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11963 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11964 if (auto *Callee = Call->getDirectCallee()) {
11965 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11976 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
11977 MRecordDecl && MRecordDecl->isLambda()) {
11978 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
11980 << MRecordDecl->getSourceRange() << Range << IsEqual;
11989 D = R->getDecl();
11991 D = M->getMemberDecl();
11995 if (!D || D->isWeak())
12001 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12002 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12007 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12009 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12011 auto ParamIter = llvm::find(FD->parameters(), PV);
12012 assert(ParamIter != FD->param_end());
12013 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12015 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12016 if (!NonNull->args_size()) {
12021 for (const ParamIdx &ArgNo : NonNull->args()) {
12032 QualType T = D->getType();
12033 const bool IsArray = T->isArrayType();
12034 const bool IsFunction = T->isFunctionType();
12048 E->printPretty(S, nullptr, getPrintingPolicy());
12065 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12072 Diag(E->getExprLoc(), diag::note_function_warning_silence)
12073 << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12086 if (!ReturnType->isPointerType()) {
12089 if (!ReturnType->isIntegerType())
12098 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12101 Diag(E->getExprLoc(), diag::note_function_to_function_call)
12102 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12110 // Don't diagnose for value- or type-dependent expressions.
12111 if (E->isTypeDependent() || E->isValueDependent())
12133 const Expr *E = OriginalE->IgnoreParenCasts();
12136 E->EvaluateForOverflow(Context);
12141 Exprs.append(InitList->inits().begin(), InitList->inits().end());
12143 E->EvaluateForOverflow(Context);
12145 Exprs.append(Call->arg_begin(), Call->arg_end());
12147 Exprs.append(Message->arg_begin(), Message->arg_end());
12149 Exprs.append(Construct->arg_begin(), Construct->arg_end());
12151 Exprs.push_back(Temporary->getSubExpr());
12153 Exprs.push_back(Array->getIdx());
12155 Exprs.push_back(Compound->getInitializer());
12157 New && New->isArray()) {
12158 if (auto ArraySize = New->getArraySize())
12161 Exprs.push_back(MTE->getSubExpr());
12208 return Seq(Values.size() - 1);
12244 /// least-sequenced usage of each kind.
12290 /// Filled in with declarations which were modified as a side-effect
12291 /// (that is, post-increment operations).
12299 /// expression. At the end of this process, the side-effects of the evaluation
12329 /// found to be non-constant, this allows us to suppress the evaluation of
12341 Prev->EvalOK &= EvalOK;
12345 if (!EvalOK || E->isValueDependent())
12347 EvalOK = E->EvaluateAsBooleanCondition(
12362 E = E->IgnoreParenCasts();
12364 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12365 return getObject(UO->getSubExpr(), Mod);
12367 if (BO->getOpcode() == BO_Comma)
12368 return getObject(BO->getRHS(), Mod);
12369 if (Mod && BO->isAssignmentOp())
12370 return getObject(BO->getLHS(), Mod);
12373 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12374 return ME->getMemberDecl();
12377 return DRE->getDecl();
12392 ModAsSideEffect->push_back(std::make_pair(O, U));
12402 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12403 /// usage and false we are checking for a mod-use unsequenced usage.
12419 Mod->getExprLoc(), {Mod, ModOrUse},
12422 << O << SourceRange(ModOrUse->getExprLoc()));
12430 // operations before C++17 and both are well-defined in C++17).
12433 // or notePreMod before visiting its sub-expression(s). At this point the
12445 // the visitation of such a sub-expression (for example: the LHS of || or ,)
12484 // Silence a -Wunused-private-field since WorkList is now unused.
12486 (void)this->WorkList;
12499 for (auto *Sub : CSE->children()) {
12504 if (ChildExpr == CSE->getOperand())
12517 if (E->getCastKind() == CK_LValueToRValue)
12518 O = getObject(E->getSubExpr(), false);
12553 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12555 Visit(ASE->getLHS());
12556 Visit(ASE->getRHS());
12564 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12567 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12569 Visit(BO->getLHS());
12570 Visit(BO->getRHS());
12580 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12582 Visit(BO->getLHS());
12583 Visit(BO->getRHS());
12592 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12613 Object O = getObject(BO->getLHS(), /*Mod=*/true);
12623 Visit(BO->getRHS());
12627 Visit(BO->getLHS());
12635 Visit(BO->getLHS());
12641 Visit(BO->getRHS());
12666 Object O = getObject(UO->getSubExpr(), true);
12671 Visit(UO->getSubExpr());
12682 Object O = getObject(UO->getSubExpr(), true);
12687 Visit(UO->getSubExpr());
12705 Visit(BO->getLHS());
12712 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12716 Visit(BO->getRHS());
12738 Visit(BO->getLHS());
12744 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12748 Visit(BO->getRHS());
12785 Visit(CO->getCond());
12795 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
12800 Visit(CO->getTrueExpr());
12804 Visit(CO->getFalseExpr());
12816 if (CE->isUnevaluatedBuiltinCall(Context))
12826 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
12828 // The postfix-expression is sequenced before each expression in the
12829 // expression-list and any default argument. [...]
12845 Visit(CE->getCallee());
12847 Visit(CE->getCallee());
12852 for (const Expr *Argument : CE->arguments())
12866 // function-call notation as summarized in Table 12 (where @ denotes one
12868 // operands are sequenced in the order prescribed for the built-in
12875 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
12884 switch (CXXOCE->getOperator()) {
12924 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
12927 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
12932 assert(CXXOCE->getOperator() == OO_Call &&
12936 // C++17 case. The postfix-expression is the first argument of the
12937 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
12946 assert(CXXOCE->getNumArgs() >= 1 &&
12948 " for the postfix-expression!");
12949 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
12950 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
12951 CXXOCE->getNumArgs() - 1);
12953 // Visit the postfix-expression first.
12969 assert(CXXOCE->getNumArgs() == 2 &&
12977 const Expr *E1 = CXXOCE->getArg(0);
12978 const Expr *E2 = CXXOCE->getArg(1);
12991 if (!CCE->isListInitialization())
12996 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
13004 SequenceExpressionsInOrder(ILE->inits());
13010 SequenceExpressionsInOrder(PLIE->getInitExprs());
13050 if (!E->isInstantiationDependent())
13052 if (!IsConstexpr && !E->isValueDependent())
13065 if (!PType->isVariablyModifiedType())
13068 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13072 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13076 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13084 if (AT->getSizeModifier() != ArraySizeModifier::Star) {
13085 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13103 // shall not be a (possibly cv-qualified) class type that is incomplete
13105 if (!Param->isInvalidDecl() &&
13106 (RequireCompleteType(Param->getLocation(), Param->getType(),
13108 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
13111 Param->setInvalidDecl();
13117 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13118 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13121 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
13129 QualType PType = Param->getOriginalType();
13130 // FIXME: This diagnostic should point the '[*]' if source-location
13132 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13137 if (!Param->isInvalidDecl()) {
13138 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13139 if (!ClassDecl->isInvalidDecl() &&
13140 !ClassDecl->hasIrrelevantDestructor() &&
13141 !ClassDecl->isDependentContext() &&
13142 ClassDecl->isParamDestroyedInCallee()) {
13144 MarkFunctionReferenced(Param->getLocation(), Destructor);
13145 DiagnoseUseOfDecl(Destructor, Param->getLocation());
13154 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13155 if (!Param->getType().isConstQualified())
13156 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13157 << Attr->getSpelling() << 1;
13160 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13163 DeclContext *DC = Param->getDeclContext();
13164 if (DC && DC->isFunctionOrMethod()) {
13165 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13166 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13171 if (!Param->isInvalidDecl() &&
13172 Param->getOriginalType()->isWebAssemblyTableType()) {
13173 Param->setInvalidDecl();
13175 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
13189 /// derived-to-base cast expression and the alignment and offset of the derived
13195 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13198 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13199 if (Base->isVirtual()) {
13200 // The complete object may have a lower alignment than the non-virtual
13202 // the smaller of the non-virtual alignment and BaseAlignment, which is a
13210 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13213 DerivedType = Base->getType();
13223 QualType PointeeType = PtrE->getType()->getPointeeType();
13225 if (!PointeeType->isConstantSizeType())
13234 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
13235 CharUnits Offset = EltSize * IdxRes->getExtValue();
13237 Offset = -Offset;
13238 return std::make_pair(P->first, P->second + Offset);
13245 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13255 E = E->IgnoreParens();
13256 switch (E->getStmtClass()) {
13263 const Expr *From = CE->getSubExpr();
13264 switch (CE->getCastKind()) {
13274 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
13275 P->second, Ctx);
13282 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
13286 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
13289 if (!VD->getType()->isReferenceType()) {
13290 // Dependent alignment cannot be resolved -> bail out.
13291 if (VD->hasDependentAlignment())
13295 if (VD->hasInit())
13296 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
13302 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13303 if (!FD || FD->getType()->isReferenceType() ||
13304 FD->getParent()->isInvalidDecl())
13307 if (ME->isArrow())
13308 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
13310 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
13313 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
13314 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
13315 return std::make_pair(P->first,
13316 P->second + CharUnits::fromQuantity(Offset));
13320 switch (UO->getOpcode()) {
13324 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
13330 auto Opcode = BO->getOpcode();
13335 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
13350 E = E->IgnoreParens();
13351 switch (E->getStmtClass()) {
13358 const Expr *From = CE->getSubExpr();
13359 switch (CE->getCastKind()) {
13372 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
13378 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
13384 if (UO->getOpcode() == UO_AddrOf)
13385 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
13390 auto Opcode = BO->getOpcode();
13396 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
13397 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
13403 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
13417 return P->first.alignmentAtOffset(P->second);
13420 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
13425 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13430 if (T->isDependentType() || Op->getType()->isDependentType())
13434 const PointerType *DestPtr = T->getAs<PointerType>();
13438 QualType DestPointee = DestPtr->getPointeeType();
13439 if (DestPointee->isIncompleteType()) return;
13444 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13446 QualType SrcPointee = SrcPtr->getPointeeType();
13452 if (SrcPointee->isIncompleteType()) return;
13459 << Op->getType() << T
13462 << TRange << Op->getSourceRange();
13472 IndexExpr = IndexExpr->IgnoreParenImpCasts();
13473 if (IndexExpr->isValueDependent())
13477 BaseExpr->getType()->getPointeeOrArrayElementType();
13478 BaseExpr = BaseExpr->IgnoreParenCasts();
13480 Context.getAsConstantArrayType(BaseExpr->getType());
13486 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
13488 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
13491 if (EffectiveType->isDependentType() ||
13492 (!IsUnboundedArray && BaseType->isDependentType()))
13496 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13502 index = -index;
13506 if (EffectiveType->isFunctionType())
13511 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
13516 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
13517 // pointer) bounds-checking isn't meaningful.
13518 if (!ElemCharUnits || ElemCharUnits->isZero())
13520 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
13546 // Diag message shows element size in bits and in "bytes" (platform-
13548 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13555 << IndexExpr->getSourceRange());
13560 BaseExpr = ASE->getBase()->IgnoreParenCasts();
13562 ND = DRE->getDecl();
13564 ND = ME->getMemberDecl();
13567 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13580 if (BaseType->isIncompleteType())
13583 llvm::APInt size = ArrayTy->getSize();
13615 // commonly done e.g. in C++ iterators and range-based for loops.
13624 ASE->getRBracketLoc());
13627 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13636 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
13639 BaseExpr->getBeginLoc(), BaseExpr,
13640 PDiag(DiagID) << toString(index, 10, true) << ArrayTy->desugar()
13641 << CastMsg << CastMsgTy << IndexExpr->getSourceRange());
13646 if (index.isNegative()) index = -index;
13649 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13651 << IndexExpr->getSourceRange());
13657 BaseExpr = ASE->getBase()->IgnoreParenCasts();
13659 ND = DRE->getDecl();
13661 ND = ME->getMemberDecl();
13664 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13671 expr = expr->IgnoreParenImpCasts();
13672 switch (expr->getStmtClass()) {
13675 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13677 expr = ASE->getBase();
13681 expr = cast<MemberExpr>(expr)->getBase();
13688 if (ASE->getLowerBound())
13689 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13696 expr = UO->getSubExpr();
13697 switch (UO->getOpcode()) {
13702 AllowOnePastEnd--;
13711 if (const Expr *lhs = cond->getLHS())
13713 if (const Expr *rhs = cond->getRHS())
13719 for (const auto *Arg : OCE->arguments())
13731 // Check if RHS is an Objective-C object literal, which also can get
13734 RHS = RHS->IgnoreParenImpCasts();
13737 // warn_objc_arc_literal_assign (off-by-1).
13745 << RHS->getSourceRange();
13753 // Strip off any implicit cast added to get to the one ARC-specific.
13755 if (cast->getCastKind() == CK_ARCConsumeObject) {
13759 << RHS->getSourceRange();
13762 RHS = cast->getSubExpr();
13791 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13792 if (PRE && !PRE->isImplicitProperty()) {
13793 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13795 LHSType = PD->getType();
13799 LHSType = LHS->getType();
13805 getCurFunction()->markSafeWeakUse(LHS);
13816 if (PRE->isImplicitProperty())
13818 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13822 unsigned Attributes = PD->getPropertyAttributes();
13827 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13829 LHSType->isObjCRetainableType())
13833 if (cast->getCastKind() == CK_ARCConsumeObject) {
13835 << RHS->getSourceRange();
13838 RHS = cast->getSubExpr();
13847 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13857 if (Body->hasLeadingEmptyMacro())
13868 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13897 Diag(NBody->getSemiLoc(), DiagID);
13898 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13909 StmtLoc = FS->getRParenLoc();
13910 Body = FS->getBody();
13913 StmtLoc = WS->getRParenLoc();
13914 Body = WS->getBody();
13925 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13947 PossibleBody->getBeginLoc(), &BodyColInvalid);
13953 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13962 Diag(NBody->getSemiLoc(), DiagID);
13963 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13967 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13978 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13979 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13984 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
13985 RHSExpr = CE->getArg(0);
13987 CXXSCE && CXXSCE->isXValue())
13988 RHSExpr = CXXSCE->getSubExpr();
13997 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13999 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14000 RHSDeclRef->getDecl()->getCanonicalDecl())
14004 << LHSExpr->getType() << LHSExpr->getSourceRange()
14005 << RHSExpr->getSourceRange();
14007 getSelfAssignmentClassMemberCandidate(RHSDeclRef->getDecl()))
14009 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14027 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14028 RHSME->getMemberDecl()->getCanonicalDecl())
14031 LHSBase = LHSME->getBase();
14032 RHSBase = RHSME->getBase();
14040 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14042 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14043 RHSDeclRef->getDecl()->getCanonicalDecl())
14047 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
14048 << RHSExpr->getSourceRange();
14054 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
14055 << RHSExpr->getSourceRange();
14058 //===--- Layout compatibility ----------------------------------------------//
14062 /// Check if two enumeration types are layout-compatible.
14066 // Two enumeration types are layout-compatible if they have the same
14068 return ED1->isComplete() && ED2->isComplete() &&
14069 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14072 /// Check if two fields are layout-compatible.
14079 Field1->getParent()->getTypeForDecl();
14081 Field2->getParent()->getTypeForDecl();
14082 assert(((Field1Parent->isStructureOrClassType() &&
14083 Field2Parent->isStructureOrClassType()) ||
14084 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
14087 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
14088 (AreUnionMembers && Field1Parent->isUnionType())) &&
14091 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14094 if (Field1->isBitField() != Field2->isBitField())
14097 if (Field1->isBitField()) {
14098 // Make sure that the bit-fields are the same length.
14099 unsigned Bits1 = Field1->getBitWidthValue();
14100 unsigned Bits2 = Field2->getBitWidthValue();
14106 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
14107 Field2->hasAttr<clang::NoUniqueAddressAttr>())
14111 Field1->getMaxAlignment() != Field2->getMaxAlignment())
14117 /// Check if two standard-layout structs are layout-compatible.
14123 RD1 = D1CXX->getStandardLayoutBaseWithFields();
14126 RD2 = D2CXX->getStandardLayoutBaseWithFields();
14129 return llvm::equal(RD1->fields(), RD2->fields(),
14130 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
14135 /// Check if two standard-layout unions are layout-compatible.
14140 for (auto *Field2 : RD2->fields())
14143 for (auto *Field1 : RD1->fields()) {
14164 if (RD1->isUnion() != RD2->isUnion())
14167 if (RD1->isUnion())
14173 /// Check if two types are layout-compatible in C++11 sense.
14179 // Two types cv1 T1 and cv2 T2 are layout-compatible types
14180 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
14181 // or layout-compatible standard-layout class types (11.4).
14188 const Type::TypeClass TC1 = T1->getTypeClass();
14189 const Type::TypeClass TC2 = T2->getTypeClass();
14196 cast<EnumType>(T1)->getDecl(),
14197 cast<EnumType>(T2)->getDecl());
14199 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14203 cast<RecordType>(T1)->getDecl(),
14204 cast<RecordType>(T2)->getDecl());
14214 //===-------------- Pointer interconvertibility ----------------------------//
14218 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
14219 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
14221 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
14225 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
14228 // Per [basic.compound]/4.3, containing object has to be standard-layout.
14229 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
14235 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14255 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14257 switch (TypeExpr->getStmtClass()) {
14260 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14261 TypeExpr = UO->getSubExpr();
14269 *VD = DRE->getDecl();
14275 llvm::APInt MagicValueAPInt = IL->getValue();
14288 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14291 TypeExpr = ACO->getTrueExpr();
14293 TypeExpr = ACO->getFalseExpr();
14301 if (BO->getOpcode() == BO_Comma) {
14302 TypeExpr = BO->getRHS();
14347 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14348 if (I->getArgumentKind() != ArgumentKind) {
14352 TypeInfo.Type = I->getMatchingCType();
14353 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14354 TypeInfo.MustBeNull = I->getMustBeNull();
14365 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14366 if (I == MagicValues->end())
14369 TypeInfo = I->second;
14387 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14391 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14395 BuiltinType::Kind T1Kind = BT1->getKind();
14396 BuiltinType::Kind T2Kind = BT2->getKind();
14407 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14408 bool IsPointerAttr = Attr->getIsPointer();
14411 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14414 << 0 << Attr->getTypeTagIdx().getSourceIndex();
14424 Diag(TypeTagExpr->getExprLoc(),
14426 << TypeTagExpr->getSourceRange();
14431 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14434 << 1 << Attr->getArgumentIdx().getSourceIndex();
14441 if (ICE->getType()->isVoidPointerType() &&
14442 ICE->getCastKind() == CK_BitCast)
14443 ArgumentExpr = ICE->getSubExpr();
14445 QualType ArgumentType = ArgumentExpr->getType();
14448 if (IsPointerAttr && ArgumentType->isVoidPointerType())
14453 if (!ArgumentExpr->isNullPointerConstant(Context,
14455 Diag(ArgumentExpr->getExprLoc(),
14457 << ArgumentKind->getName()
14458 << ArgumentExpr->getSourceRange()
14459 << TypeTagExpr->getSourceRange();
14478 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14479 RequiredType->getPointeeType())) ||
14485 ArgumentType->getPointeeType(),
14486 RequiredType->getPointeeType());
14491 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14494 << ArgumentExpr->getSourceRange()
14495 << TypeTagExpr->getSourceRange();
14506 if (ND->getName().empty()) {
14507 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14510 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14511 << m.MD << ND << m.E->getSourceRange();
14517 E = E->IgnoreParens();
14518 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
14521 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14522 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14526 (T->isDependentType() || T->isIntegerType() ||
14527 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14529 T->getPointeeType()) <= MA->Alignment))))
14543 // No need to check expressions with an __unaligned-qualified type.
14544 if (E->getType().getQualifiers().hasUnaligned())
14553 QualType BaseType = ME->getBase()->getType();
14554 if (BaseType->isDependentType())
14556 if (ME->isArrow())
14557 BaseType = BaseType->getPointeeType();
14558 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14559 if (RD->isInvalidDecl())
14562 ValueDecl *MD = ME->getMemberDecl();
14564 // We do not care about non-data members.
14565 if (!FD || FD->isInvalidDecl())
14569 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14573 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14581 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14590 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14603 ReverseMemberChain.back()->getParent()->getTypeForDecl());
14607 if (DRE && !TopME->isArrow()) {
14608 const ValueDecl *VD = DRE->getDecl();
14609 if (!VD->getType()->isReferenceType())
14630 if (FDI->hasAttr<PackedAttr>() ||
14631 FDI->getParent()->hasAttr<PackedAttr>()) {
14634 Context.getTypeAlignInChars(FD->getType()),
14635 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14640 Action(E, FD->getParent(), FD, Alignment);
14655 // First, convert to an r-value.
14660 // Promote floating-point types.
14668 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
14672 TheCall->setArg(0, A.get());
14673 QualType TyA = A.get()->getType();
14675 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))
14678 TheCall->setType(TyA);
14684 TheCall->setType(*Res);
14695 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
14696 TheCall->setType(VecTy0->getElementType());
14698 TheCall->setType(*Res);
14705 QualType L = LHS->getEnumCoercedType(S.Context),
14706 R = RHS->getEnumCoercedType(S.Context);
14707 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
14710 << LHS->getSourceRange() << RHS->getSourceRange()
14722 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
14728 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
14734 SourceLocation LocA = Args[0]->getBeginLoc();
14735 QualType TyA = Args[0]->getType();
14736 QualType TyB = Args[1]->getType();
14751 TheCall->setArg(0, Args[0]);
14752 TheCall->setArg(1, Args[1]);
14761 SourceLocation Loc = TheCall->getExprLoc();
14762 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
14763 TheCall->getArg(1), Loc) ||
14764 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
14765 TheCall->getArg(2), Loc))
14771 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
14780 if (checkFPMathBuiltinElementType(*this, Arg->getBeginLoc(),
14781 Arg->getType(), ArgOrdinal++))
14787 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
14794 if (Args[0]->getType().getCanonicalType() !=
14795 Args[I]->getType().getCanonicalType()) {
14796 return Diag(Args[0]->getBeginLoc(),
14798 << Args[0]->getType() << Args[I]->getType();
14801 TheCall->setArg(I, Args[I]);
14804 TheCall->setType(Args[0]->getType());
14812 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
14816 TheCall->setArg(0, A.get());
14824 ExprResult Arg = TheCall->getArg(0);
14825 QualType TyArg = Arg.get()->getType();
14827 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
14828 return Diag(TheCall->getArg(0)->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14831 TheCall->setType(TyArg);
14840 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
14845 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
14847 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14848 << 1 << /* matrix ty*/ 1 << Matrix->getType();
14855 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
14858 TheCall->setType(ResultType);
14861 TheCall->setArg(0, Matrix);
14870 Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
14872 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
14876 uint64_t Dim = Value->getZExtValue();
14878 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
14888 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
14896 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
14897 Expr *RowsExpr = TheCall->getArg(1);
14898 Expr *ColumnsExpr = TheCall->getArg(2);
14899 Expr *StrideExpr = TheCall->getArg(3);
14909 TheCall->setArg(0, PtrExpr);
14910 if (PtrExpr->isTypeDependent()) {
14911 TheCall->setType(Context.DependentTy);
14916 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
14919 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14920 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
14923 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
14926 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14928 << PtrExpr->getType();
14946 TheCall->setArg(1, RowsExpr);
14953 TheCall->setArg(2, ColumnsExpr);
14959 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
14960 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
14961 TheCall->setType(Context.DependentTy);
14979 TheCall->setArg(3, StrideExpr);
14983 StrideExpr->getIntegerConstantExpr(Context)) {
14984 uint64_t Stride = Value->getZExtValue();
14986 Diag(StrideExpr->getBeginLoc(),
14996 TheCall->setType(
15007 Expr *MatrixExpr = TheCall->getArg(0);
15008 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15009 Expr *StrideExpr = TheCall->getArg(2);
15018 TheCall->setArg(0, MatrixExpr);
15020 if (MatrixExpr->isTypeDependent()) {
15021 TheCall->setType(Context.DependentTy);
15025 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
15027 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
15028 << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
15037 TheCall->setArg(1, PtrExpr);
15038 if (PtrExpr->isTypeDependent()) {
15039 TheCall->setType(Context.DependentTy);
15045 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15047 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
15048 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
15051 QualType ElementTy = PtrTy->getPointeeType();
15053 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
15058 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
15059 Diag(PtrExpr->getBeginLoc(),
15061 << ElementTy << MatrixTy->getElementType();
15077 TheCall->setArg(2, StrideExpr);
15083 StrideExpr->getIntegerConstantExpr(Context)) {
15084 uint64_t Stride = Value->getZExtValue();
15085 if (Stride < MatrixTy->getNumRows()) {
15086 Diag(StrideExpr->getBeginLoc(),
15107 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
15113 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
15114 CalleeTCBs.insert(A->getTCBName());
15115 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
15116 CalleeTCBs.insert(A->getTCBName());
15120 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
15121 StringRef CallerTCB = A->getTCBName();
15123 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)