Index: clang/include/clang/Basic/DiagnosticGroups.td =================================================================== --- clang/include/clang/Basic/DiagnosticGroups.td +++ clang/include/clang/Basic/DiagnosticGroups.td @@ -64,7 +64,8 @@ def SignConversion : DiagGroup<"sign-conversion">; def PointerBoolConversion : DiagGroup<"pointer-bool-conversion">; def UndefinedBoolConversion : DiagGroup<"undefined-bool-conversion">; -def BoolOperation : DiagGroup<"bool-operation">; +def BitwiseInsteadOfLogical : DiagGroup<"bitwise-instead-of-logical">; +def BoolOperation : DiagGroup<"bool-operation", [BitwiseInsteadOfLogical]>; def BoolConversion : DiagGroup<"bool-conversion", [PointerBoolConversion, UndefinedBoolConversion]>; def IntConversion : DiagGroup<"int-conversion">; Index: clang/include/clang/Basic/DiagnosticSemaKinds.td =================================================================== --- clang/include/clang/Basic/DiagnosticSemaKinds.td +++ clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -66,6 +66,7 @@ def warn_comma_operator : Warning<"possible misuse of comma operator here">, InGroup>, DefaultIgnore; def note_cast_to_void : Note<"cast expression to void to silence warning">; +def note_cast_operand_to_int : Note<"cast one or both operands to int to silence warning">; // Constant expressions def err_expr_not_ice : Error< @@ -7425,6 +7426,9 @@ "member %0 declared here">; def note_member_first_declared_here : Note< "member %0 first declared here">; +def warn_bitwise_instead_of_logical : Warning< + "use of bitwise '%0' with boolean operands">, + InGroup, DefaultIgnore; def warn_bitwise_negation_bool : Warning< "bitwise negation of a boolean expression%select{;| always evaluates to 'true';}0 " "did you mean logical negation?">, Index: clang/lib/Sema/SemaChecking.cpp =================================================================== --- clang/lib/Sema/SemaChecking.cpp +++ clang/lib/Sema/SemaChecking.cpp @@ -13217,6 +13217,20 @@ << OrigE->getSourceRange() << T->isBooleanType() << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); + if (const auto *BO = dyn_cast(SourceExpr)) + if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && + BO->getLHS()->isKnownToHaveBooleanValue() && + BO->getRHS()->isKnownToHaveBooleanValue() && + BO->getLHS()->HasSideEffects(S.Context) && + BO->getRHS()->HasSideEffects(S.Context)) { + S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) + << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange() + << FixItHint::CreateReplacement( + BO->getOperatorLoc(), + (BO->getOpcode() == BO_And ? "&&" : "||")); + S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int); + } + // For conditional operators, we analyze the arguments as if they // were being fed directly into the output. if (auto *CO = dyn_cast(SourceExpr)) { Index: clang/p.patch =================================================================== --- /dev/null +++ clang/p.patch @@ -0,0 +1,26508 @@ +commit 7b09f244872bf04c0652460d09d15e57c807450f +Author: Dávid Bolvanský +Date: Sun Sep 26 16:41:33 2021 +0200 + + [Clang] Extend -Wbool-operation to warn about bitwise and of bools with side effects + + Motivation: https://arstechnica.com/gadgets/2021/07/google-pushed-a-one-character-typo-to-production-bricking-chrome-os-devices/ + + Warn for pattern boolA & boolB or boolA | boolB where boolA and boolB has possible side effects. + + Fixes https://bugs.llvm.org/show_bug.cgi?id=51216 + + Differential Revision: https://reviews.llvm.org/D108003 + +diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td +index f48598eec326..3fbcd77f4619 100644 +--- a/clang/include/clang/Basic/DiagnosticGroups.td ++++ b/clang/include/clang/Basic/DiagnosticGroups.td +@@ -1,1325 +1,1326 @@ + //==--- DiagnosticGroups.td - Diagnostic Group Definitions ----------------===// + // + // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. + // See https://llvm.org/LICENSE.txt for license information. + // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + // + //===----------------------------------------------------------------------===// + + def ImplicitFunctionDeclare : DiagGroup<"implicit-function-declaration">; + def ImplicitInt : DiagGroup<"implicit-int">; + + // Aggregation warning settings. + def Implicit : DiagGroup<"implicit", [ + ImplicitFunctionDeclare, + ImplicitInt + ]>; + + // Empty DiagGroups are recognized by clang but ignored. + def ODR : DiagGroup<"odr">; + def : DiagGroup<"abi">; + def AbsoluteValue : DiagGroup<"absolute-value">; + def MisspelledAssumption : DiagGroup<"misspelled-assumption">; + def UnknownAssumption : DiagGroup<"unknown-assumption">; + def AddressOfTemporary : DiagGroup<"address-of-temporary">; + def : DiagGroup<"aggregate-return">; + def GNUAlignofExpression : DiagGroup<"gnu-alignof-expression">; + def AmbigMemberTemplate : DiagGroup<"ambiguous-member-template">; + def GNUAnonymousStruct : DiagGroup<"gnu-anonymous-struct">; + def GNUAutoType : DiagGroup<"gnu-auto-type">; + def ArrayBounds : DiagGroup<"array-bounds">; + def ArrayBoundsPointerArithmetic : DiagGroup<"array-bounds-pointer-arithmetic">; + def AutoDisableVptrSanitizer : DiagGroup<"auto-disable-vptr-sanitizer">; + def Availability : DiagGroup<"availability">; + def Section : DiagGroup<"section">; + def AutoImport : DiagGroup<"auto-import">; + def FrameworkHdrQuotedInclude : DiagGroup<"quoted-include-in-framework-header">; + def FrameworkIncludePrivateFromPublic : + DiagGroup<"framework-include-private-from-public">; + def FrameworkHdrAtImport : DiagGroup<"atimport-in-framework-header">; + def CXX14BinaryLiteral : DiagGroup<"c++14-binary-literal">; + def CXXPre14CompatBinaryLiteral : DiagGroup<"c++98-c++11-compat-binary-literal">; + def GNUBinaryLiteral : DiagGroup<"gnu-binary-literal">; + def BinaryLiteral : DiagGroup<"binary-literal", [CXX14BinaryLiteral, + CXXPre14CompatBinaryLiteral, + GNUBinaryLiteral]>; + def GNUCompoundLiteralInitializer : DiagGroup<"gnu-compound-literal-initializer">; + def BitFieldConstantConversion : DiagGroup<"bitfield-constant-conversion">; + def BitFieldEnumConversion : DiagGroup<"bitfield-enum-conversion">; + def BitFieldWidth : DiagGroup<"bitfield-width">; + def CompoundTokenSplitByMacro : DiagGroup<"compound-token-split-by-macro">; + def CompoundTokenSplitBySpace : DiagGroup<"compound-token-split-by-space">; + def CompoundTokenSplit : DiagGroup<"compound-token-split", + [CompoundTokenSplitByMacro, + CompoundTokenSplitBySpace]>; + def CoroutineMissingUnhandledException : + DiagGroup<"coroutine-missing-unhandled-exception">; + def Coroutine : DiagGroup<"coroutine", [CoroutineMissingUnhandledException]>; + def ObjCBoolConstantConversion : DiagGroup<"objc-bool-constant-conversion">; + def ConstantConversion : DiagGroup<"constant-conversion", + [BitFieldConstantConversion, + ObjCBoolConstantConversion]>; + def LiteralConversion : DiagGroup<"literal-conversion">; + def StringConversion : DiagGroup<"string-conversion">; + def SignConversion : DiagGroup<"sign-conversion">; + def PointerBoolConversion : DiagGroup<"pointer-bool-conversion">; + def UndefinedBoolConversion : DiagGroup<"undefined-bool-conversion">; +-def BoolOperation : DiagGroup<"bool-operation">; ++def BitwiseInsteadOfLogical : DiagGroup<"bitwise-instead-of-logical">; ++def BoolOperation : DiagGroup<"bool-operation", [BitwiseInsteadOfLogical]>; + def BoolConversion : DiagGroup<"bool-conversion", [PointerBoolConversion, + UndefinedBoolConversion]>; + def IntConversion : DiagGroup<"int-conversion">; + def ClassConversion: DiagGroup<"class-conversion">; + def DeprecatedEnumCompareConditional : + DiagGroup<"deprecated-enum-compare-conditional">; + def EnumCompareConditional : DiagGroup<"enum-compare-conditional", + [DeprecatedEnumCompareConditional]>; + def EnumCompareSwitch : DiagGroup<"enum-compare-switch">; + def DeprecatedEnumCompare : DiagGroup<"deprecated-enum-compare">; + def EnumCompare : DiagGroup<"enum-compare", [EnumCompareSwitch, + DeprecatedEnumCompare]>; + def DeprecatedAnonEnumEnumConversion : DiagGroup<"deprecated-anon-enum-enum-conversion">; + def DeprecatedEnumEnumConversion : DiagGroup<"deprecated-enum-enum-conversion">; + def DeprecatedEnumFloatConversion : DiagGroup<"deprecated-enum-float-conversion">; + def AnonEnumEnumConversion : DiagGroup<"anon-enum-enum-conversion", + [DeprecatedAnonEnumEnumConversion]>; + def EnumEnumConversion : DiagGroup<"enum-enum-conversion", + [DeprecatedEnumEnumConversion]>; + def EnumFloatConversion : DiagGroup<"enum-float-conversion", + [DeprecatedEnumFloatConversion]>; + def EnumConversion : DiagGroup<"enum-conversion", + [EnumEnumConversion, + EnumFloatConversion, + EnumCompareConditional]>; + def ObjCSignedCharBoolImplicitIntConversion : + DiagGroup<"objc-signed-char-bool-implicit-int-conversion">; + def ImplicitIntConversion : DiagGroup<"implicit-int-conversion", + [ObjCSignedCharBoolImplicitIntConversion]>; + def ImplicitConstIntFloatConversion : DiagGroup<"implicit-const-int-float-conversion">; + def ImplicitIntFloatConversion : DiagGroup<"implicit-int-float-conversion", + [ImplicitConstIntFloatConversion]>; + def ObjCSignedCharBoolImplicitFloatConversion : + DiagGroup<"objc-signed-char-bool-implicit-float-conversion">; + def ImplicitFloatConversion : DiagGroup<"implicit-float-conversion", + [ImplicitIntFloatConversion, + ObjCSignedCharBoolImplicitFloatConversion]>; + def ImplicitFixedPointConversion : DiagGroup<"implicit-fixed-point-conversion">; + + def FloatOverflowConversion : DiagGroup<"float-overflow-conversion">; + def FloatZeroConversion : DiagGroup<"float-zero-conversion">; + def FloatConversion : + DiagGroup<"float-conversion", [FloatOverflowConversion, + FloatZeroConversion]>; + + def FrameAddress : DiagGroup<"frame-address">; + def FreeNonHeapObject : DiagGroup<"free-nonheap-object">; + def DoublePromotion : DiagGroup<"double-promotion">; + def EnumTooLarge : DiagGroup<"enum-too-large">; + def UnsupportedNan : DiagGroup<"unsupported-nan">; + def UnsupportedAbs : DiagGroup<"unsupported-abs">; + def UnsupportedFPOpt : DiagGroup<"unsupported-floating-point-opt">; + def UnsupportedCB : DiagGroup<"unsupported-cb">; + def UnsupportedGPOpt : DiagGroup<"unsupported-gpopt">; + def UnsupportedTargetOpt : DiagGroup<"unsupported-target-opt">; + def NonLiteralNullConversion : DiagGroup<"non-literal-null-conversion">; + def NullConversion : DiagGroup<"null-conversion">; + def ImplicitConversionFloatingPointToBool : + DiagGroup<"implicit-conversion-floating-point-to-bool">; + def ObjCLiteralConversion : DiagGroup<"objc-literal-conversion">; + def MacroRedefined : DiagGroup<"macro-redefined">; + def BuiltinMacroRedefined : DiagGroup<"builtin-macro-redefined">; + def BuiltinRequiresHeader : DiagGroup<"builtin-requires-header">; + def C99Compat : DiagGroup<"c99-compat">; + def CXXCompat: DiagGroup<"c++-compat">; + def ExternCCompat : DiagGroup<"extern-c-compat">; + def KeywordCompat : DiagGroup<"keyword-compat">; + def GNUCaseRange : DiagGroup<"gnu-case-range">; + def CastAlign : DiagGroup<"cast-align">; + def CastQual : DiagGroup<"cast-qual">; + def : DiagGroup<"char-align">; + def Comment : DiagGroup<"comment">; + def GNUComplexInteger : DiagGroup<"gnu-complex-integer">; + def GNUConditionalOmittedOperand : DiagGroup<"gnu-conditional-omitted-operand">; + def ConfigMacros : DiagGroup<"config-macros">; + def : DiagGroup<"ctor-dtor-privacy">; + def GNUStringLiteralOperatorTemplate : + DiagGroup<"gnu-string-literal-operator-template">; + def UndefinedVarTemplate : DiagGroup<"undefined-var-template">; + def UndefinedFuncTemplate : DiagGroup<"undefined-func-template">; + def MissingNoEscape : DiagGroup<"missing-noescape">; + + def DefaultedFunctionDeleted : DiagGroup<"defaulted-function-deleted">; + def DeleteIncomplete : DiagGroup<"delete-incomplete">; + def DeleteNonAbstractNonVirtualDtor : DiagGroup<"delete-non-abstract-non-virtual-dtor">; + def DeleteAbstractNonVirtualDtor : DiagGroup<"delete-abstract-non-virtual-dtor">; + def DeleteNonVirtualDtor : DiagGroup<"delete-non-virtual-dtor", + [DeleteNonAbstractNonVirtualDtor, + DeleteAbstractNonVirtualDtor]>; + def AbstractFinalClass : DiagGroup<"abstract-final-class">; + def FinalDtorNonFinalClass : DiagGroup<"final-dtor-non-final-class">; + + def CXX11CompatDeprecatedWritableStr : + DiagGroup<"c++11-compat-deprecated-writable-strings">; + + def DeprecatedArrayCompare : DiagGroup<"deprecated-array-compare">; + def DeprecatedAttributes : DiagGroup<"deprecated-attributes">; + def DeprecatedCommaSubscript : DiagGroup<"deprecated-comma-subscript">; + def DeprecatedCopyWithUserProvidedCopy : DiagGroup<"deprecated-copy-with-user-provided-copy">; + def DeprecatedCopyWithUserProvidedDtor : DiagGroup<"deprecated-copy-with-user-provided-dtor">; + def DeprecatedCopy : DiagGroup<"deprecated-copy", [DeprecatedCopyWithUserProvidedCopy]>; + def DeprecatedCopyWithDtor : DiagGroup<"deprecated-copy-with-dtor", [DeprecatedCopyWithUserProvidedDtor]>; + // For compatibility with GCC. + def : DiagGroup<"deprecated-copy-dtor", [DeprecatedCopyWithDtor]>; + def DeprecatedDeclarations : DiagGroup<"deprecated-declarations">; + def UnavailableDeclarations : DiagGroup<"unavailable-declarations">; + def UnguardedAvailabilityNew : DiagGroup<"unguarded-availability-new">; + def UnguardedAvailability : DiagGroup<"unguarded-availability", + [UnguardedAvailabilityNew]>; + // partial-availability is an alias of unguarded-availability. + def : DiagGroup<"partial-availability", [UnguardedAvailability]>; + def DeprecatedDynamicExceptionSpec + : DiagGroup<"deprecated-dynamic-exception-spec">; + def DeprecatedImplementations :DiagGroup<"deprecated-implementations">; + def DeprecatedIncrementBool : DiagGroup<"deprecated-increment-bool">; + def DeprecatedRegister : DiagGroup<"deprecated-register">; + def DeprecatedThisCapture : DiagGroup<"deprecated-this-capture">; + def DeprecatedVolatile : DiagGroup<"deprecated-volatile">; + def DeprecatedWritableStr : DiagGroup<"deprecated-writable-strings", + [CXX11CompatDeprecatedWritableStr]>; + def DeprecatedPragma : DiagGroup<"deprecated-pragma">; + // FIXME: Why is DeprecatedImplementations not in this group? + def Deprecated : DiagGroup<"deprecated", [DeprecatedAnonEnumEnumConversion, + DeprecatedArrayCompare, + DeprecatedAttributes, + DeprecatedCommaSubscript, + DeprecatedCopy, + DeprecatedCopyWithDtor, + DeprecatedDeclarations, + DeprecatedDynamicExceptionSpec, + DeprecatedEnumCompare, + DeprecatedEnumCompareConditional, + DeprecatedEnumEnumConversion, + DeprecatedEnumFloatConversion, + DeprecatedIncrementBool, + DeprecatedPragma, + DeprecatedRegister, + DeprecatedThisCapture, + DeprecatedVolatile, + DeprecatedWritableStr]>, + DiagCategory<"Deprecations">; + + def CXX20Designator : DiagGroup<"c++20-designator">; + // Allow -Wno-c99-designator to be used to turn off all warnings on valid C99 + // designators (including the warning controlled by -Wc++20-designator). + def C99Designator : DiagGroup<"c99-designator", [CXX20Designator]>; + def GNUDesignator : DiagGroup<"gnu-designator">; + def DtorName : DiagGroup<"dtor-name">; + + def DynamicExceptionSpec + : DiagGroup<"dynamic-exception-spec", [DeprecatedDynamicExceptionSpec]>; + + def LibLTO : DiagGroup<"liblto">; + def : DiagGroup<"disabled-optimization">; + def : DiagGroup<"discard-qual">; + def DivZero : DiagGroup<"division-by-zero">; + def : DiagGroup<"div-by-zero", [DivZero]>; + + def DocumentationHTML : DiagGroup<"documentation-html">; + def DocumentationUnknownCommand : DiagGroup<"documentation-unknown-command">; + def DocumentationPedantic : DiagGroup<"documentation-pedantic", + [DocumentationUnknownCommand]>; + def DocumentationDeprecatedSync : DiagGroup<"documentation-deprecated-sync">; + def Documentation : DiagGroup<"documentation", + [DocumentationHTML, + DocumentationDeprecatedSync]>; + + def EmptyBody : DiagGroup<"empty-body">; + def Exceptions : DiagGroup<"exceptions">; + + def GNUEmptyInitializer : DiagGroup<"gnu-empty-initializer">; + def GNUEmptyStruct : DiagGroup<"gnu-empty-struct">; + def ExtraTokens : DiagGroup<"extra-tokens">; + def CXX98CompatExtraSemi : DiagGroup<"c++98-compat-extra-semi">; + def CXX11ExtraSemi : DiagGroup<"c++11-extra-semi">; + def EmptyInitStatement : DiagGroup<"empty-init-stmt">; + def ExportUnnamed : DiagGroup<"export-unnamed">; + def ExtraSemiStmt : DiagGroup<"extra-semi-stmt", [EmptyInitStatement]>; + def ExtraSemi : DiagGroup<"extra-semi", [CXX98CompatExtraSemi, + CXX11ExtraSemi]>; + + def GNUFlexibleArrayInitializer : DiagGroup<"gnu-flexible-array-initializer">; + def GNUFlexibleArrayUnionMember : DiagGroup<"gnu-flexible-array-union-member">; + def GNUFoldingConstant : DiagGroup<"gnu-folding-constant">; + def FormatInsufficientArgs : DiagGroup<"format-insufficient-args">; + def FormatExtraArgs : DiagGroup<"format-extra-args">; + def FormatZeroLength : DiagGroup<"format-zero-length">; + + def InvalidIOSDeploymentTarget : DiagGroup<"invalid-ios-deployment-target">; + + def CXX17CompatMangling : DiagGroup<"c++17-compat-mangling">; + def : DiagGroup<"c++1z-compat-mangling", [CXX17CompatMangling]>; + // Name of this warning in GCC. + def NoexceptType : DiagGroup<"noexcept-type", [CXX17CompatMangling]>; + + // Warnings for C code which is not compatible with previous C standards. + def CPre2xCompat : DiagGroup<"pre-c2x-compat">; + def CPre2xCompatPedantic : DiagGroup<"pre-c2x-compat-pedantic", + [CPre2xCompat]>; + + // Warnings for C++ code which is not compatible with previous C++ standards. + def CXXPre14Compat : DiagGroup<"pre-c++14-compat">; + def : DiagGroup<"c++98-c++11-compat", [CXXPre14Compat]>; + def CXXPre14CompatPedantic : DiagGroup<"pre-c++14-compat-pedantic", + [CXXPre14Compat, + CXXPre14CompatBinaryLiteral]>; + def : DiagGroup<"c++98-c++11-compat-pedantic", [CXXPre14CompatPedantic]>; + def CXXPre17Compat : DiagGroup<"pre-c++17-compat">; + def : DiagGroup<"c++98-c++11-c++14-compat", [CXXPre17Compat]>; + def CXXPre17CompatPedantic : DiagGroup<"pre-c++17-compat-pedantic", + [CXXPre17Compat]>; + def : DiagGroup<"c++98-c++11-c++14-compat-pedantic", + [CXXPre17CompatPedantic]>; + def CXXPre20Compat : DiagGroup<"pre-c++20-compat">; + def : DiagGroup<"c++98-c++11-c++14-c++17-compat", [CXXPre20Compat]>; + def CXXPre20CompatPedantic : DiagGroup<"pre-c++20-compat-pedantic", + [CXXPre20Compat]>; + def : DiagGroup<"c++98-c++11-c++14-c++17-compat-pedantic", + [CXXPre20CompatPedantic]>; + def CXXPre2bCompat : DiagGroup<"pre-c++2b-compat">; + def CXXPre2bCompatPedantic : + DiagGroup<"pre-c++2b-compat-pedantic", [CXXPre2bCompat]>; + + def CXX98CompatBindToTemporaryCopy : + DiagGroup<"c++98-compat-bind-to-temporary-copy">; + def CXX98CompatLocalTypeTemplateArgs : + DiagGroup<"c++98-compat-local-type-template-args">; + def CXX98CompatUnnamedTypeTemplateArgs : + DiagGroup<"c++98-compat-unnamed-type-template-args">; + + def CXX98Compat : DiagGroup<"c++98-compat", + [CXX98CompatLocalTypeTemplateArgs, + CXX98CompatUnnamedTypeTemplateArgs, + CXXPre14Compat, + CXXPre17Compat, + CXXPre20Compat, + CXXPre2bCompat]>; + // Warnings for C++11 features which are Extensions in C++98 mode. + def CXX98CompatPedantic : DiagGroup<"c++98-compat-pedantic", + [CXX98Compat, + CXX98CompatBindToTemporaryCopy, + CXX98CompatExtraSemi, + CXXPre14CompatPedantic, + CXXPre17CompatPedantic, + CXXPre20CompatPedantic, + CXXPre2bCompatPedantic]>; + + def CXX11Narrowing : DiagGroup<"c++11-narrowing">; + + def CXX11WarnInconsistentOverrideDestructor : + DiagGroup<"inconsistent-missing-destructor-override">; + def CXX11WarnInconsistentOverrideMethod : + DiagGroup<"inconsistent-missing-override">; + def CXX11WarnSuggestOverrideDestructor : DiagGroup<"suggest-destructor-override">; + def CXX11WarnSuggestOverride : DiagGroup<"suggest-override">; + + // Original name of this warning in Clang + def : DiagGroup<"c++0x-narrowing", [CXX11Narrowing]>; + + // Name of this warning in GCC + def : DiagGroup<"narrowing", [CXX11Narrowing]>; + + def CXX11CompatReservedUserDefinedLiteral : + DiagGroup<"c++11-compat-reserved-user-defined-literal">; + def ReservedUserDefinedLiteral : + DiagGroup<"reserved-user-defined-literal", + [CXX11CompatReservedUserDefinedLiteral]>; + + def CXX11Compat : DiagGroup<"c++11-compat", + [CXX11Narrowing, + CXX11CompatReservedUserDefinedLiteral, + CXX11CompatDeprecatedWritableStr, + CXXPre14Compat, + CXXPre17Compat, + CXXPre20Compat, + CXXPre2bCompat]>; + def : DiagGroup<"c++0x-compat", [CXX11Compat]>; + def CXX11CompatPedantic : DiagGroup<"c++11-compat-pedantic", + [CXX11Compat, + CXXPre14CompatPedantic, + CXXPre17CompatPedantic, + CXXPre20CompatPedantic, + CXXPre2bCompatPedantic]>; + + def CXX14Compat : DiagGroup<"c++14-compat", [CXXPre17Compat, + CXXPre20Compat, + CXXPre2bCompat]>; + def CXX14CompatPedantic : DiagGroup<"c++14-compat-pedantic", + [CXX14Compat, + CXXPre17CompatPedantic, + CXXPre20CompatPedantic, + CXXPre2bCompatPedantic]>; + + def CXX17Compat : DiagGroup<"c++17-compat", [DeprecatedRegister, + DeprecatedIncrementBool, + CXX17CompatMangling, + CXXPre20Compat, + CXXPre2bCompat]>; + def CXX17CompatPedantic : DiagGroup<"c++17-compat-pedantic", + [CXX17Compat, + CXXPre20CompatPedantic, + CXXPre2bCompatPedantic]>; + def : DiagGroup<"c++1z-compat", [CXX17Compat]>; + + def CXX20Compat : DiagGroup<"c++20-compat", [CXXPre2bCompat]>; + def CXX20CompatPedantic : DiagGroup<"c++20-compat-pedantic", + [CXX20Compat, + CXXPre2bCompatPedantic]>; + def : DiagGroup<"c++2a-compat", [CXX20Compat]>; + def : DiagGroup<"c++2a-compat-pedantic", [CXX20CompatPedantic]>; + + def ExitTimeDestructors : DiagGroup<"exit-time-destructors">; + def FlexibleArrayExtensions : DiagGroup<"flexible-array-extensions">; + def FourByteMultiChar : DiagGroup<"four-char-constants">; + def GlobalConstructors : DiagGroup<"global-constructors">; + def BitwiseConditionalParentheses: DiagGroup<"bitwise-conditional-parentheses">; + def BitwiseOpParentheses: DiagGroup<"bitwise-op-parentheses">; + def LogicalOpParentheses: DiagGroup<"logical-op-parentheses">; + def LogicalNotParentheses: DiagGroup<"logical-not-parentheses">; + def ShiftOpParentheses: DiagGroup<"shift-op-parentheses">; + def OverloadedShiftOpParentheses: DiagGroup<"overloaded-shift-op-parentheses">; + def DanglingElse: DiagGroup<"dangling-else">; + def DanglingField : DiagGroup<"dangling-field">; + def DanglingInitializerList : DiagGroup<"dangling-initializer-list">; + def DanglingGsl : DiagGroup<"dangling-gsl">; + def ReturnStackAddress : DiagGroup<"return-stack-address">; + def Dangling : DiagGroup<"dangling", [DanglingField, + DanglingInitializerList, + DanglingGsl, + ReturnStackAddress]>; + def DistributedObjectModifiers : DiagGroup<"distributed-object-modifiers">; + def ExcessInitializers : DiagGroup<"excess-initializers">; + def ExpansionToDefined : DiagGroup<"expansion-to-defined">; + def FlagEnum : DiagGroup<"flag-enum">; + def IncrementBool : DiagGroup<"increment-bool", [DeprecatedIncrementBool]>; + def InfiniteRecursion : DiagGroup<"infinite-recursion">; + def PureVirtualCallFromCtorDtor: DiagGroup<"call-to-pure-virtual-from-ctor-dtor">; + def GNUImaginaryConstant : DiagGroup<"gnu-imaginary-constant">; + def IgnoredReferenceQualifiers : DiagGroup<"ignored-reference-qualifiers">; + def IgnoredQualifiers : DiagGroup<"ignored-qualifiers", [IgnoredReferenceQualifiers]>; + def : DiagGroup<"import">; + def GNUIncludeNext : DiagGroup<"gnu-include-next">; + def IncompatibleMSStruct : DiagGroup<"incompatible-ms-struct">; + def IncompatiblePointerTypesDiscardsQualifiers + : DiagGroup<"incompatible-pointer-types-discards-qualifiers">; + def IncompatibleFunctionPointerTypes + : DiagGroup<"incompatible-function-pointer-types">; + def IncompatiblePointerTypes + : DiagGroup<"incompatible-pointer-types", + [IncompatiblePointerTypesDiscardsQualifiers, + IncompatibleFunctionPointerTypes]>; + def IncompleteUmbrella : DiagGroup<"incomplete-umbrella">; + def IncompleteFrameworkModuleDeclaration + : DiagGroup<"incomplete-framework-module-declaration">; + def NonModularIncludeInFrameworkModule + : DiagGroup<"non-modular-include-in-framework-module">; + def NonModularIncludeInModule : DiagGroup<"non-modular-include-in-module", + [NonModularIncludeInFrameworkModule]>; + def IncompleteModule : DiagGroup<"incomplete-module", + [IncompleteUmbrella, NonModularIncludeInModule]>; + def PrivateModule : DiagGroup<"private-module">; + + def CXX11InlineNamespace : DiagGroup<"c++11-inline-namespace">; + def InlineNamespaceReopenedNoninline + : DiagGroup<"inline-namespace-reopened-noninline">; + def InvalidNoreturn : DiagGroup<"invalid-noreturn">; + def InvalidSourceEncoding : DiagGroup<"invalid-source-encoding">; + def KNRPromotedParameter : DiagGroup<"knr-promoted-parameter">; + def : DiagGroup<"init-self">; + def : DiagGroup<"inline">; + def : DiagGroup<"invalid-pch">; + def GNULabelsAsValue : DiagGroup<"gnu-label-as-value">; + def LiteralRange : DiagGroup<"literal-range">; + def LocalTypeTemplateArgs : DiagGroup<"local-type-template-args", + [CXX98CompatLocalTypeTemplateArgs]>; + def RangeLoopConstruct : DiagGroup<"range-loop-construct">; + def RangeLoopBindReference : DiagGroup<"range-loop-bind-reference">; + def RangeLoopAnalysis : DiagGroup<"range-loop-analysis", + [RangeLoopConstruct, RangeLoopBindReference]>; + def ForLoopAnalysis : DiagGroup<"for-loop-analysis">; + def LoopAnalysis : DiagGroup<"loop-analysis", [ForLoopAnalysis, + RangeLoopAnalysis]>; + def MalformedWarningCheck : DiagGroup<"malformed-warning-check">; + def Main : DiagGroup<"main">; + def MainReturnType : DiagGroup<"main-return-type">; + def MaxUnsignedZero : DiagGroup<"max-unsigned-zero">; + def MissingBraces : DiagGroup<"missing-braces">; + def MissingDeclarations: DiagGroup<"missing-declarations">; + def : DiagGroup<"missing-format-attribute">; + def : DiagGroup<"missing-include-dirs">; + def MissingNoreturn : DiagGroup<"missing-noreturn">; + def MultiChar : DiagGroup<"multichar">; + def : DiagGroup<"nested-externs">; + def CXX11LongLong : DiagGroup<"c++11-long-long">; + def LongLong : DiagGroup<"long-long", [CXX11LongLong]>; + def ImplicitlyUnsignedLiteral : DiagGroup<"implicitly-unsigned-literal">; + def MethodSignatures : DiagGroup<"method-signatures">; + def MismatchedParameterTypes : DiagGroup<"mismatched-parameter-types">; + def MismatchedReturnTypes : DiagGroup<"mismatched-return-types">; + def MismatchedTags : DiagGroup<"mismatched-tags">; + def MissingFieldInitializers : DiagGroup<"missing-field-initializers">; + def ModuleLock : DiagGroup<"module-lock">; + def ModuleBuild : DiagGroup<"module-build">; + def ModuleImport : DiagGroup<"module-import">; + def ModuleConflict : DiagGroup<"module-conflict">; + def ModuleFileExtension : DiagGroup<"module-file-extension">; + def RoundTripCC1Args : DiagGroup<"round-trip-cc1-args">; + def NewlineEOF : DiagGroup<"newline-eof">; + def Nullability : DiagGroup<"nullability">; + def NullabilityDeclSpec : DiagGroup<"nullability-declspec">; + def NullabilityInferredOnNestedType : DiagGroup<"nullability-inferred-on-nested-type">; + def NullableToNonNullConversion : DiagGroup<"nullable-to-nonnull-conversion">; + def NullabilityCompletenessOnArrays : DiagGroup<"nullability-completeness-on-arrays">; + def NullabilityCompleteness : DiagGroup<"nullability-completeness", + [NullabilityCompletenessOnArrays]>; + def NullArithmetic : DiagGroup<"null-arithmetic">; + def NullCharacter : DiagGroup<"null-character">; + def NullDereference : DiagGroup<"null-dereference">; + def InitializerOverrides : DiagGroup<"initializer-overrides">; + // For compatibility with GCC; -Woverride-init = -Winitializer-overrides + def : DiagGroup<"override-init", [InitializerOverrides]>; + def NonNull : DiagGroup<"nonnull">; + def NonPODVarargs : DiagGroup<"non-pod-varargs">; + def ClassVarargs : DiagGroup<"class-varargs", [NonPODVarargs]>; + def : DiagGroup<"nonportable-cfstrings">; + def NonVirtualDtor : DiagGroup<"non-virtual-dtor">; + def NullPointerArithmetic : DiagGroup<"null-pointer-arithmetic">; + def NullPointerSubtraction : DiagGroup<"null-pointer-subtraction">; + def : DiagGroup<"effc++", [NonVirtualDtor]>; + def OveralignedType : DiagGroup<"over-aligned">; + def OldStyleCast : DiagGroup<"old-style-cast">; + def : DiagGroup<"old-style-definition">; + def OutOfLineDeclaration : DiagGroup<"out-of-line-declaration">; + def : DiagGroup<"overflow">; + def ForwardClassReceiver : DiagGroup<"receiver-forward-class">; + def MethodAccess : DiagGroup<"objc-method-access">; + def ObjCReceiver : DiagGroup<"receiver-expr">; + def OperatorNewReturnsNull : DiagGroup<"new-returns-null">; + def OverlengthStrings : DiagGroup<"overlength-strings">; + def OverloadedVirtual : DiagGroup<"overloaded-virtual">; + def PrivateExtern : DiagGroup<"private-extern">; + def SelTypeCast : DiagGroup<"cast-of-sel-type">; + def FunctionDefInObjCContainer : DiagGroup<"function-def-in-objc-container">; + def BadFunctionCast : DiagGroup<"bad-function-cast">; + def CastFunctionType : DiagGroup<"cast-function-type">; + def ObjCPropertyImpl : DiagGroup<"objc-property-implementation">; + def ObjCPropertyNoAttribute : DiagGroup<"objc-property-no-attribute">; + def ObjCPropertyAssignOnObjectType : DiagGroup<"objc-property-assign-on-object-type">; + def ObjCProtocolQualifiers : DiagGroup<"objc-protocol-qualifiers">; + def ObjCMissingSuperCalls : DiagGroup<"objc-missing-super-calls">; + def ObjCDesignatedInit : DiagGroup<"objc-designated-initializers">; + def ObjCRetainBlockProperty : DiagGroup<"objc-noncopy-retain-block-property">; + def ObjCReadonlyPropertyHasSetter : DiagGroup<"objc-readonly-with-setter-property">; + def ObjCInvalidIBOutletProperty : DiagGroup<"invalid-iboutlet">; + def ObjCRootClass : DiagGroup<"objc-root-class">; + def ObjCPointerIntrospectPerformSelector : DiagGroup<"deprecated-objc-pointer-introspection-performSelector">; + def ObjCPointerIntrospect : DiagGroup<"deprecated-objc-pointer-introspection", [ObjCPointerIntrospectPerformSelector]>; + def ObjCMultipleMethodNames : DiagGroup<"objc-multiple-method-names">; + def ObjCFlexibleArray : DiagGroup<"objc-flexible-array">; + def ObjCBoxing : DiagGroup<"objc-boxing">; + def CompletionHandler : DiagGroup<"completion-handler">; + def CalledOnceParameter : DiagGroup<"called-once-parameter", [CompletionHandler]>; + def OpenCLUnsupportedRGBA: DiagGroup<"opencl-unsupported-rgba">; + def UnderalignedExceptionObject : DiagGroup<"underaligned-exception-object">; + def DeprecatedObjCIsaUsage : DiagGroup<"deprecated-objc-isa-usage">; + def ExplicitInitializeCall : DiagGroup<"explicit-initialize-call">; + def OrderedCompareFunctionPointers : DiagGroup<"ordered-compare-function-pointers">; + def Packed : DiagGroup<"packed">; + def Padded : DiagGroup<"padded">; + + def PessimizingMove : DiagGroup<"pessimizing-move">; + def ReturnStdMove : DiagGroup<"return-std-move">; + + def PointerArith : DiagGroup<"pointer-arith">; + def PoundWarning : DiagGroup<"#warnings">; + def PoundPragmaMessage : DiagGroup<"#pragma-messages">, + DiagCategory<"#pragma message Directive">; + def : DiagGroup<"redundant-decls">; + def RedeclaredClassMember : DiagGroup<"redeclared-class-member">; + def GNURedeclaredEnum : DiagGroup<"gnu-redeclared-enum">; + def RedundantMove : DiagGroup<"redundant-move">; + def Register : DiagGroup<"register", [DeprecatedRegister]>; + def ReturnTypeCLinkage : DiagGroup<"return-type-c-linkage">; + def ReturnType : DiagGroup<"return-type", [ReturnTypeCLinkage]>; + def BindToTemporaryCopy : DiagGroup<"bind-to-temporary-copy", + [CXX98CompatBindToTemporaryCopy]>; + def SelfAssignmentField : DiagGroup<"self-assign-field">; + def SelfAssignmentOverloaded : DiagGroup<"self-assign-overloaded">; + def SelfAssignment : DiagGroup<"self-assign", [SelfAssignmentOverloaded, SelfAssignmentField]>; + def SelfMove : DiagGroup<"self-move">; + def SemiBeforeMethodBody : DiagGroup<"semicolon-before-method-body">; + def Sentinel : DiagGroup<"sentinel">; + def MissingMethodReturnType : DiagGroup<"missing-method-return-type">; + + def ShadowField : DiagGroup<"shadow-field">; + def ShadowFieldInConstructorModified : DiagGroup<"shadow-field-in-constructor-modified">; + def ShadowFieldInConstructor : DiagGroup<"shadow-field-in-constructor", + [ShadowFieldInConstructorModified]>; + def ShadowIvar : DiagGroup<"shadow-ivar">; + def ShadowUncapturedLocal : DiagGroup<"shadow-uncaptured-local">; + + // -Wshadow-all is a catch-all for all shadowing. -Wshadow is just the + // shadowing that we think is unsafe. + def Shadow : DiagGroup<"shadow", [ShadowFieldInConstructorModified, + ShadowIvar]>; + def ShadowAll : DiagGroup<"shadow-all", [Shadow, ShadowFieldInConstructor, + ShadowUncapturedLocal, ShadowField]>; + + def Shorten64To32 : DiagGroup<"shorten-64-to-32">; + def : DiagGroup<"sign-promo">; + def SignCompare : DiagGroup<"sign-compare">; + def : DiagGroup<"switch-default">; + def : DiagGroup<"synth">; + def SizeofArrayArgument : DiagGroup<"sizeof-array-argument">; + def SizeofArrayDecay : DiagGroup<"sizeof-array-decay">; + def SizeofPointerMemaccess : DiagGroup<"sizeof-pointer-memaccess">; + def MemsetTransposedArgs : DiagGroup<"memset-transposed-args">; + def DynamicClassMemaccess : DiagGroup<"dynamic-class-memaccess">; + def NonTrivialMemaccess : DiagGroup<"nontrivial-memaccess">; + def SuspiciousBzero : DiagGroup<"suspicious-bzero">; + def SuspiciousMemaccess : DiagGroup<"suspicious-memaccess", + [SizeofPointerMemaccess, DynamicClassMemaccess, + NonTrivialMemaccess, MemsetTransposedArgs, SuspiciousBzero]>; + def StaticInInline : DiagGroup<"static-in-inline">; + def StaticLocalInInline : DiagGroup<"static-local-in-inline">; + def GNUStaticFloatInit : DiagGroup<"gnu-static-float-init">; + def StaticFloatInit : DiagGroup<"static-float-init", [GNUStaticFloatInit]>; + def GNUStatementExpression : DiagGroup<"gnu-statement-expression">; + def StringConcatation : DiagGroup<"string-concatenation">; + def StringCompare : DiagGroup<"string-compare">; + def StringPlusInt : DiagGroup<"string-plus-int">; + def StringPlusChar : DiagGroup<"string-plus-char">; + def StrncatSize : DiagGroup<"strncat-size">; + def SwiftNameAttribute : DiagGroup<"swift-name-attribute">; + def IntInBoolContext : DiagGroup<"int-in-bool-context">; + def TautologicalTypeLimitCompare : DiagGroup<"tautological-type-limit-compare">; + def TautologicalUnsignedZeroCompare : DiagGroup<"tautological-unsigned-zero-compare">; + def TautologicalUnsignedCharZeroCompare : DiagGroup<"tautological-unsigned-char-zero-compare">; + def TautologicalUnsignedEnumZeroCompare : DiagGroup<"tautological-unsigned-enum-zero-compare">; + // For compatibility with GCC. Tautological comparison warnings for constants + // that are an extremal value of the type. + def TypeLimits : DiagGroup<"type-limits", [TautologicalTypeLimitCompare, + TautologicalUnsignedZeroCompare, + TautologicalUnsignedCharZeroCompare, + TautologicalUnsignedEnumZeroCompare]>; + // Additional tautological comparison warnings based on the expression, not + // only on its type. + def TautologicalValueRangeCompare : DiagGroup<"tautological-value-range-compare">; + def TautologicalInRangeCompare : DiagGroup<"tautological-constant-in-range-compare", + [TypeLimits, TautologicalValueRangeCompare]>; + def TautologicalOutOfRangeCompare : DiagGroup<"tautological-constant-out-of-range-compare">; + def TautologicalConstantCompare : DiagGroup<"tautological-constant-compare", + [TautologicalOutOfRangeCompare]>; + def TautologicalPointerCompare : DiagGroup<"tautological-pointer-compare">; + def TautologicalOverlapCompare : DiagGroup<"tautological-overlap-compare">; + def TautologicalBitwiseCompare : DiagGroup<"tautological-bitwise-compare">; + def TautologicalUndefinedCompare : DiagGroup<"tautological-undefined-compare">; + def TautologicalObjCBoolCompare : DiagGroup<"tautological-objc-bool-compare">; + def TautologicalCompare : DiagGroup<"tautological-compare", + [TautologicalConstantCompare, + TautologicalPointerCompare, + TautologicalOverlapCompare, + TautologicalBitwiseCompare, + TautologicalUndefinedCompare, + TautologicalObjCBoolCompare]>; + def HeaderHygiene : DiagGroup<"header-hygiene">; + def DuplicateDeclSpecifier : DiagGroup<"duplicate-decl-specifier">; + def CompareDistinctPointerType : DiagGroup<"compare-distinct-pointer-types">; + def GNUUnionCast : DiagGroup<"gnu-union-cast">; + def GNUVariableSizedTypeNotAtEnd : DiagGroup<"gnu-variable-sized-type-not-at-end">; + def Varargs : DiagGroup<"varargs">; + def XorUsedAsPow : DiagGroup<"xor-used-as-pow">; + + def Unsequenced : DiagGroup<"unsequenced">; + // GCC name for -Wunsequenced + def : DiagGroup<"sequence-point", [Unsequenced]>; + + // Preprocessor warnings. + def AmbiguousMacro : DiagGroup<"ambiguous-macro">; + def KeywordAsMacro : DiagGroup<"keyword-macro">; + def ReservedIdAsMacro : DiagGroup<"reserved-macro-identifier">; + def ReservedIdAsMacroAlias : DiagGroup<"reserved-id-macro", [ReservedIdAsMacro]>; + def RestrictExpansionMacro : DiagGroup<"restrict-expansion">; + + // Just silence warnings about -Wstrict-aliasing for now. + def : DiagGroup<"strict-aliasing=0">; + def : DiagGroup<"strict-aliasing=1">; + def : DiagGroup<"strict-aliasing=2">; + def : DiagGroup<"strict-aliasing">; + + // Just silence warnings about -Wstrict-overflow for now. + def : DiagGroup<"strict-overflow=0">; + def : DiagGroup<"strict-overflow=1">; + def : DiagGroup<"strict-overflow=2">; + def : DiagGroup<"strict-overflow=3">; + def : DiagGroup<"strict-overflow=4">; + def : DiagGroup<"strict-overflow=5">; + def : DiagGroup<"strict-overflow">; + + def InvalidOffsetof : DiagGroup<"invalid-offsetof">; + def StrictSelector : DiagGroup<"strict-selector-match">; + def MethodDuplicate : DiagGroup<"duplicate-method-match">; + def ObjCCStringFormat : DiagGroup<"cstring-format-directive">; + def CoveredSwitchDefault : DiagGroup<"covered-switch-default">; + def SwitchBool : DiagGroup<"switch-bool">; + def SwitchEnum : DiagGroup<"switch-enum">; + def Switch : DiagGroup<"switch">; + def ImplicitFallthroughPerFunction : + DiagGroup<"implicit-fallthrough-per-function">; + def ImplicitFallthrough : DiagGroup<"implicit-fallthrough", + [ImplicitFallthroughPerFunction]>; + def InvalidPPToken : DiagGroup<"invalid-pp-token">; + def Trigraphs : DiagGroup<"trigraphs">; + + def UndefinedReinterpretCast : DiagGroup<"undefined-reinterpret-cast">; + def ReinterpretBaseClass : DiagGroup<"reinterpret-base-class">; + def Unicode : DiagGroup<"unicode">; + def UninitializedMaybe : DiagGroup<"conditional-uninitialized">; + def UninitializedSometimes : DiagGroup<"sometimes-uninitialized">; + def UninitializedStaticSelfInit : DiagGroup<"static-self-init">; + def UninitializedConstReference : DiagGroup<"uninitialized-const-reference">; + def Uninitialized : DiagGroup<"uninitialized", [UninitializedSometimes, + UninitializedStaticSelfInit, + UninitializedConstReference]>; + def IgnoredPragmaIntrinsic : DiagGroup<"ignored-pragma-intrinsic">; + // #pragma optimize is often used to avoid to work around MSVC codegen bugs or + // to disable inlining. It's not completely clear what alternative to suggest + // (#pragma clang optimize, noinline) so suggest nothing for now. + def IgnoredPragmaOptimize : DiagGroup<"ignored-pragma-optimize">; + def UnknownPragmas : DiagGroup<"unknown-pragmas">; + def IgnoredPragmas : DiagGroup<"ignored-pragmas", + [IgnoredPragmaIntrinsic, IgnoredPragmaOptimize]>; + def PragmaClangAttribute : DiagGroup<"pragma-clang-attribute">; + def PragmaPackSuspiciousInclude : DiagGroup<"pragma-pack-suspicious-include">; + def PragmaPack : DiagGroup<"pragma-pack", [PragmaPackSuspiciousInclude]>; + def Pragmas : DiagGroup<"pragmas", [UnknownPragmas, IgnoredPragmas, + PragmaClangAttribute, PragmaPack]>; + def UnknownWarningOption : DiagGroup<"unknown-warning-option">; + def NSobjectAttribute : DiagGroup<"NSObject-attribute">; + def NSConsumedMismatch : DiagGroup<"nsconsumed-mismatch">; + def NSReturnsMismatch : DiagGroup<"nsreturns-mismatch">; + + def IndependentClassAttribute : DiagGroup<"IndependentClass-attribute">; + def UnknownAttributes : DiagGroup<"unknown-attributes">; + def IgnoredAttributes : DiagGroup<"ignored-attributes">; + def Attributes : DiagGroup<"attributes", [UnknownAttributes, + IgnoredAttributes]>; + def UnknownSanitizers : DiagGroup<"unknown-sanitizers">; + def UnnamedTypeTemplateArgs : DiagGroup<"unnamed-type-template-args", + [CXX98CompatUnnamedTypeTemplateArgs]>; + def UnsupportedFriend : DiagGroup<"unsupported-friend">; + def UnusedArgument : DiagGroup<"unused-argument">; + def UnusedCommandLineArgument : DiagGroup<"unused-command-line-argument">; + def IgnoredOptimizationArgument : DiagGroup<"ignored-optimization-argument">; + def InvalidCommandLineArgument : DiagGroup<"invalid-command-line-argument", + [IgnoredOptimizationArgument]>; + def UnusedComparison : DiagGroup<"unused-comparison">; + def UnusedExceptionParameter : DiagGroup<"unused-exception-parameter">; + def UnneededInternalDecl : DiagGroup<"unneeded-internal-declaration">; + def UnneededMemberFunction : DiagGroup<"unneeded-member-function">; + def UnusedPrivateField : DiagGroup<"unused-private-field">; + def UnusedFunction : DiagGroup<"unused-function", [UnneededInternalDecl]>; + def UnusedTemplate : DiagGroup<"unused-template", [UnneededInternalDecl]>; + def UnusedMemberFunction : DiagGroup<"unused-member-function", + [UnneededMemberFunction]>; + def UnusedLabel : DiagGroup<"unused-label">; + def UnusedLambdaCapture : DiagGroup<"unused-lambda-capture">; + def UnusedParameter : DiagGroup<"unused-parameter">; + def UnusedButSetParameter : DiagGroup<"unused-but-set-parameter">; + def UnusedResult : DiagGroup<"unused-result">; + def PotentiallyEvaluatedExpression : DiagGroup<"potentially-evaluated-expression">; + def UnevaluatedExpression : DiagGroup<"unevaluated-expression", + [PotentiallyEvaluatedExpression]>; + def UnusedValue : DiagGroup<"unused-value", [UnusedComparison, UnusedResult, + UnevaluatedExpression]>; + def UnusedConstVariable : DiagGroup<"unused-const-variable">; + def UnusedVariable : DiagGroup<"unused-variable", + [UnusedConstVariable]>; + def UnusedButSetVariable : DiagGroup<"unused-but-set-variable">; + def UnusedLocalTypedef : DiagGroup<"unused-local-typedef">; + def UnusedPropertyIvar : DiagGroup<"unused-property-ivar">; + def UnusedGetterReturnValue : DiagGroup<"unused-getter-return-value">; + def UsedButMarkedUnused : DiagGroup<"used-but-marked-unused">; + def UserDefinedLiterals : DiagGroup<"user-defined-literals">; + def UserDefinedWarnings : DiagGroup<"user-defined-warnings">; + def ReorderCtor : DiagGroup<"reorder-ctor">; + def ReorderInitList : DiagGroup<"reorder-init-list">; + def Reorder : DiagGroup<"reorder", [ReorderCtor, ReorderInitList]>; + def UndeclaredSelector : DiagGroup<"undeclared-selector">; + def ImplicitAtomic : DiagGroup<"implicit-atomic-properties">; + def AtomicAlignment : DiagGroup<"atomic-alignment">; + def CustomAtomic : DiagGroup<"custom-atomic-properties">; + def AtomicProperties : DiagGroup<"atomic-properties", + [ImplicitAtomic, CustomAtomic]>; + def ARCUnsafeRetainedAssign : DiagGroup<"arc-unsafe-retained-assign">; + def ARCRetainCycles : DiagGroup<"arc-retain-cycles">; + def ARCNonPodMemAccess : DiagGroup<"arc-non-pod-memaccess">; + def AutomaticReferenceCounting : DiagGroup<"arc", + [ARCUnsafeRetainedAssign, + ARCRetainCycles, + ARCNonPodMemAccess]>; + def ARCRepeatedUseOfWeakMaybe : DiagGroup<"arc-maybe-repeated-use-of-weak">; + def ARCRepeatedUseOfWeak : DiagGroup<"arc-repeated-use-of-weak", + [ARCRepeatedUseOfWeakMaybe]>; + def BlockCaptureAutoReleasing : DiagGroup<"block-capture-autoreleasing">; + def ObjCBridge : DiagGroup<"bridge-cast">; + + def DeallocInCategory:DiagGroup<"dealloc-in-category">; + def SelectorTypeMismatch : DiagGroup<"selector-type-mismatch">; + def Selector : DiagGroup<"selector", [SelectorTypeMismatch]>; + def Protocol : DiagGroup<"protocol">; + // No longer in use, preserve for backwards compatibility. + def : DiagGroup<"at-protocol">; + def PropertyAccessDotSyntax: DiagGroup<"property-access-dot-syntax">; + def PropertyAttr : DiagGroup<"property-attribute-mismatch">; + def SuperSubClassMismatch : DiagGroup<"super-class-method-mismatch">; + def OverridingMethodMismatch : DiagGroup<"overriding-method-mismatch">; + def VariadicMacros : DiagGroup<"variadic-macros">; + def VectorConversion : DiagGroup<"vector-conversion">; // clang specific + def VexingParse : DiagGroup<"vexing-parse">; + def VLAExtension : DiagGroup<"vla-extension">; + def VLA : DiagGroup<"vla", [VLAExtension]>; + def VolatileRegisterVar : DiagGroup<"volatile-register-var">; + def Visibility : DiagGroup<"visibility">; + def ZeroLengthArray : DiagGroup<"zero-length-array">; + def GNUZeroLineDirective : DiagGroup<"gnu-zero-line-directive">; + def GNUZeroVariadicMacroArguments : DiagGroup<"gnu-zero-variadic-macro-arguments">; + def MisleadingIndentation : DiagGroup<"misleading-indentation">; + + // This covers both the deprecated case (in C++98) + // and the extension case (in C++11 onwards). + def WritableStrings : DiagGroup<"writable-strings", [DeprecatedWritableStr]>; + + // GCC calls -Wdeprecated-writable-strings -Wwrite-strings. + // + // Bizarrely, this warning flag enables -fconst-strings in C. This is + // GCC-compatible, but really weird. + // + // FIXME: Should this affect C++11 (where this is an error, + // not just deprecated) or not? + def GCCWriteStrings : DiagGroup<"write-strings" , [WritableStrings]>; + + def CharSubscript : DiagGroup<"char-subscripts">; + def LargeByValueCopy : DiagGroup<"large-by-value-copy">; + def DuplicateArgDecl : DiagGroup<"duplicate-method-arg">; + def SignedEnumBitfield : DiagGroup<"signed-enum-bitfield">; + + def ReservedIdentifier : DiagGroup<"reserved-identifier", + [ReservedIdAsMacro]>; + + // Unreachable code warning groups. + // + // The goal is make -Wunreachable-code on by default, in -Wall, or at + // least actively used, with more noisy versions of the warning covered + // under separate flags. + // + def UnreachableCodeLoopIncrement : DiagGroup<"unreachable-code-loop-increment">; + def UnreachableCodeFallthrough : DiagGroup<"unreachable-code-fallthrough">; + def UnreachableCode : DiagGroup<"unreachable-code", + [UnreachableCodeLoopIncrement, + UnreachableCodeFallthrough]>; + def UnreachableCodeBreak : DiagGroup<"unreachable-code-break">; + def UnreachableCodeReturn : DiagGroup<"unreachable-code-return">; + def UnreachableCodeAggressive : DiagGroup<"unreachable-code-aggressive", + [UnreachableCode, + UnreachableCodeBreak, + UnreachableCodeReturn]>; + + // Aggregation warning settings. + + // Populate -Waddress with warnings from other groups. + def : DiagGroup<"address", [PointerBoolConversion, + StringCompare, + TautologicalPointerCompare]>; + + // -Widiomatic-parentheses contains warnings about 'idiomatic' + // missing parentheses; it is off by default. We do not include it + // in -Wparentheses because most users who use -Wparentheses explicitly + // do not want these warnings. + def ParenthesesOnEquality : DiagGroup<"parentheses-equality">; + def Parentheses : DiagGroup<"parentheses", + [LogicalOpParentheses, + LogicalNotParentheses, + BitwiseConditionalParentheses, + BitwiseOpParentheses, + ShiftOpParentheses, + OverloadedShiftOpParentheses, + ParenthesesOnEquality, + DanglingElse]>; + + // -Wconversion has its own warnings, but we split a few out for + // legacy reasons: + // - some people want just 64-to-32 warnings + // - conversion warnings with constant sources are on by default + // - conversion warnings for literals are on by default + // - bool-to-pointer conversion warnings are on by default + // - __null-to-integer conversion warnings are on by default + def Conversion : DiagGroup<"conversion", + [BoolConversion, + ConstantConversion, + EnumConversion, + BitFieldEnumConversion, + FloatConversion, + Shorten64To32, + IntConversion, + ImplicitIntConversion, + ImplicitFloatConversion, + LiteralConversion, + NonLiteralNullConversion, // (1-1)->pointer (etc) + NullConversion, // NULL->non-pointer + ObjCLiteralConversion, + SignConversion, + StringConversion]>, + DiagCategory<"Value Conversion Issue">; + + def Unused : DiagGroup<"unused", + [UnusedArgument, UnusedFunction, UnusedLabel, + // UnusedParameter, (matches GCC's behavior) + // UnusedTemplate, (clean-up libc++ before enabling) + // UnusedMemberFunction, (clean-up llvm before enabling) + UnusedPrivateField, UnusedLambdaCapture, + UnusedLocalTypedef, UnusedValue, UnusedVariable, + UnusedButSetVariable, UnusedPropertyIvar]>, + DiagCategory<"Unused Entity Issue">; + + // Format settings. + def FormatInvalidSpecifier : DiagGroup<"format-invalid-specifier">; + def FormatSecurity : DiagGroup<"format-security">; + def FormatNonStandard : DiagGroup<"format-non-iso">; + def FormatY2K : DiagGroup<"format-y2k">; + def FormatPedantic : DiagGroup<"format-pedantic">; + def FormatTypeConfusion : DiagGroup<"format-type-confusion">; + def Format : DiagGroup<"format", + [FormatExtraArgs, FormatZeroLength, NonNull, + FormatSecurity, FormatY2K, FormatInvalidSpecifier, + FormatInsufficientArgs]>, + DiagCategory<"Format String Issue">; + def FormatNonLiteral : DiagGroup<"format-nonliteral">; + def Format2 : DiagGroup<"format=2", + [FormatNonLiteral, FormatSecurity, FormatY2K]>; + + def TypeSafety : DiagGroup<"type-safety">; + + def IncompatibleExceptionSpec : DiagGroup<"incompatible-exception-spec">; + + def IntToVoidPointerCast : DiagGroup<"int-to-void-pointer-cast">; + def IntToPointerCast : DiagGroup<"int-to-pointer-cast", + [IntToVoidPointerCast]>; + def VoidPointerToEnumCast : DiagGroup<"void-pointer-to-enum-cast">; + def VoidPointerToIntCast : DiagGroup<"void-pointer-to-int-cast", + [VoidPointerToEnumCast]>; + def PointerToEnumCast : DiagGroup<"pointer-to-enum-cast", + [VoidPointerToEnumCast]>; + def PointerToIntCast : DiagGroup<"pointer-to-int-cast", + [PointerToEnumCast, VoidPointerToIntCast]>; + + def FUseLdPath : DiagGroup<"fuse-ld-path">; + + def Move : DiagGroup<"move", [ + PessimizingMove, + RedundantMove, + ReturnStdMove, + SelfMove + ]>; + + def Extra : DiagGroup<"extra", [ + DeprecatedCopy, + MissingFieldInitializers, + IgnoredQualifiers, + InitializerOverrides, + SemiBeforeMethodBody, + MissingMethodReturnType, + SignCompare, + UnusedParameter, + UnusedButSetParameter, + NullPointerArithmetic, + NullPointerSubtraction, + EmptyInitStatement, + StringConcatation, + FUseLdPath, + ]>; + + def Most : DiagGroup<"most", [ + BoolOperation, + CharSubscript, + Comment, + DeleteNonVirtualDtor, + Format, + ForLoopAnalysis, + FrameAddress, + Implicit, + InfiniteRecursion, + IntInBoolContext, + MismatchedTags, + MissingBraces, + Move, + MultiChar, + RangeLoopConstruct, + Reorder, + ReturnType, + SelfAssignment, + SelfMove, + SizeofArrayArgument, + SizeofArrayDecay, + StringPlusInt, + TautologicalCompare, + Trigraphs, + Uninitialized, + UnknownPragmas, + Unused, + VolatileRegisterVar, + ObjCMissingSuperCalls, + ObjCDesignatedInit, + ObjCFlexibleArray, + OverloadedVirtual, + PrivateExtern, + SelTypeCast, + ExternCCompat, + UserDefinedWarnings + ]>; + + // Thread Safety warnings + def ThreadSafetyAttributes : DiagGroup<"thread-safety-attributes">; + def ThreadSafetyAnalysis : DiagGroup<"thread-safety-analysis">; + def ThreadSafetyPrecise : DiagGroup<"thread-safety-precise">; + def ThreadSafetyReference : DiagGroup<"thread-safety-reference">; + def ThreadSafetyNegative : DiagGroup<"thread-safety-negative">; + def ThreadSafety : DiagGroup<"thread-safety", + [ThreadSafetyAttributes, + ThreadSafetyAnalysis, + ThreadSafetyPrecise, + ThreadSafetyReference]>; + def ThreadSafetyVerbose : DiagGroup<"thread-safety-verbose">; + def ThreadSafetyBeta : DiagGroup<"thread-safety-beta">; + + // Uniqueness Analysis warnings + def Consumed : DiagGroup<"consumed">; + + // Note that putting warnings in -Wall will not disable them by default. If a + // warning should be active _only_ when -Wall is passed in, mark it as + // DefaultIgnore in addition to putting it here. + def All : DiagGroup<"all", [Most, Parentheses, Switch, SwitchBool, + MisleadingIndentation]>; + + // Warnings that should be in clang-cl /w4. + def : DiagGroup<"CL4", [All, Extra]>; + + // Warnings enabled by -pedantic. This is magically filled in by TableGen. + def Pedantic : DiagGroup<"pedantic">; + + // Aliases. + def : DiagGroup<"", [Extra]>; // -W = -Wextra + def : DiagGroup<"endif-labels", [ExtraTokens]>; // -Wendif-labels=-Wextra-tokens + def : DiagGroup<"cpp", [PoundWarning]>; // -Wcpp = -W#warnings + def : DiagGroup<"comments", [Comment]>; // -Wcomments = -Wcomment + def : DiagGroup<"conversion-null", + [NullConversion]>; // -Wconversion-null = -Wnull-conversion + def : DiagGroup<"bool-conversions", + [BoolConversion]>; // -Wbool-conversions = -Wbool-conversion + def : DiagGroup<"int-conversions", + [IntConversion]>; // -Wint-conversions = -Wint-conversion + def : DiagGroup<"vector-conversions", + [VectorConversion]>; // -Wvector-conversions = -Wvector-conversion + def : DiagGroup<"unused-local-typedefs", [UnusedLocalTypedef]>; + // -Wunused-local-typedefs = -Wunused-local-typedef + + // A warning group for warnings that we want to have on by default in clang, + // but which aren't on by default in GCC. + def NonGCC : DiagGroup<"non-gcc", + [SignCompare, Conversion, LiteralRange]>; + + // A warning group for warnings about using C++11 features as extensions in + // earlier C++ versions. + def CXX11 : DiagGroup<"c++11-extensions", [CXX11ExtraSemi, CXX11InlineNamespace, + CXX11LongLong]>; + + // A warning group for warnings about using C++14 features as extensions in + // earlier C++ versions. + def CXX14 : DiagGroup<"c++14-extensions", [CXX14BinaryLiteral]>; + + // A warning group for warnings about using C++17 features as extensions in + // earlier C++ versions. + def CXX17 : DiagGroup<"c++17-extensions">; + + // A warning group for warnings about using C++20 features as extensions in + // earlier C++ versions. + def CXX20 : DiagGroup<"c++20-extensions", [CXX20Designator]>; + + // A warning group for warnings about using C++2b features as extensions in + // earlier C++ versions. + def CXX2b : DiagGroup<"c++2b-extensions">; + + def : DiagGroup<"c++0x-extensions", [CXX11]>; + def : DiagGroup<"c++1y-extensions", [CXX14]>; + def : DiagGroup<"c++1z-extensions", [CXX17]>; + def : DiagGroup<"c++2a-extensions", [CXX20]>; + + def DelegatingCtorCycles : + DiagGroup<"delegating-ctor-cycles">; + + // A warning group for warnings about using C11 features as extensions. + def C11 : DiagGroup<"c11-extensions">; + + // A warning group for warnings about using C99 features as extensions. + def C99 : DiagGroup<"c99-extensions", [C99Designator]>; + + // A warning group for warnings about using C2x features as extensions. + def C2x : DiagGroup<"c2x-extensions">; + + // A warning group for warnings about GCC extensions. + def GNU : DiagGroup<"gnu", [GNUAlignofExpression, GNUAnonymousStruct, + GNUAutoType, + GNUBinaryLiteral, GNUCaseRange, + GNUComplexInteger, GNUCompoundLiteralInitializer, + GNUConditionalOmittedOperand, GNUDesignator, + GNUEmptyInitializer, GNUEmptyStruct, + VLAExtension, GNUFlexibleArrayInitializer, + GNUFlexibleArrayUnionMember, GNUFoldingConstant, + GNUImaginaryConstant, GNUIncludeNext, + GNULabelsAsValue, + RedeclaredClassMember, GNURedeclaredEnum, + GNUStatementExpression, GNUStaticFloatInit, + GNUStringLiteralOperatorTemplate, + GNUUnionCast, GNUVariableSizedTypeNotAtEnd, + ZeroLengthArray, GNUZeroLineDirective, + GNUZeroVariadicMacroArguments]>; + // A warning group for warnings about code that clang accepts but gcc doesn't. + def GccCompat : DiagGroup<"gcc-compat">; + + // A warning group for warnings about code that may be incompatible on AIX. + def AIXCompat : DiagGroup<"aix-compat">; + + // Warnings for Microsoft extensions. + def MicrosoftCharize : DiagGroup<"microsoft-charize">; + def MicrosoftDrectveSection : DiagGroup<"microsoft-drectve-section">; + def MicrosoftInclude : DiagGroup<"microsoft-include">; + def MicrosoftCppMacro : DiagGroup<"microsoft-cpp-macro">; + def MicrosoftFixedEnum : DiagGroup<"microsoft-fixed-enum">; + def MicrosoftSealed : DiagGroup<"microsoft-sealed">; + def MicrosoftAbstract : DiagGroup<"microsoft-abstract">; + def MicrosoftUnqualifiedFriend : DiagGroup<"microsoft-unqualified-friend">; + def MicrosoftExceptionSpec : DiagGroup<"microsoft-exception-spec">; + def MicrosoftUsingDecl : DiagGroup<"microsoft-using-decl">; + def MicrosoftMutableReference : DiagGroup<"microsoft-mutable-reference">; + def MicrosoftPureDefinition : DiagGroup<"microsoft-pure-definition">; + def MicrosoftUnionMemberReference : DiagGroup< + "microsoft-union-member-reference">; + def MicrosoftExplicitConstructorCall : DiagGroup< + "microsoft-explicit-constructor-call">; + def MicrosoftEnumValue : DiagGroup<"microsoft-enum-value">; + def MicrosoftDefaultArgRedefinition : + DiagGroup<"microsoft-default-arg-redefinition">; + def MicrosoftTemplateShadow : DiagGroup<"microsoft-template-shadow">; + def MicrosoftTemplate : DiagGroup<"microsoft-template", [MicrosoftTemplateShadow]>; + def MicrosoftInconsistentDllImport : DiagGroup<"inconsistent-dllimport">; + def MicrosoftRedeclareStatic : DiagGroup<"microsoft-redeclare-static">; + def MicrosoftEnumForwardReference : + DiagGroup<"microsoft-enum-forward-reference">; + def MicrosoftGoto : DiagGroup<"microsoft-goto">; + def MicrosoftFlexibleArray : DiagGroup<"microsoft-flexible-array">; + def MicrosoftExtraQualification : DiagGroup<"microsoft-extra-qualification">; + def MicrosoftCast : DiagGroup<"microsoft-cast">; + def MicrosoftConstInit : DiagGroup<"microsoft-const-init">; + def MicrosoftVoidPseudoDtor : DiagGroup<"microsoft-void-pseudo-dtor">; + def MicrosoftAnonTag : DiagGroup<"microsoft-anon-tag">; + def MicrosoftCommentPaste : DiagGroup<"microsoft-comment-paste">; + def MicrosoftEndOfFile : DiagGroup<"microsoft-end-of-file">; + def MicrosoftInaccessibleBase : DiagGroup<"microsoft-inaccessible-base">; + def MicrosoftStaticAssert : DiagGroup<"microsoft-static-assert">; + + // Aliases. + def : DiagGroup<"msvc-include", [MicrosoftInclude]>; + // -Wmsvc-include = -Wmicrosoft-include + + // Warnings group for warnings about Microsoft extensions. + def Microsoft : DiagGroup<"microsoft", + [MicrosoftCharize, MicrosoftDrectveSection, MicrosoftInclude, + MicrosoftCppMacro, MicrosoftFixedEnum, MicrosoftSealed, MicrosoftAbstract, + MicrosoftUnqualifiedFriend, MicrosoftExceptionSpec, MicrosoftUsingDecl, + MicrosoftMutableReference, MicrosoftPureDefinition, + MicrosoftUnionMemberReference, MicrosoftExplicitConstructorCall, + MicrosoftEnumValue, MicrosoftDefaultArgRedefinition, MicrosoftTemplate, + MicrosoftRedeclareStatic, MicrosoftEnumForwardReference, MicrosoftGoto, + MicrosoftFlexibleArray, MicrosoftExtraQualification, MicrosoftCast, + MicrosoftConstInit, MicrosoftVoidPseudoDtor, MicrosoftAnonTag, + MicrosoftCommentPaste, MicrosoftEndOfFile, MicrosoftStaticAssert, + MicrosoftInconsistentDllImport]>; + + def ClangClPch : DiagGroup<"clang-cl-pch">; + + def ObjCNonUnifiedException : DiagGroup<"objc-nonunified-exceptions">; + + def ObjCProtocolMethodImpl : DiagGroup<"objc-protocol-method-implementation">; + + def ObjCNoPropertyAutoSynthesis : DiagGroup<"objc-property-synthesis">; + + // ObjC API warning groups. + def ObjCRedundantLiteralUse : DiagGroup<"objc-redundant-literal-use">; + def ObjCRedundantAPIUse : DiagGroup<"objc-redundant-api-use", [ + ObjCRedundantLiteralUse + ]>; + + def ObjCCocoaAPI : DiagGroup<"objc-cocoa-api", [ + ObjCRedundantAPIUse + ]>; + + def ObjCStringComparison : DiagGroup<"objc-string-compare">; + def ObjCStringConcatenation : DiagGroup<"objc-string-concatenation">; + def ObjCLiteralComparison : DiagGroup<"objc-literal-compare", [ + ObjCStringComparison + ]>; + + def ObjCSignedCharBool : DiagGroup<"objc-signed-char-bool", + [ObjCSignedCharBoolImplicitIntConversion, + ObjCSignedCharBoolImplicitFloatConversion, + ObjCBoolConstantConversion, + TautologicalObjCBoolCompare]>; + + def ObjCPotentiallyDirectSelector : DiagGroup<"potentially-direct-selector">; + def ObjCStrictPotentiallyDirectSelector : + DiagGroup<"strict-potentially-direct-selector", + [ObjCPotentiallyDirectSelector]>; + + // Inline ASM warnings. + def ASMOperandWidths : DiagGroup<"asm-operand-widths">; + def ASM : DiagGroup<"asm", [ + ASMOperandWidths + ]>; + + // Linker warnings. + def LinkerWarnings : DiagGroup<"linker-warnings">; + + // OpenMP warnings. + def SourceUsesOpenMP : DiagGroup<"source-uses-openmp">; + def OpenMPClauses : DiagGroup<"openmp-clauses">; + def OpenMPLoopForm : DiagGroup<"openmp-loop-form">; + def OpenMPMapping : DiagGroup<"openmp-mapping">; + def OpenMPTarget : DiagGroup<"openmp-target", [OpenMPMapping]>; + def OpenMPPre51Compat : DiagGroup<"pre-openmp-51-compat">; + def OpenMP51Ext : DiagGroup<"openmp-51-extensions">; + def OpenMP : DiagGroup<"openmp", [ + SourceUsesOpenMP, OpenMPClauses, OpenMPLoopForm, OpenMPTarget, + OpenMPMapping, OpenMP51Ext + ]>; + + // Backend warnings. + def BackendInlineAsm : DiagGroup<"inline-asm">; + def BackendSourceMgr : DiagGroup<"source-mgr">; + def BackendFrameLargerThan : DiagGroup<"frame-larger-than">; + // Compatibility flag name from old versions of Clang. + def : DiagGroup<"frame-larger-than=", [BackendFrameLargerThan]>; + def BackendPlugin : DiagGroup<"backend-plugin">; + def RemarkBackendPlugin : DiagGroup<"remark-backend-plugin">; + def BackendOptimizationRemark : DiagGroup<"pass">; + def BackendOptimizationRemarkMissed : DiagGroup<"pass-missed">; + def BackendOptimizationRemarkAnalysis : DiagGroup<"pass-analysis">; + def BackendOptimizationFailure : DiagGroup<"pass-failed">; + def BackendWarningAttributes : DiagGroup<"attribute-warning">; + + // Instrumentation based profiling warnings. + def ProfileInstrMissing : DiagGroup<"profile-instr-missing">; + def ProfileInstrOutOfDate : DiagGroup<"profile-instr-out-of-date">; + def ProfileInstrUnprofiled : DiagGroup<"profile-instr-unprofiled">; + + // AddressSanitizer frontend instrumentation remarks. + def SanitizeAddressRemarks : DiagGroup<"sanitize-address">; + + // Issues with serialized diagnostics. + def SerializedDiagnostics : DiagGroup<"serialized-diagnostics">; + + // A warning group for warnings about code that clang accepts when + // compiling CUDA C/C++ but which is not compatible with the CUDA spec. + def CudaCompat : DiagGroup<"cuda-compat">; + + // Warning about unknown CUDA SDK version. + def CudaUnknownVersion: DiagGroup<"unknown-cuda-version">; + + // A warning group for warnings about features supported by HIP but + // ignored by CUDA. + def HIPOnly : DiagGroup<"hip-only">; + + // Warnings which cause linking of the runtime libraries like + // libc and the CRT to be skipped. + def AVRRtlibLinkingQuirks : DiagGroup<"avr-rtlib-linking-quirks">; + + // A warning group for things that will change semantics in the future. + def FutureCompat : DiagGroup<"future-compat">; + + def InvalidOrNonExistentDirectory : DiagGroup<"invalid-or-nonexistent-directory">; + + def OptionIgnored : DiagGroup<"option-ignored">; + + def UnknownArgument : DiagGroup<"unknown-argument">; + + // A warning group for warnings about code that clang accepts when + // compiling OpenCL C/C++ but which is not compatible with the SPIR spec. + def SpirCompat : DiagGroup<"spir-compat">; + + // Warning for the GlobalISel options. + def GlobalISel : DiagGroup<"global-isel">; + + // A warning group specifically for warnings related to function + // multiversioning. + def FunctionMultiVersioning : DiagGroup<"function-multiversion">; + + def NoDeref : DiagGroup<"noderef">; + + // A group for cross translation unit static analysis related warnings. + def CrossTU : DiagGroup<"ctu">; + + def CTADMaybeUnsupported : DiagGroup<"ctad-maybe-unsupported">; + + def FortifySource : DiagGroup<"fortify-source">; + + def MaxTokens : DiagGroup<"max-tokens"> { + code Documentation = [{ + The warning is issued if the number of pre-processor tokens exceeds + the token limit, which can be set in three ways: + + 1. As a limit at a specific point in a file, using the ``clang max_tokens_here`` + pragma: + + .. code-block: c++ + #pragma clang max_tokens_here 1234 + + 2. As a per-translation unit limit, using the ``-fmax-tokens=`` command-line + flag: + + .. code-block: console + clang -c a.cpp -fmax-tokens=1234 + + 3. As a per-translation unit limit using the ``clang max_tokens_total`` pragma, + which works like and overrides the ``-fmax-tokens=`` flag: + + .. code-block: c++ + #pragma clang max_tokens_total 1234 + + These limits can be helpful in limiting code growth through included files. + + Setting a token limit of zero means no limit. + + Note that the warning is disabled by default, so -Wmax-tokens must be used + in addition with the pragmas or -fmax-tokens flag to get any warnings. + }]; + } + + def WebAssemblyExceptionSpec : DiagGroup<"wasm-exception-spec">; + + def RTTI : DiagGroup<"rtti">; + + def OpenCLCoreFeaturesDiagGroup : DiagGroup<"pedantic-core-features">; + + // Warnings and extensions to make preprocessor macro usage pedantic. + def PedanticMacros : DiagGroup<"pedantic-macros", + [DeprecatedPragma, + MacroRedefined, + BuiltinMacroRedefined, + RestrictExpansionMacro]>; +diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td +index 0e803ee028ce..d06cd0041d19 100644 +--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td ++++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td +@@ -1,11370 +1,11373 @@ + //==--- DiagnosticSemaKinds.td - libsema diagnostics ----------------------===// + // + // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. + // See https://llvm.org/LICENSE.txt for license information. + // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + // + //===----------------------------------------------------------------------===// + + //===----------------------------------------------------------------------===// + // Semantic Analysis + //===----------------------------------------------------------------------===// + + let Component = "Sema" in { + let CategoryName = "Semantic Issue" in { + def note_previous_decl : Note<"%0 declared here">; + def note_entity_declared_at : Note<"%0 declared here">; + def note_callee_decl : Note<"%0 declared here">; + def note_defined_here : Note<"%0 defined here">; + + // For loop analysis + def warn_variables_not_in_loop_body : Warning< + "variable%select{s| %1|s %1 and %2|s %1, %2, and %3|s %1, %2, %3, and %4}0 " + "used in loop condition not modified in loop body">, + InGroup, DefaultIgnore; + def warn_redundant_loop_iteration : Warning< + "variable %0 is %select{decremented|incremented}1 both in the loop header " + "and in the loop body">, + InGroup, DefaultIgnore; + def note_loop_iteration_here : Note<"%select{decremented|incremented}0 here">; + + def warn_duplicate_enum_values : Warning< + "element %0 has been implicitly assigned %1 which another element has " + "been assigned">, InGroup>, DefaultIgnore; + def note_duplicate_element : Note<"element %0 also has value %1">; + + // Absolute value functions + def warn_unsigned_abs : Warning< + "taking the absolute value of unsigned type %0 has no effect">, + InGroup; + def note_remove_abs : Note< + "remove the call to '%0' since unsigned values cannot be negative">; + def warn_abs_too_small : Warning< + "absolute value function %0 given an argument of type %1 but has parameter " + "of type %2 which may cause truncation of value">, InGroup; + def warn_wrong_absolute_value_type : Warning< + "using %select{integer|floating point|complex}1 absolute value function %0 " + "when argument is of %select{integer|floating point|complex}2 type">, + InGroup; + def note_replace_abs_function : Note<"use function '%0' instead">; + def warn_pointer_abs : Warning< + "taking the absolute value of %select{pointer|function|array}0 type %1 is suspicious">, + InGroup; + + def warn_max_unsigned_zero : Warning< + "taking the max of " + "%select{a value and unsigned zero|unsigned zero and a value}0 " + "is always equal to the other value">, + InGroup; + def note_remove_max_call : Note< + "remove call to max function and unsigned zero argument">; + + def warn_infinite_recursive_function : Warning< + "all paths through this function will call itself">, + InGroup, DefaultIgnore; + + def warn_comma_operator : Warning<"possible misuse of comma operator here">, + InGroup>, DefaultIgnore; + def note_cast_to_void : Note<"cast expression to void to silence warning">; + + // Constant expressions + def err_expr_not_ice : Error< + "expression is not an %select{integer|integral}0 constant expression">; + def ext_expr_not_ice : Extension< + "expression is not an %select{integer|integral}0 constant expression; " + "folding it to a constant is a GNU extension">, InGroup; + def err_typecheck_converted_constant_expression : Error< + "value of type %0 is not implicitly convertible to %1">; + def err_typecheck_converted_constant_expression_disallowed : Error< + "conversion from %0 to %1 is not allowed in a converted constant expression">; + def err_typecheck_converted_constant_expression_indirect : Error< + "conversion from %0 to %1 in converted constant expression would " + "bind reference to a temporary">; + def err_expr_not_cce : Error< + "%select{case value|enumerator value|non-type template argument|" + "array size|explicit specifier argument|noexcept specifier argument}0 " + "is not a constant expression">; + def ext_cce_narrowing : ExtWarn< + "%select{case value|enumerator value|non-type template argument|" + "array size|explicit specifier argument|noexcept specifier argument}0 " + "%select{cannot be narrowed from type %2 to %3|" + "evaluates to %2, which cannot be narrowed to type %3}1">, + InGroup, DefaultError, SFINAEFailure; + def err_ice_not_integral : Error< + "%select{integer|integral}1 constant expression must have " + "%select{integer|integral or unscoped enumeration}1 type, not %0">; + def err_ice_incomplete_type : Error< + "integral constant expression has incomplete class type %0">; + def err_ice_explicit_conversion : Error< + "integral constant expression requires explicit conversion from %0 to %1">; + def note_ice_conversion_here : Note< + "conversion to %select{integral|enumeration}0 type %1 declared here">; + def err_ice_ambiguous_conversion : Error< + "ambiguous conversion from type %0 to an integral or unscoped " + "enumeration type">; + def err_ice_too_large : Error< + "integer constant expression evaluates to value %0 that cannot be " + "represented in a %1-bit %select{signed|unsigned}2 integer type">; + def err_expr_not_string_literal : Error<"expression is not a string literal">; + + // Semantic analysis of constant literals. + def ext_predef_outside_function : Warning< + "predefined identifier is only valid inside function">, + InGroup>; + def warn_float_overflow : Warning< + "magnitude of floating-point constant too large for type %0; maximum is %1">, + InGroup; + def warn_float_underflow : Warning< + "magnitude of floating-point constant too small for type %0; minimum is %1">, + InGroup; + def warn_double_const_requires_fp64 : Warning< + "double precision constant requires %select{cl_khr_fp64|cl_khr_fp64 and __opencl_c_fp64}0, " + "casting to single precision">; + def err_half_const_requires_fp16 : Error< + "half precision constant requires cl_khr_fp16">; + + // C99 variable-length arrays + def ext_vla : Extension<"variable length arrays are a C99 feature">, + InGroup; + def warn_vla_used : Warning<"variable length array used">, + InGroup, DefaultIgnore; + def err_vla_in_sfinae : Error< + "variable length array cannot be formed during template argument deduction">; + def err_array_star_in_function_definition : Error< + "variable length array must be bound in function definition">; + def err_vla_decl_in_file_scope : Error< + "variable length array declaration not allowed at file scope">; + def err_vla_decl_has_static_storage : Error< + "variable length array declaration cannot have 'static' storage duration">; + def err_vla_decl_has_extern_linkage : Error< + "variable length array declaration cannot have 'extern' linkage">; + def ext_vla_folded_to_constant : ExtWarn< + "variable length array folded to constant array as an extension">, + InGroup; + def err_vla_unsupported : Error< + "variable length arrays are not supported for the current target">; + def note_vla_unsupported : Note< + "variable length arrays are not supported for the current target">; + + // C99 variably modified types + def err_variably_modified_template_arg : Error< + "variably modified type %0 cannot be used as a template argument">; + def err_variably_modified_nontype_template_param : Error< + "non-type template parameter of variably modified type %0">; + def err_variably_modified_new_type : Error< + "'new' cannot allocate object of variably modified type %0">; + + // C99 Designated Initializers + def ext_designated_init : Extension< + "designated initializers are a C99 feature">, InGroup; + def err_array_designator_negative : Error< + "array designator value '%0' is negative">; + def err_array_designator_empty_range : Error< + "array designator range [%0, %1] is empty">; + def err_array_designator_non_array : Error< + "array designator cannot initialize non-array type %0">; + def err_array_designator_too_large : Error< + "array designator index (%0) exceeds array bounds (%1)">; + def err_field_designator_non_aggr : Error< + "field designator cannot initialize a " + "%select{non-struct, non-union|non-class}0 type %1">; + def err_field_designator_unknown : Error< + "field designator %0 does not refer to any field in type %1">; + def err_field_designator_nonfield : Error< + "field designator %0 does not refer to a non-static data member">; + def note_field_designator_found : Note<"field designator refers here">; + def err_designator_for_scalar_or_sizeless_init : Error< + "designator in initializer for %select{scalar|indivisible sizeless}0 " + "type %1">; + def warn_initializer_overrides : Warning< + "initializer %select{partially |}0overrides prior initialization of " + "this subobject">, InGroup; + def ext_initializer_overrides : ExtWarn, + InGroup, SFINAEFailure; + def err_initializer_overrides_destructed : Error< + "initializer would partially override prior initialization of object of " + "type %1 with non-trivial destruction">; + def note_previous_initializer : Note< + "previous initialization %select{|with side effects }0is here" + "%select{| (side effects will not occur at run time)}0">; + def err_designator_into_flexible_array_member : Error< + "designator into flexible array member subobject">; + def note_flexible_array_member : Note< + "initialized flexible array member %0 is here">; + def ext_flexible_array_init : Extension< + "flexible array initialization is a GNU extension">, InGroup; + + // C++20 designated initializers + def ext_cxx_designated_init : Extension< + "designated initializers are a C++20 extension">, InGroup; + def warn_cxx17_compat_designated_init : Warning< + "designated initializers are incompatible with C++ standards before C++20">, + InGroup, DefaultIgnore; + def ext_designated_init_mixed : ExtWarn< + "mixture of designated and non-designated initializers in the same " + "initializer list is a C99 extension">, InGroup; + def note_designated_init_mixed : Note< + "first non-designated initializer is here">; + def ext_designated_init_array : ExtWarn< + "array designators are a C99 extension">, InGroup; + def ext_designated_init_nested : ExtWarn< + "nested designators are a C99 extension">, InGroup; + def ext_designated_init_reordered : ExtWarn< + "ISO C++ requires field designators to be specified in declaration order; " + "field %1 will be initialized after field %0">, InGroup, + SFINAEFailure; + def note_previous_field_init : Note< + "previous initialization for field %0 is here">; + def ext_designated_init_brace_elision : ExtWarn< + "brace elision for designated initializer is a C99 extension">, + InGroup, SFINAEFailure; + + // Declarations. + def ext_plain_complex : ExtWarn< + "plain '_Complex' requires a type specifier; assuming '_Complex double'">; + def ext_imaginary_constant : Extension< + "imaginary constants are a GNU extension">, InGroup; + def ext_integer_complex : Extension< + "complex integer types are a GNU extension">, InGroup; + + def err_invalid_saturation_spec : Error<"'_Sat' specifier is only valid on " + "'_Fract' or '_Accum', not '%0'">; + def err_invalid_sign_spec : Error<"'%0' cannot be signed or unsigned">; + def err_invalid_width_spec : Error< + "'%select{|short|long|long long}0 %1' is invalid">; + def err_invalid_complex_spec : Error<"'_Complex %0' is invalid">; + + def ext_auto_type_specifier : ExtWarn< + "'auto' type specifier is a C++11 extension">, InGroup; + def warn_auto_storage_class : Warning< + "'auto' storage class specifier is redundant and incompatible with C++11">, + InGroup, DefaultIgnore; + + def warn_deprecated_register : Warning< + "'register' storage class specifier is deprecated " + "and incompatible with C++17">, InGroup; + def ext_register_storage_class : ExtWarn< + "ISO C++17 does not allow 'register' storage class specifier">, + DefaultError, InGroup; + + def err_invalid_decl_spec_combination : Error< + "cannot combine with previous '%0' declaration specifier">; + def err_invalid_vector_decl_spec_combination : Error< + "cannot combine with previous '%0' declaration specifier. " + "'__vector' must be first">; + def err_invalid_pixel_decl_spec_combination : Error< + "'__pixel' must be preceded by '__vector'. " + "'%0' declaration specifier not allowed here">; + def err_invalid_vector_bool_decl_spec : Error< + "cannot use '%0' with '__vector bool'">; + def err_invalid_vector_long_decl_spec : Error< + "cannot use 'long' with '__vector'">; + def err_invalid_vector_float_decl_spec : Error< + "cannot use 'float' with '__vector'">; + def err_invalid_vector_double_decl_spec : Error < + "use of 'double' with '__vector' requires VSX support to be enabled " + "(available on POWER7 or later)">; + def err_invalid_vector_bool_int128_decl_spec : Error < + "use of '__int128' with '__vector bool' requires VSX support enabled (on " + "POWER10 or later)">; + def err_invalid_vector_long_long_decl_spec : Error < + "use of 'long long' with '__vector bool' requires VSX support (available on " + "POWER7 or later) or extended Altivec support (available on POWER8 or later) " + "to be enabled">; + def err_invalid_vector_long_double_decl_spec : Error< + "cannot use 'long double' with '__vector'">; + def warn_vector_long_decl_spec_combination : Warning< + "Use of 'long' with '__vector' is deprecated">, InGroup; + + def err_redeclaration_different_type : Error< + "redeclaration of %0 with a different type%diff{: $ vs $|}1,2">; + def err_bad_variable_name : Error< + "%0 cannot be the name of a variable or data member">; + def err_bad_parameter_name : Error< + "%0 cannot be the name of a parameter">; + def err_bad_parameter_name_template_id : Error< + "parameter name cannot have template arguments">; + def ext_parameter_name_omitted_c2x : ExtWarn< + "omitting the parameter name in a function definition is a C2x extension">, + InGroup; + def err_anyx86_interrupt_attribute : Error< + "%select{x86|x86-64}0 'interrupt' attribute only applies to functions that " + "have %select{a 'void' return type|" + "only a pointer parameter optionally followed by an integer parameter|" + "a pointer as the first parameter|a %2 type as the second parameter}1">; + def err_anyx86_interrupt_called : Error< + "interrupt service routine cannot be called directly">; + def warn_anyx86_interrupt_regsave : Warning< + "interrupt service routine should only call a function" + " with attribute 'no_caller_saved_registers'">, + InGroup>; + def warn_arm_interrupt_calling_convention : Warning< + "call to function without interrupt attribute could clobber interruptee's VFP registers">, + InGroup; + def warn_interrupt_attribute_invalid : Warning< + "%select{MIPS|MSP430|RISC-V}0 'interrupt' attribute only applies to " + "functions that have %select{no parameters|a 'void' return type}1">, + InGroup; + def warn_riscv_repeated_interrupt_attribute : Warning< + "repeated RISC-V 'interrupt' attribute">, InGroup; + def note_riscv_repeated_interrupt_attribute : Note< + "repeated RISC-V 'interrupt' attribute is here">; + def warn_unused_parameter : Warning<"unused parameter %0">, + InGroup, DefaultIgnore; + def warn_unused_but_set_parameter : Warning<"parameter %0 set but not used">, + InGroup, DefaultIgnore; + def warn_unused_variable : Warning<"unused variable %0">, + InGroup, DefaultIgnore; + def warn_unused_but_set_variable : Warning<"variable %0 set but not used">, + InGroup, DefaultIgnore; + def warn_unused_local_typedef : Warning< + "unused %select{typedef|type alias}0 %1">, + InGroup, DefaultIgnore; + def warn_unused_property_backing_ivar : + Warning<"ivar %0 which backs the property is not " + "referenced in this property's accessor">, + InGroup, DefaultIgnore; + def warn_unused_const_variable : Warning<"unused variable %0">, + InGroup, DefaultIgnore; + def warn_unused_exception_param : Warning<"unused exception parameter %0">, + InGroup, DefaultIgnore; + def warn_decl_in_param_list : Warning< + "declaration of %0 will not be visible outside of this function">, + InGroup; + def warn_redefinition_in_param_list : Warning< + "redefinition of %0 will not be visible outside of this function">, + InGroup; + def warn_empty_parens_are_function_decl : Warning< + "empty parentheses interpreted as a function declaration">, + InGroup; + def warn_parens_disambiguated_as_function_declaration : Warning< + "parentheses were disambiguated as a function declaration">, + InGroup; + def warn_parens_disambiguated_as_variable_declaration : Warning< + "parentheses were disambiguated as redundant parentheses around declaration " + "of variable named %0">, InGroup; + def warn_redundant_parens_around_declarator : Warning< + "redundant parentheses surrounding declarator">, + InGroup>, DefaultIgnore; + def note_additional_parens_for_variable_declaration : Note< + "add a pair of parentheses to declare a variable">; + def note_raii_guard_add_name : Note< + "add a variable name to declare a %0 initialized with %1">; + def note_function_style_cast_add_parentheses : Note< + "add enclosing parentheses to perform a function-style cast">; + def note_remove_parens_for_variable_declaration : Note< + "remove parentheses to silence this warning">; + def note_empty_parens_function_call : Note< + "change this ',' to a ';' to call %0">; + def note_empty_parens_default_ctor : Note< + "remove parentheses to declare a variable">; + def note_empty_parens_zero_initialize : Note< + "replace parentheses with an initializer to declare a variable">; + def warn_unused_function : Warning<"unused function %0">, + InGroup, DefaultIgnore; + def warn_unused_template : Warning<"unused %select{function|variable}0 template %1">, + InGroup, DefaultIgnore; + def warn_unused_member_function : Warning<"unused member function %0">, + InGroup, DefaultIgnore; + def warn_used_but_marked_unused: Warning<"%0 was marked unused but was used">, + InGroup, DefaultIgnore; + def warn_unneeded_internal_decl : Warning< + "%select{function|variable}0 %1 is not needed and will not be emitted">, + InGroup, DefaultIgnore; + def warn_unneeded_static_internal_decl : Warning< + "'static' function %0 declared in header file " + "should be declared 'static inline'">, + InGroup, DefaultIgnore; + def warn_unneeded_member_function : Warning< + "member function %0 is not needed and will not be emitted">, + InGroup, DefaultIgnore; + def warn_unused_private_field: Warning<"private field %0 is not used">, + InGroup, DefaultIgnore; + def warn_unused_lambda_capture: Warning<"lambda capture %0 is not " + "%select{used|required to be captured for this use}1">, + InGroup, DefaultIgnore; + + def warn_reserved_extern_symbol: Warning< + "identifier %0 is reserved because %select{" + "|" // ReservedIdentifierStatus::NotReserved + "it starts with '_' at global scope|" + "it starts with '__'|" + "it starts with '_' followed by a capital letter|" + "it contains '__'}1">, + InGroup, DefaultIgnore; + + def warn_parameter_size: Warning< + "%0 is a large (%1 bytes) pass-by-value argument; " + "pass it by reference instead ?">, InGroup; + def warn_return_value_size: Warning< + "return value of %0 is a large (%1 bytes) pass-by-value object; " + "pass it by reference instead ?">, InGroup; + def warn_return_value_udt: Warning< + "%0 has C-linkage specified, but returns user-defined type %1 which is " + "incompatible with C">, InGroup; + def warn_return_value_udt_incomplete: Warning< + "%0 has C-linkage specified, but returns incomplete type %1 which could be " + "incompatible with C">, InGroup; + def warn_implicit_function_decl : Warning< + "implicit declaration of function %0">, + InGroup, DefaultIgnore; + def ext_implicit_function_decl : ExtWarn< + "implicit declaration of function %0 is invalid in C99">, + InGroup; + def note_function_suggestion : Note<"did you mean %0?">; + + def err_ellipsis_first_param : Error< + "ISO C requires a named parameter before '...'">; + def err_declarator_need_ident : Error<"declarator requires an identifier">; + def err_language_linkage_spec_unknown : Error<"unknown linkage language">; + def err_language_linkage_spec_not_ascii : Error< + "string literal in language linkage specifier cannot have an " + "encoding-prefix">; + def ext_use_out_of_scope_declaration : ExtWarn< + "use of out-of-scope declaration of %0%select{| whose type is not " + "compatible with that of an implicit declaration}1">, + InGroup>; + def err_inline_non_function : Error< + "'inline' can only appear on functions%select{| and non-local variables}0">; + def err_noreturn_non_function : Error< + "'_Noreturn' can only appear on functions">; + def warn_qual_return_type : Warning< + "'%0' type qualifier%s1 on return type %plural{1:has|:have}1 no effect">, + InGroup, DefaultIgnore; + def warn_deprecated_redundant_constexpr_static_def : Warning< + "out-of-line definition of constexpr static data member is redundant " + "in C++17 and is deprecated">, + InGroup, DefaultIgnore; + + def warn_decl_shadow : + Warning<"declaration shadows a %select{" + "local variable|" + "variable in %2|" + "static data member of %2|" + "field of %2|" + "typedef in %2|" + "type alias in %2|" + "structured binding}1">, + InGroup, DefaultIgnore; + def warn_decl_shadow_uncaptured_local : + Warning, + InGroup, DefaultIgnore; + def warn_ctor_parm_shadows_field: + Warning<"constructor parameter %0 shadows the field %1 of %2">, + InGroup, DefaultIgnore; + def warn_modifying_shadowing_decl : + Warning<"modifying constructor parameter %0 that shadows a " + "field of %1">, + InGroup, DefaultIgnore; + + // C++ decomposition declarations + def err_decomp_decl_context : Error< + "decomposition declaration not permitted in this context">; + def warn_cxx14_compat_decomp_decl : Warning< + "decomposition declarations are incompatible with " + "C++ standards before C++17">, DefaultIgnore, InGroup; + def ext_decomp_decl : ExtWarn< + "decomposition declarations are a C++17 extension">, InGroup; + def ext_decomp_decl_cond : ExtWarn< + "ISO C++17 does not permit structured binding declaration in a condition">, + InGroup>; + def err_decomp_decl_spec : Error< + "decomposition declaration cannot be declared " + "%plural{1:'%1'|:with '%1' specifiers}0">; + def ext_decomp_decl_spec : ExtWarn< + "decomposition declaration declared " + "%plural{1:'%1'|:with '%1' specifiers}0 is a C++20 extension">, + InGroup; + def warn_cxx17_compat_decomp_decl_spec : Warning< + "decomposition declaration declared " + "%plural{1:'%1'|:with '%1' specifiers}0 " + "is incompatible with C++ standards before C++20">, + InGroup, DefaultIgnore; + def err_decomp_decl_type : Error< + "decomposition declaration cannot be declared with type %0; " + "declared type must be 'auto' or reference to 'auto'">; + def err_decomp_decl_parens : Error< + "decomposition declaration cannot be declared with parentheses">; + def err_decomp_decl_template : Error< + "decomposition declaration template not supported">; + def err_decomp_decl_not_alone : Error< + "decomposition declaration must be the only declaration in its group">; + def err_decomp_decl_requires_init : Error< + "decomposition declaration %0 requires an initializer">; + def err_decomp_decl_wrong_number_bindings : Error< + "type %0 decomposes into %3 %plural{1:element|:elements}2, but " + "%select{%plural{0:no|:only %1}1|%1}4 " + "%plural{1:name was|:names were}1 provided">; + def err_decomp_decl_unbindable_type : Error< + "cannot decompose %select{union|non-class, non-array}1 type %2">; + def err_decomp_decl_multiple_bases_with_members : Error< + "cannot decompose class type %1: " + "%select{its base classes %2 and|both it and its base class}0 %3 " + "have non-static data members">; + def err_decomp_decl_ambiguous_base : Error< + "cannot decompose members of ambiguous base class %1 of %0:%2">; + def err_decomp_decl_inaccessible_base : Error< + "cannot decompose members of inaccessible base class %1 of %0">, + AccessControl; + def err_decomp_decl_inaccessible_field : Error< + "cannot decompose %select{private|protected}0 member %1 of %3">, + AccessControl; + def err_decomp_decl_lambda : Error< + "cannot decompose lambda closure type">; + def err_decomp_decl_anon_union_member : Error< + "cannot decompose class type %0 because it has an anonymous " + "%select{struct|union}1 member">; + def err_decomp_decl_std_tuple_element_not_specialized : Error< + "cannot decompose this type; 'std::tuple_element<%0>::type' " + "does not name a type">; + def err_decomp_decl_std_tuple_size_not_constant : Error< + "cannot decompose this type; 'std::tuple_size<%0>::value' " + "is not a valid integral constant expression">; + def note_in_binding_decl_init : Note< + "in implicit initialization of binding declaration %0">; + + def err_std_type_trait_not_class_template : Error< + "unsupported standard library implementation: " + "'std::%0' is not a class template">; + + // C++ using declarations + def err_using_requires_qualname : Error< + "using declaration requires a qualified name">; + def err_using_typename_non_type : Error< + "'typename' keyword used on a non-type">; + def err_using_dependent_value_is_type : Error< + "dependent using declaration resolved to type without 'typename'">; + def err_using_decl_nested_name_specifier_is_not_class : Error< + "using declaration in class refers into '%0', which is not a class">; + def warn_cxx17_compat_using_decl_non_member_enumerator : Warning< + "member using declaration naming non-class '%0' enumerator is " + "incompatible with C++ standards before C++20">, InGroup, + DefaultIgnore; + def err_using_decl_nested_name_specifier_is_current_class : Error< + "using declaration refers to its own class">; + def err_using_decl_nested_name_specifier_is_not_base_class : Error< + "using declaration refers into '%0', which is not a base class of %1">; + def err_using_decl_constructor_not_in_direct_base : Error< + "%0 is not a direct base of %1, cannot inherit constructors">; + def err_using_decl_can_not_refer_to_class_member : Error< + "using declaration cannot refer to class member">; + def warn_cxx17_compat_using_decl_class_member_enumerator : Warning< + "member using declaration naming a non-member enumerator is incompatible " + "with C++ standards before C++20">, InGroup, DefaultIgnore; + def ext_using_decl_class_member_enumerator : ExtWarn< + "member using declaration naming a non-member enumerator is " + "a C++20 extension">, InGroup; + def err_using_enum_is_dependent : Error< + "using-enum cannot name a dependent type">; + def err_ambiguous_inherited_constructor : Error< + "constructor of %0 inherited from multiple base class subobjects">; + def note_ambiguous_inherited_constructor_using : Note< + "inherited from base class %0 here">; + def note_using_decl_class_member_workaround : Note< + "use %select{an alias declaration|a typedef declaration|a reference|" + "a const variable|a constexpr variable}0 instead">; + def err_using_decl_can_not_refer_to_namespace : Error< + "using declaration cannot refer to a namespace">; + def warn_cxx17_compat_using_decl_scoped_enumerator: Warning< + "using declaration naming a scoped enumerator is incompatible with " + "C++ standards before C++20">, InGroup, DefaultIgnore; + def ext_using_decl_scoped_enumerator : ExtWarn< + "using declaration naming a scoped enumerator is a C++20 extension">, + InGroup; + def err_using_decl_constructor : Error< + "using declaration cannot refer to a constructor">; + def warn_cxx98_compat_using_decl_constructor : Warning< + "inheriting constructors are incompatible with C++98">, + InGroup, DefaultIgnore; + def err_using_decl_destructor : Error< + "using declaration cannot refer to a destructor">; + def err_using_decl_template_id : Error< + "using declaration cannot refer to a template specialization">; + def note_using_decl_target : Note<"target of using declaration">; + def note_using_decl_conflict : Note<"conflicting declaration">; + def err_using_decl_redeclaration : Error<"redeclaration of using declaration">; + def err_using_decl_conflict : Error< + "target of using declaration conflicts with declaration already in scope">; + def err_using_decl_conflict_reverse : Error< + "declaration conflicts with target of using declaration already in scope">; + def note_using_decl : Note<"%select{|previous }0using declaration">; + def err_using_decl_redeclaration_expansion : Error< + "using declaration pack expansion at block scope produces multiple values">; + def err_use_of_empty_using_if_exists : Error< + "reference to unresolved using declaration">; + def note_empty_using_if_exists_here : Note< + "using declaration annotated with 'using_if_exists' here">; + def err_using_if_exists_on_ctor : Error< + "'using_if_exists' attribute cannot be applied to an inheriting constructor">; + def err_using_enum_decl_redeclaration : Error< + "redeclaration of using-enum declaration">; + def note_using_enum_decl : Note<"%select{|previous }0using-enum declaration">; + + def warn_access_decl_deprecated : Warning< + "access declarations are deprecated; use using declarations instead">, + InGroup; + def err_access_decl : Error< + "ISO C++11 does not allow access declarations; " + "use using declarations instead">; + def warn_deprecated_copy : Warning< + "definition of implicit copy %select{constructor|assignment operator}1 " + "for %0 is deprecated because it has a user-declared copy " + "%select{assignment operator|constructor}1">, + InGroup, DefaultIgnore; + def warn_deprecated_copy_with_dtor : Warning< + "definition of implicit copy %select{constructor|assignment operator}1 " + "for %0 is deprecated because it has a user-declared destructor">, + InGroup, DefaultIgnore; + def warn_deprecated_copy_with_user_provided_copy: Warning< + "definition of implicit copy %select{constructor|assignment operator}1 " + "for %0 is deprecated because it has a user-provided copy " + "%select{assignment operator|constructor}1">, + InGroup, DefaultIgnore; + def warn_deprecated_copy_with_user_provided_dtor : Warning< + "definition of implicit copy %select{constructor|assignment operator}1 " + "for %0 is deprecated because it has a user-provided destructor">, + InGroup, DefaultIgnore; + def warn_cxx17_compat_exception_spec_in_signature : Warning< + "mangled name of %0 will change in C++17 due to non-throwing exception " + "specification in function signature">, InGroup; + + def warn_global_constructor : Warning< + "declaration requires a global constructor">, + InGroup, DefaultIgnore; + def warn_global_destructor : Warning< + "declaration requires a global destructor">, + InGroup, DefaultIgnore; + def warn_exit_time_destructor : Warning< + "declaration requires an exit-time destructor">, + InGroup, DefaultIgnore; + + def err_invalid_thread : Error< + "'%0' is only allowed on variable declarations">; + def err_thread_non_global : Error< + "'%0' variables must have global storage">; + def err_thread_unsupported : Error< + "thread-local storage is not supported for the current target">; + + // FIXME: Combine fallout warnings to just one warning. + def warn_maybe_falloff_nonvoid_function : Warning< + "non-void function does not return a value in all control paths">, + InGroup; + def warn_falloff_nonvoid_function : Warning< + "non-void function does not return a value">, + InGroup; + def err_maybe_falloff_nonvoid_block : Error< + "non-void block does not return a value in all control paths">; + def err_falloff_nonvoid_block : Error< + "non-void block does not return a value">; + def warn_maybe_falloff_nonvoid_coroutine : Warning< + "non-void coroutine does not return a value in all control paths">, + InGroup; + def warn_falloff_nonvoid_coroutine : Warning< + "non-void coroutine does not return a value">, + InGroup; + def warn_suggest_noreturn_function : Warning< + "%select{function|method}0 %1 could be declared with attribute 'noreturn'">, + InGroup, DefaultIgnore; + def warn_suggest_noreturn_block : Warning< + "block could be declared with attribute 'noreturn'">, + InGroup, DefaultIgnore; + + // Unreachable code. + def warn_unreachable : Warning< + "code will never be executed">, + InGroup, DefaultIgnore; + def warn_unreachable_break : Warning< + "'break' will never be executed">, + InGroup, DefaultIgnore; + def warn_unreachable_return : Warning< + "'return' will never be executed">, + InGroup, DefaultIgnore; + def warn_unreachable_loop_increment : Warning< + "loop will run at most once (loop increment never executed)">, + InGroup, DefaultIgnore; + def warn_unreachable_fallthrough_attr : Warning< + "fallthrough annotation in unreachable code">, + InGroup, DefaultIgnore; + def note_unreachable_silence : Note< + "silence by adding parentheses to mark code as explicitly dead">; + + /// Built-in functions. + def ext_implicit_lib_function_decl : ExtWarn< + "implicitly declaring library function '%0' with type %1">, + InGroup; + def note_include_header_or_declare : Note< + "include the header <%0> or explicitly provide a declaration for '%1'">; + def note_previous_builtin_declaration : Note<"%0 is a builtin with type %1">; + def warn_implicit_decl_no_jmp_buf + : Warning<"declaration of built-in function '%0' requires the declaration" + " of the 'jmp_buf' type, commonly provided in the header .">, + InGroup>; + def warn_implicit_decl_requires_sysheader : Warning< + "declaration of built-in function '%1' requires inclusion of the header <%0>">, + InGroup; + def warn_redecl_library_builtin : Warning< + "incompatible redeclaration of library function %0">, + InGroup>; + def err_builtin_definition : Error<"definition of builtin function %0">; + def err_builtin_redeclare : Error<"cannot redeclare builtin function %0">; + def err_arm_invalid_specialreg : Error<"invalid special register for builtin">; + def err_arm_invalid_coproc : Error<"coprocessor %0 must be configured as " + "%select{GCP|CDE}1">; + def err_invalid_cpu_supports : Error<"invalid cpu feature string for builtin">; + def err_invalid_cpu_is : Error<"invalid cpu name for builtin">; + def err_invalid_cpu_specific_dispatch_value : Error< + "invalid option '%0' for %select{cpu_specific|cpu_dispatch}1">; + def warn_builtin_unknown : Warning<"use of unknown builtin %0">, + InGroup, DefaultError; + def warn_cstruct_memaccess : Warning< + "%select{destination for|source of|first operand of|second operand of}0 this " + "%1 call is a pointer to record %2 that is not trivial to " + "%select{primitive-default-initialize|primitive-copy}3">, + InGroup; + def note_nontrivial_field : Note< + "field is non-trivial to %select{copy|default-initialize}0">; + def err_non_trivial_c_union_in_invalid_context : Error< + "cannot %select{" + "use type %1 for a function/method parameter|" + "use type %1 for function/method return|" + "default-initialize an object of type %1|" + "declare an automatic variable of type %1|" + "copy-initialize an object of type %1|" + "assign to a variable of type %1|" + "construct an automatic compound literal of type %1|" + "capture a variable of type %1|" + "cannot use volatile type %1 where it causes an lvalue-to-rvalue conversion" + "}3 " + "since it %select{contains|is}2 a union that is non-trivial to " + "%select{default-initialize|destruct|copy}0">; + def note_non_trivial_c_union : Note< + "%select{%2 has subobjects that are|%3 has type %2 that is}0 " + "non-trivial to %select{default-initialize|destruct|copy}1">; + def warn_dyn_class_memaccess : Warning< + "%select{destination for|source of|first operand of|second operand of}0 this " + "%1 call is a pointer to %select{|class containing a }2dynamic class %3; " + "vtable pointer will be %select{overwritten|copied|moved|compared}4">, + InGroup; + def note_bad_memaccess_silence : Note< + "explicitly cast the pointer to silence this warning">; + def warn_sizeof_pointer_expr_memaccess : Warning< + "'%0' call operates on objects of type %1 while the size is based on a " + "different type %2">, + InGroup; + def warn_sizeof_pointer_expr_memaccess_note : Note< + "did you mean to %select{dereference the argument to 'sizeof' (and multiply " + "it by the number of elements)|remove the addressof in the argument to " + "'sizeof' (and multiply it by the number of elements)|provide an explicit " + "length}0?">; + def warn_sizeof_pointer_type_memaccess : Warning< + "argument to 'sizeof' in %0 call is the same pointer type %1 as the " + "%select{destination|source}2; expected %3 or an explicit length">, + InGroup; + def warn_strlcpycat_wrong_size : Warning< + "size argument in %0 call appears to be size of the source; " + "expected the size of the destination">, + InGroup>; + def note_strlcpycat_wrong_size : Note< + "change size argument to be the size of the destination">; + def warn_memsize_comparison : Warning< + "size argument in %0 call is a comparison">, + InGroup>; + def note_memsize_comparison_paren : Note< + "did you mean to compare the result of %0 instead?">; + def note_memsize_comparison_cast_silence : Note< + "explicitly cast the argument to size_t to silence this warning">; + def warn_suspicious_sizeof_memset : Warning< + "%select{'size' argument to memset is '0'|" + "setting buffer to a 'sizeof' expression}0" + "; did you mean to transpose the last two arguments?">, + InGroup; + def note_suspicious_sizeof_memset_silence : Note< + "%select{parenthesize the third argument|" + "cast the second argument to 'int'}0 to silence">; + def warn_suspicious_bzero_size : Warning<"'size' argument to bzero is '0'">, + InGroup; + def note_suspicious_bzero_size_silence : Note< + "parenthesize the second argument to silence">; + + def warn_strncat_large_size : Warning< + "the value of the size argument in 'strncat' is too large, might lead to a " + "buffer overflow">, InGroup; + def warn_strncat_src_size : Warning<"size argument in 'strncat' call appears " + "to be size of the source">, InGroup; + def warn_strncat_wrong_size : Warning< + "the value of the size argument to 'strncat' is wrong">, InGroup; + def note_strncat_wrong_size : Note< + "change the argument to be the free space in the destination buffer minus " + "the terminating null byte">; + + def warn_assume_side_effects : Warning< + "the argument to %0 has side effects that will be discarded">, + InGroup>; + def warn_assume_attribute_string_unknown : Warning< + "unknown assumption string '%0'; attribute is potentially ignored">, + InGroup; + def warn_assume_attribute_string_unknown_suggested : Warning< + "unknown assumption string '%0' may be misspelled; attribute is potentially " + "ignored, did you mean '%1'?">, + InGroup; + + def warn_builtin_chk_overflow : Warning< + "'%0' will always overflow; destination buffer has size %1," + " but size argument is %2">, + InGroup>; + + def warn_fortify_source_overflow + : Warning, InGroup; + def warn_fortify_source_size_mismatch : Warning< + "'%0' size argument is too large; destination buffer has size %1," + " but size argument is %2">, InGroup; + + def warn_fortify_strlen_overflow: Warning< + "'%0' will always overflow; destination buffer has size %1," + " but the source string has length %2 (including NUL byte)">, + InGroup; + + def warn_fortify_source_format_overflow : Warning< + "'%0' will always overflow; destination buffer has size %1," + " but format string expands to at least %2">, + InGroup; + + + /// main() + // static main() is not an error in C, just in C++. + def warn_static_main : Warning<"'main' should not be declared static">, + InGroup
; + def err_static_main : Error<"'main' is not allowed to be declared static">; + def err_inline_main : Error<"'main' is not allowed to be declared inline">; + def ext_variadic_main : ExtWarn< + "'main' is not allowed to be declared variadic">, InGroup
; + def ext_noreturn_main : ExtWarn< + "'main' is not allowed to be declared _Noreturn">, InGroup
; + def note_main_remove_noreturn : Note<"remove '_Noreturn'">; + def err_constexpr_main : Error< + "'main' is not allowed to be declared %select{constexpr|consteval}0">; + def err_deleted_main : Error<"'main' is not allowed to be deleted">; + def err_mainlike_template_decl : Error<"%0 cannot be a template">; + def err_main_returns_nonint : Error<"'main' must return 'int'">; + def ext_main_returns_nonint : ExtWarn<"return type of 'main' is not 'int'">, + InGroup; + def note_main_change_return_type : Note<"change return type to 'int'">; + def err_main_surplus_args : Error<"too many parameters (%0) for 'main': " + "must be 0, 2, or 3">; + def warn_main_one_arg : Warning<"only one parameter on 'main' declaration">, + InGroup
; + def err_main_arg_wrong : Error<"%select{first|second|third|fourth}0 " + "parameter of 'main' (%select{argument count|argument array|environment|" + "platform-specific data}0) must be of type %1">; + def warn_main_returns_bool_literal : Warning<"bool literal returned from " + "'main'">, InGroup
; + def err_main_global_variable : + Error<"main cannot be declared as global variable">; + def warn_main_redefined : Warning<"variable named 'main' with external linkage " + "has undefined behavior">, InGroup
; + def ext_main_used : Extension< + "ISO C++ does not allow 'main' to be used by a program">, InGroup
; + + /// parser diagnostics + def ext_no_declarators : ExtWarn<"declaration does not declare anything">, + InGroup; + def err_no_declarators : Error<"declaration does not declare anything">; + def ext_typedef_without_a_name : ExtWarn<"typedef requires a name">, + InGroup; + def err_typedef_not_identifier : Error<"typedef name must be an identifier">; + + def ext_non_c_like_anon_struct_in_typedef : ExtWarn< + "anonymous non-C-compatible type given name for linkage purposes " + "by %select{typedef|alias}0 declaration; " + "add a tag name here">, InGroup>; + def err_non_c_like_anon_struct_in_typedef : Error< + "anonymous non-C-compatible type given name for linkage purposes " + "by %select{typedef|alias}0 declaration after its linkage was computed; " + "add a tag name here to establish linkage prior to definition">; + def err_typedef_changes_linkage : Error< + "unsupported: anonymous type given name for linkage purposes " + "by %select{typedef|alias}0 declaration after its linkage was computed; " + "add a tag name here to establish linkage prior to definition">; + def note_non_c_like_anon_struct : Note< + "type is not C-compatible due to this " + "%select{base class|default member initializer|lambda expression|" + "friend declaration|member declaration}0">; + def note_typedef_for_linkage_here : Note< + "type is given name %0 for linkage purposes by this " + "%select{typedef|alias}1 declaration">; + + def err_statically_allocated_object : Error< + "interface type cannot be statically allocated">; + def err_object_cannot_be_passed_returned_by_value : Error< + "interface type %1 cannot be %select{returned|passed}0 by value" + "; did you forget * in %1?">; + def err_parameters_retval_cannot_have_fp16_type : Error< + "%select{parameters|function return value}0 cannot have __fp16 type; did you forget * ?">; + def err_opencl_half_load_store : Error< + "%select{loading directly from|assigning directly to}0 pointer to type %1 requires " + "cl_khr_fp16. Use vector data %select{load|store}0 builtin functions instead">; + def err_opencl_cast_to_half : Error<"casting to type %0 is not allowed">; + def err_opencl_half_declaration : Error< + "declaring variable of type %0 is not allowed">; + def err_opencl_invalid_param : Error< + "declaring function parameter of type %0 is not allowed%select{; did you forget * ?|}1">; + def err_opencl_invalid_return : Error< + "declaring function return value of type %0 is not allowed %select{; did you forget * ?|}1">; + def warn_enum_value_overflow : Warning<"overflow in enumeration value">; + def warn_pragma_options_align_reset_failed : Warning< + "#pragma options align=reset failed: %0">, + InGroup; + def err_pragma_options_align_mac68k_target_unsupported : Error< + "mac68k alignment pragma is not supported on this target">; + def warn_pragma_pack_invalid_alignment : Warning< + "expected #pragma pack parameter to be '1', '2', '4', '8', or '16'">, + InGroup; + def err_pragma_pack_invalid_alignment : Error< + warn_pragma_pack_invalid_alignment.Text>; + def warn_pragma_pack_non_default_at_include : Warning< + "non-default #pragma pack value changes the alignment of struct or union " + "members in the included file">, InGroup, + DefaultIgnore; + def warn_pragma_pack_modified_after_include : Warning< + "the current #pragma pack alignment value is modified in the included " + "file">, InGroup; + def warn_pragma_pack_no_pop_eof : Warning<"unterminated " + "'#pragma pack (push, ...)' at end of file">, InGroup; + def note_pragma_pack_here : Note< + "previous '#pragma pack' directive that modifies alignment is here">; + def note_pragma_pack_pop_instead_reset : Note< + "did you intend to use '#pragma pack (pop)' instead of '#pragma pack()'?">; + // Follow the Microsoft implementation. + def warn_pragma_pack_show : Warning<"value of #pragma pack(show) == %0">; + def warn_pragma_pack_pop_identifier_and_alignment : Warning< + "specifying both a name and alignment to 'pop' is undefined">; + def warn_pragma_pop_failed : Warning<"#pragma %0(pop, ...) failed: %1">, + InGroup; + def err_pragma_fc_pp_scope : Error< + "'#pragma float_control push/pop' can only appear at file or namespace scope " + "or within a language linkage specification">; + def err_pragma_fc_noprecise_requires_nofenv : Error< + "'#pragma float_control(precise, off)' is illegal when fenv_access is enabled">; + def err_pragma_fc_except_requires_precise : Error< + "'#pragma float_control(except, on)' is illegal when precise is disabled">; + def err_pragma_fc_noprecise_requires_noexcept : Error< + "'#pragma float_control(precise, off)' is illegal when except is enabled">; + def err_pragma_fenv_requires_precise : Error< + "'#pragma STDC FENV_ACCESS ON' is illegal when precise is disabled">; + def warn_cxx_ms_struct : + Warning<"ms_struct may not produce Microsoft-compatible layouts for classes " + "with base classes or virtual functions">, + DefaultError, InGroup; + def err_pragma_pack_identifer_not_supported : Error< + "specifying an identifier within `#pragma pack` is not supported on this target">; + def err_section_conflict : Error<"%0 causes a section type conflict with %1">; + def err_no_base_classes : Error<"invalid use of '__super', %0 has no base classes">; + def err_invalid_super_scope : Error<"invalid use of '__super', " + "this keyword can only be used inside class or member function scope">; + def err_super_in_lambda_unsupported : Error< + "use of '__super' inside a lambda is unsupported">; + + def warn_pragma_unused_undeclared_var : Warning< + "undeclared variable %0 used as an argument for '#pragma unused'">, + InGroup; + def warn_atl_uuid_deprecated : Warning< + "specifying 'uuid' as an ATL attribute is deprecated; use __declspec instead">, + InGroup; + def warn_pragma_unused_expected_var_arg : Warning< + "only variables can be arguments to '#pragma unused'">, + InGroup; + def err_pragma_push_visibility_mismatch : Error< + "#pragma visibility push with no matching #pragma visibility pop">; + def note_surrounding_namespace_ends_here : Note< + "surrounding namespace with visibility attribute ends here">; + def err_pragma_pop_visibility_mismatch : Error< + "#pragma visibility pop with no matching #pragma visibility push">; + def note_surrounding_namespace_starts_here : Note< + "surrounding namespace with visibility attribute starts here">; + def err_pragma_loop_invalid_argument_type : Error< + "invalid argument of type %0; expected an integer type">; + def err_pragma_loop_invalid_argument_value : Error< + "%select{invalid value '%0'; must be positive|value '%0' is too large}1">; + def err_pragma_loop_compatibility : Error< + "%select{incompatible|duplicate}0 directives '%1' and '%2'">; + def err_pragma_loop_precedes_nonloop : Error< + "expected a for, while, or do-while loop to follow '%0'">; + + def err_pragma_attribute_matcher_subrule_contradicts_rule : Error< + "redundant attribute subject matcher sub-rule '%0'; '%1' already matches " + "those declarations">; + def err_pragma_attribute_matcher_negated_subrule_contradicts_subrule : Error< + "negated attribute subject matcher sub-rule '%0' contradicts sub-rule '%1'">; + def err_pragma_attribute_invalid_matchers : Error< + "attribute %0 can't be applied to %1">; + def err_pragma_attribute_stack_mismatch : Error< + "'#pragma clang attribute %select{%1.|}0pop' with no matching" + " '#pragma clang attribute %select{%1.|}0push'">; + def warn_pragma_attribute_unused : Warning< + "unused attribute %0 in '#pragma clang attribute push' region">, + InGroup; + def note_pragma_attribute_region_ends_here : Note< + "'#pragma clang attribute push' regions ends here">; + def err_pragma_attribute_no_pop_eof : Error<"unterminated " + "'#pragma clang attribute push' at end of file">; + def note_pragma_attribute_applied_decl_here : Note< + "when applied to this declaration">; + def err_pragma_attr_attr_no_push : Error< + "'#pragma clang attribute' attribute with no matching " + "'#pragma clang attribute push'">; + + /// Objective-C parser diagnostics + def err_duplicate_class_def : Error< + "duplicate interface definition for class %0">; + def err_undef_superclass : Error< + "cannot find interface declaration for %0, superclass of %1">; + def err_forward_superclass : Error< + "attempting to use the forward class %0 as superclass of %1">; + def err_no_nsconstant_string_class : Error< + "cannot find interface declaration for %0">; + def err_recursive_superclass : Error< + "trying to recursively use %0 as superclass of %1">; + def err_conflicting_aliasing_type : Error<"conflicting types for alias %0">; + def warn_undef_interface : Warning<"cannot find interface declaration for %0">; + def warn_duplicate_protocol_def : Warning< + "duplicate protocol definition of %0 is ignored">, + InGroup>; + def err_protocol_has_circular_dependency : Error< + "protocol has circular dependency">; + def err_undeclared_protocol : Error<"cannot find protocol declaration for %0">; + def warn_undef_protocolref : Warning<"cannot find protocol definition for %0">; + def err_atprotocol_protocol : Error< + "@protocol is using a forward protocol declaration of %0">; + def warn_readonly_property : Warning< + "attribute 'readonly' of property %0 restricts attribute " + "'readwrite' of property inherited from %1">, + InGroup; + + def warn_property_attribute : Warning< + "'%1' attribute on property %0 does not match the property inherited from %2">, + InGroup; + def warn_property_types_are_incompatible : Warning< + "property type %0 is incompatible with type %1 inherited from %2">, + InGroup>; + def warn_protocol_property_mismatch : Warning< + "property %select{of type %1|with attribute '%1'|without attribute '%1'|with " + "getter %1|with setter %1}0 was selected for synthesis">, + InGroup>; + def err_protocol_property_mismatch: Error; + def err_undef_interface : Error<"cannot find interface declaration for %0">; + def err_category_forward_interface : Error< + "cannot define %select{category|class extension}0 for undefined class %1">; + def err_class_extension_after_impl : Error< + "cannot declare class extension for %0 after class implementation">; + def note_implementation_declared : Note< + "class implementation is declared here">; + def note_while_in_implementation : Note< + "detected while default synthesizing properties in class implementation">; + def note_class_declared : Note< + "class is declared here">; + def note_receiver_class_declared : Note< + "receiver is instance of class declared here">; + def note_receiver_expr_here : Note< + "receiver expression is here">; + def note_receiver_is_id : Note< + "receiver is treated with 'id' type for purpose of method lookup">; + def note_suppressed_class_declare : Note< + "class with specified objc_requires_property_definitions attribute is declared here">; + def err_objc_root_class_subclass : Error< + "objc_root_class attribute may only be specified on a root class declaration">; + def err_restricted_superclass_mismatch : Error< + "cannot subclass a class that was declared with the " + "'objc_subclassing_restricted' attribute">; + def err_class_stub_subclassing_mismatch : Error< + "'objc_class_stub' attribute cannot be specified on a class that does not " + "have the 'objc_subclassing_restricted' attribute">; + def err_implementation_of_class_stub : Error< + "cannot declare implementation of a class declared with the " + "'objc_class_stub' attribute">; + def warn_objc_root_class_missing : Warning< + "class %0 defined without specifying a base class">, + InGroup; + def err_objc_runtime_visible_category : Error< + "cannot implement a category for class %0 that is only visible via the " + "Objective-C runtime">; + def err_objc_runtime_visible_subclass : Error< + "cannot implement subclass %0 of a superclass %1 that is only visible via the " + "Objective-C runtime">; + def note_objc_needs_superclass : Note< + "add a super class to fix this problem">; + def err_conflicting_super_class : Error<"conflicting super class name %0">; + def err_dup_implementation_class : Error<"reimplementation of class %0">; + def err_dup_implementation_category : Error< + "reimplementation of category %1 for class %0">; + def err_conflicting_ivar_type : Error< + "instance variable %0 has conflicting type%diff{: $ vs $|}1,2">; + def err_duplicate_ivar_declaration : Error< + "instance variable is already declared">; + def warn_on_superclass_use : Warning< + "class implementation may not have super class">; + def err_conflicting_ivar_bitwidth : Error< + "instance variable %0 has conflicting bit-field width">; + def err_conflicting_ivar_name : Error< + "conflicting instance variable names: %0 vs %1">; + def err_inconsistent_ivar_count : Error< + "inconsistent number of instance variables specified">; + def warn_undef_method_impl : Warning<"method definition for %0 not found">, + InGroup>; + def warn_objc_boxing_invalid_utf8_string : Warning< + "string is ill-formed as UTF-8 and will become a null %0 when boxed">, + InGroup; + + def err_objc_non_runtime_protocol_in_protocol_expr : Error< + "cannot use a protocol declared 'objc_non_runtime_protocol' in a @protocol expression">; + def err_objc_direct_on_protocol : Error< + "'objc_direct' attribute cannot be applied to %select{methods|properties}0 " + "declared in an Objective-C protocol">; + def err_objc_direct_duplicate_decl : Error< + "%select{|direct }0%select{method|property}1 declaration conflicts " + "with previous %select{|direct }2declaration of %select{method|property}1 %3">; + def err_objc_direct_impl_decl_mismatch : Error< + "direct method was declared in %select{the primary interface|an extension|a category}0 " + "but is implemented in %select{the primary interface|a category|a different category}1">; + def err_objc_direct_missing_on_decl : Error< + "direct method implementation was previously declared not direct">; + def err_objc_direct_on_override : Error< + "methods that %select{override superclass methods|implement protocol requirements}0 cannot be direct">; + def err_objc_override_direct_method : Error< + "cannot override a method that is declared direct by a superclass">; + def warn_objc_direct_ignored : Warning< + "%0 attribute isn't implemented by this Objective-C runtime">, + InGroup; + def warn_objc_direct_property_ignored : Warning< + "direct attribute on property %0 ignored (not implemented by this Objective-C runtime)">, + InGroup; + def err_objc_direct_dynamic_property : Error< + "direct property cannot be @dynamic">; + def err_objc_direct_protocol_conformance : Error< + "%select{category %1|class extension}0 cannot conform to protocol %2 because " + "of direct members declared in interface %3">; + def note_direct_member_here : Note<"direct member declared here">; + + def warn_conflicting_overriding_ret_types : Warning< + "conflicting return type in " + "declaration of %0%diff{: $ vs $|}1,2">, + InGroup, DefaultIgnore; + + def warn_conflicting_ret_types : Warning< + "conflicting return type in " + "implementation of %0%diff{: $ vs $|}1,2">, + InGroup; + + def warn_conflicting_overriding_ret_type_modifiers : Warning< + "conflicting distributed object modifiers on return type " + "in declaration of %0">, + InGroup, DefaultIgnore; + + def warn_conflicting_ret_type_modifiers : Warning< + "conflicting distributed object modifiers on return type " + "in implementation of %0">, + InGroup; + + def warn_non_covariant_overriding_ret_types : Warning< + "conflicting return type in " + "declaration of %0: %1 vs %2">, + InGroup, DefaultIgnore; + + def warn_non_covariant_ret_types : Warning< + "conflicting return type in " + "implementation of %0: %1 vs %2">, + InGroup, DefaultIgnore; + + def warn_conflicting_overriding_param_types : Warning< + "conflicting parameter types in " + "declaration of %0%diff{: $ vs $|}1,2">, + InGroup, DefaultIgnore; + + def warn_conflicting_param_types : Warning< + "conflicting parameter types in " + "implementation of %0%diff{: $ vs $|}1,2">, + InGroup; + + def warn_conflicting_param_modifiers : Warning< + "conflicting distributed object modifiers on parameter type " + "in implementation of %0">, + InGroup; + + def warn_conflicting_overriding_param_modifiers : Warning< + "conflicting distributed object modifiers on parameter type " + "in declaration of %0">, + InGroup, DefaultIgnore; + + def warn_non_contravariant_overriding_param_types : Warning< + "conflicting parameter types in " + "declaration of %0: %1 vs %2">, + InGroup, DefaultIgnore; + + def warn_non_contravariant_param_types : Warning< + "conflicting parameter types in " + "implementation of %0: %1 vs %2">, + InGroup, DefaultIgnore; + + def warn_conflicting_overriding_variadic :Warning< + "conflicting variadic declaration of method and its " + "implementation">, + InGroup, DefaultIgnore; + + def warn_conflicting_variadic :Warning< + "conflicting variadic declaration of method and its " + "implementation">; + + def warn_category_method_impl_match:Warning< + "category is implementing a method which will also be implemented" + " by its primary class">, InGroup; + + def warn_implements_nscopying : Warning< + "default assign attribute on property %0 which implements " + "NSCopying protocol is not appropriate with -fobjc-gc[-only]">; + + def warn_multiple_method_decl : Warning<"multiple methods named %0 found">, + InGroup; + def warn_strict_multiple_method_decl : Warning< + "multiple methods named %0 found">, InGroup, DefaultIgnore; + def warn_accessor_property_type_mismatch : Warning< + "type of property %0 does not match type of accessor %1">; + def note_conv_function_declared_at : Note<"type conversion function declared here">; + def note_method_declared_at : Note<"method %0 declared here">; + def note_direct_method_declared_at : Note<"direct method %0 declared here">; + def note_property_attribute : Note<"property %0 is declared " + "%select{deprecated|unavailable|partial}1 here">; + def err_setter_type_void : Error<"type of setter must be void">; + def err_duplicate_method_decl : Error<"duplicate declaration of method %0">; + def warn_duplicate_method_decl : + Warning<"multiple declarations of method %0 found and ignored">, + InGroup, DefaultIgnore; + def warn_objc_cdirective_format_string : + Warning<"using %0 directive in %select{NSString|CFString}1 " + "which is being passed as a formatting argument to the formatting " + "%select{method|CFfunction}2">, + InGroup, DefaultIgnore; + def err_objc_var_decl_inclass : + Error<"cannot declare variable inside @interface or @protocol">; + def err_missing_method_context : Error< + "missing context for method declaration">; + def err_objc_property_attr_mutually_exclusive : Error< + "property attributes '%0' and '%1' are mutually exclusive">; + def err_objc_property_requires_object : Error< + "property with '%0' attribute must be of object type">; + def warn_objc_property_assign_on_object : Warning< + "'assign' property of object type may become a dangling reference; consider using 'unsafe_unretained'">, + InGroup, DefaultIgnore; + def warn_objc_property_no_assignment_attribute : Warning< + "no 'assign', 'retain', or 'copy' attribute is specified - " + "'assign' is assumed">, + InGroup; + def warn_objc_isa_use : Warning< + "direct access to Objective-C's isa is deprecated in favor of " + "object_getClass()">, InGroup; + def warn_objc_isa_assign : Warning< + "assignment to Objective-C's isa is deprecated in favor of " + "object_setClass()">, InGroup; + def warn_objc_pointer_masking : Warning< + "bitmasking for introspection of Objective-C object pointers is strongly " + "discouraged">, + InGroup; + def warn_objc_pointer_masking_performSelector : Warning, + InGroup; + def warn_objc_property_default_assign_on_object : Warning< + "default property attribute 'assign' not appropriate for object">, + InGroup; + def warn_property_attr_mismatch : Warning< + "property attribute in class extension does not match the primary class">, + InGroup; + def warn_property_implicitly_mismatched : Warning < + "primary property declaration is implicitly strong while redeclaration " + "in class extension is weak">, + InGroup>; + def warn_objc_property_copy_missing_on_block : Warning< + "'copy' attribute must be specified for the block property " + "when -fobjc-gc-only is specified">; + def warn_objc_property_retain_of_block : Warning< + "retain'ed block property does not copy the block " + "- use copy attribute instead">, InGroup; + def warn_objc_readonly_property_has_setter : Warning< + "setter cannot be specified for a readonly property">, + InGroup; + def warn_atomic_property_rule : Warning< + "writable atomic property %0 cannot pair a synthesized %select{getter|setter}1 " + "with a user defined %select{getter|setter}2">, + InGroup>; + def note_atomic_property_fixup_suggest : Note<"setter and getter must both be " + "synthesized, or both be user defined,or the property must be nonatomic">; + def err_atomic_property_nontrivial_assign_op : Error< + "atomic property of reference type %0 cannot have non-trivial assignment" + " operator">; + def warn_cocoa_naming_owned_rule : Warning< + "property follows Cocoa naming" + " convention for returning 'owned' objects">, + InGroup>; + def err_cocoa_naming_owned_rule : Error< + "property follows Cocoa naming" + " convention for returning 'owned' objects">; + def note_cocoa_naming_declare_family : Note< + "explicitly declare getter %objcinstance0 with '%1' to return an 'unowned' " + "object">; + def warn_auto_synthesizing_protocol_property :Warning< + "auto property synthesis will not synthesize property %0" + " declared in protocol %1">, + InGroup>; + def note_add_synthesize_directive : Note< + "add a '@synthesize' directive">; + def warn_no_autosynthesis_shared_ivar_property : Warning < + "auto property synthesis will not synthesize property " + "%0 because it cannot share an ivar with another synthesized property">, + InGroup; + def warn_no_autosynthesis_property : Warning< + "auto property synthesis will not synthesize property " + "%0 because it is 'readwrite' but it will be synthesized 'readonly' " + "via another property">, + InGroup; + def warn_autosynthesis_property_in_superclass : Warning< + "auto property synthesis will not synthesize property " + "%0; it will be implemented by its superclass, use @dynamic to " + "acknowledge intention">, + InGroup; + def warn_autosynthesis_property_ivar_match :Warning< + "autosynthesized property %0 will use %select{|synthesized}1 instance variable " + "%2, not existing instance variable %3">, + InGroup>; + def warn_missing_explicit_synthesis : Warning < + "auto property synthesis is synthesizing property not explicitly synthesized">, + InGroup>, DefaultIgnore; + def warn_property_getter_owning_mismatch : Warning< + "property declared as returning non-retained objects" + "; getter returning retained objects">; + def warn_property_redecl_getter_mismatch : Warning< + "getter name mismatch between property redeclaration (%1) and its original " + "declaration (%0)">, InGroup; + def err_property_setter_ambiguous_use : Error< + "synthesized properties %0 and %1 both claim setter %2 -" + " use of this setter will cause unexpected behavior">; + def warn_default_atomic_custom_getter_setter : Warning< + "atomic by default property %0 has a user defined %select{getter|setter}1 " + "(property should be marked 'atomic' if this is intended)">, + InGroup, DefaultIgnore; + def err_use_continuation_class : Error< + "illegal redeclaration of property in class extension %0" + " (attribute must be 'readwrite', while its primary must be 'readonly')">; + def err_type_mismatch_continuation_class : Error< + "type of property %0 in class extension does not match " + "property type in primary class">; + def err_use_continuation_class_redeclaration_readwrite : Error< + "illegal redeclaration of 'readwrite' property in class extension %0" + " (perhaps you intended this to be a 'readwrite' redeclaration of a " + "'readonly' public property?)">; + def err_continuation_class : Error<"class extension has no primary class">; + def err_property_type : Error<"property cannot have array or function type %0">; + def err_missing_property_context : Error< + "missing context for property implementation declaration">; + def err_bad_property_decl : Error< + "property implementation must have its declaration in interface %0 or one of " + "its extensions">; + def err_category_property : Error< + "property declared in category %0 cannot be implemented in " + "class implementation">; + def note_property_declare : Note< + "property declared here">; + def note_protocol_property_declare : Note< + "it could also be property " + "%select{of type %1|without attribute '%1'|with attribute '%1'|with getter " + "%1|with setter %1}0 declared here">; + def note_property_synthesize : Note< + "property synthesized here">; + def err_synthesize_category_decl : Error< + "@synthesize not allowed in a category's implementation">; + def err_synthesize_on_class_property : Error< + "@synthesize not allowed on a class property %0">; + def err_missing_property_interface : Error< + "property implementation in a category with no category declaration">; + def err_bad_category_property_decl : Error< + "property implementation must have its declaration in the category %0">; + def err_bad_property_context : Error< + "property implementation must be in a class or category implementation">; + def err_missing_property_ivar_decl : Error< + "synthesized property %0 must either be named the same as a compatible" + " instance variable or must explicitly name an instance variable">; + def err_arc_perform_selector_retains : Error< + "performSelector names a selector which retains the object">; + def warn_arc_perform_selector_leaks : Warning< + "performSelector may cause a leak because its selector is unknown">, + InGroup>; + def warn_dealloc_in_category : Warning< + "-dealloc is being overridden in a category">, + InGroup; + def err_gc_weak_property_strong_type : Error< + "weak attribute declared on a __strong type property in GC mode">; + def warn_arc_repeated_use_of_weak : Warning < + "weak %select{variable|property|implicit property|instance variable}0 %1 is " + "accessed multiple times in this %select{function|method|block|lambda}2 " + "but may be unpredictably set to nil; assign to a strong variable to keep " + "the object alive">, + InGroup, DefaultIgnore; + def warn_implicitly_retains_self : Warning < + "block implicitly retains 'self'; explicitly mention 'self' to indicate " + "this is intended behavior">, + InGroup>, DefaultIgnore; + def warn_arc_possible_repeated_use_of_weak : Warning < + "weak %select{variable|property|implicit property|instance variable}0 %1 may " + "be accessed multiple times in this %select{function|method|block|lambda}2 " + "and may be unpredictably set to nil; assign to a strong variable to keep " + "the object alive">, + InGroup, DefaultIgnore; + def note_arc_weak_also_accessed_here : Note< + "also accessed here">; + def err_incomplete_synthesized_property : Error< + "cannot synthesize property %0 with incomplete type %1">; + + def err_property_ivar_type : Error< + "type of property %0 (%1) does not match type of instance variable %2 (%3)">; + def err_property_accessor_type : Error< + "type of property %0 (%1) does not match type of accessor %2 (%3)">; + def err_ivar_in_superclass_use : Error< + "property %0 attempting to use instance variable %1 declared in super class %2">; + def err_weak_property : Error< + "existing instance variable %1 for __weak property %0 must be __weak">; + def err_strong_property : Error< + "existing instance variable %1 for strong property %0 may not be __weak">; + def err_dynamic_property_ivar_decl : Error< + "dynamic property cannot have instance variable specification">; + def err_duplicate_ivar_use : Error< + "synthesized properties %0 and %1 both claim instance variable %2">; + def err_property_implemented : Error<"property %0 is already implemented">; + def warn_objc_missing_super_call : Warning< + "method possibly missing a [super %0] call">, + InGroup; + def err_dealloc_bad_result_type : Error< + "dealloc return type must be correctly specified as 'void' under ARC, " + "instead of %0">; + def warn_undeclared_selector : Warning< + "undeclared selector %0">, InGroup, DefaultIgnore; + def warn_undeclared_selector_with_typo : Warning< + "undeclared selector %0; did you mean %1?">, + InGroup, DefaultIgnore; + def warn_implicit_atomic_property : Warning< + "property is assumed atomic by default">, InGroup, DefaultIgnore; + def note_auto_readonly_iboutlet_fixup_suggest : Note< + "property should be changed to be readwrite">; + def warn_auto_readonly_iboutlet_property : Warning< + "readonly IBOutlet property %0 when auto-synthesized may " + "not work correctly with 'nib' loader">, + InGroup>; + def warn_auto_implicit_atomic_property : Warning< + "property is assumed atomic when auto-synthesizing the property">, + InGroup, DefaultIgnore; + def warn_unimplemented_selector: Warning< + "no method with selector %0 is implemented in this translation unit">, + InGroup, DefaultIgnore; + def warn_unimplemented_protocol_method : Warning< + "method %0 in protocol %1 not implemented">, InGroup; + def warn_multiple_selectors: Warning< + "several methods with selector %0 of mismatched types are found " + "for the @selector expression">, + InGroup, DefaultIgnore; + def err_direct_selector_expression : Error< + "@selector expression formed with direct selector %0">; + def warn_potentially_direct_selector_expression : Warning< + "@selector expression formed with potentially direct selector %0">, + InGroup; + def warn_strict_potentially_direct_selector_expression : Warning< + warn_potentially_direct_selector_expression.Text>, + InGroup, DefaultIgnore; + + def err_objc_kindof_nonobject : Error< + "'__kindof' specifier cannot be applied to non-object type %0">; + def err_objc_kindof_wrong_position : Error< + "'__kindof' type specifier must precede the declarator">; + + def err_objc_method_unsupported_param_ret_type : Error< + "%0 %select{parameter|return}1 type is unsupported; " + "support for vector types for this target is introduced in %2">; + + def warn_messaging_unqualified_id : Warning< + "messaging unqualified id">, DefaultIgnore, + InGroup>; + def err_messaging_unqualified_id_with_direct_method : Error< + "messaging unqualified id with a method that is possibly direct">; + def err_messaging_super_with_direct_method : Error< + "messaging super with a direct method">; + def err_messaging_class_with_direct_method : Error< + "messaging a Class with a method that is possibly direct">; + + // C++ declarations + def err_static_assert_expression_is_not_constant : Error< + "static_assert expression is not an integral constant expression">; + def err_constexpr_if_condition_expression_is_not_constant : Error< + "constexpr if condition is not a constant expression">; + def err_static_assert_failed : Error<"static_assert failed%select{ %1|}0">; + def err_static_assert_requirement_failed : Error< + "static_assert failed due to requirement '%0'%select{ %2|}1">; + + def ext_inline_variable : ExtWarn< + "inline variables are a C++17 extension">, InGroup; + def warn_cxx14_compat_inline_variable : Warning< + "inline variables are incompatible with C++ standards before C++17">, + DefaultIgnore, InGroup; + + def warn_inline_namespace_reopened_noninline : Warning< + "inline namespace reopened as a non-inline namespace">, + InGroup; + def err_inline_namespace_mismatch : Error< + "non-inline namespace cannot be reopened as inline">; + + def err_unexpected_friend : Error< + "friends can only be classes or functions">; + def ext_enum_friend : ExtWarn< + "befriending enumeration type %0 is a C++11 extension">, InGroup; + def warn_cxx98_compat_enum_friend : Warning< + "befriending enumeration type %0 is incompatible with C++98">, + InGroup, DefaultIgnore; + def ext_nonclass_type_friend : ExtWarn< + "non-class friend type %0 is a C++11 extension">, InGroup; + def warn_cxx98_compat_nonclass_type_friend : Warning< + "non-class friend type %0 is incompatible with C++98">, + InGroup, DefaultIgnore; + def err_friend_is_member : Error< + "friends cannot be members of the declaring class">; + def warn_cxx98_compat_friend_is_member : Warning< + "friend declaration naming a member of the declaring class is incompatible " + "with C++98">, InGroup, DefaultIgnore; + def ext_unelaborated_friend_type : ExtWarn< + "unelaborated friend declaration is a C++11 extension; specify " + "'%select{struct|interface|union|class|enum}0' to befriend %1">, + InGroup; + def warn_cxx98_compat_unelaborated_friend_type : Warning< + "befriending %1 without '%select{struct|interface|union|class|enum}0' " + "keyword is incompatible with C++98">, InGroup, DefaultIgnore; + def err_qualified_friend_no_match : Error< + "friend declaration of %0 does not match any declaration in %1">; + def err_introducing_special_friend : Error< + "%plural{[0,2]:must use a qualified name when declaring|3:cannot declare}0" + " a %select{constructor|destructor|conversion operator|deduction guide}0 " + "as a friend">; + def err_tagless_friend_type_template : Error< + "friend type templates must use an elaborated type">; + def err_no_matching_local_friend : Error< + "no matching function found in local scope">; + def err_no_matching_local_friend_suggest : Error< + "no matching function %0 found in local scope; did you mean %3?">; + def err_partial_specialization_friend : Error< + "partial specialization cannot be declared as a friend">; + def err_qualified_friend_def : Error< + "friend function definition cannot be qualified with '%0'">; + def err_friend_def_in_local_class : Error< + "friend function cannot be defined in a local class">; + def err_friend_not_first_in_declaration : Error< + "'friend' must appear first in a non-function declaration">; + def err_using_decl_friend : Error< + "cannot befriend target of using declaration">; + def warn_template_qualified_friend_unsupported : Warning< + "dependent nested name specifier '%0' for friend class declaration is " + "not supported; turning off access control for %1">, + InGroup; + def warn_template_qualified_friend_ignored : Warning< + "dependent nested name specifier '%0' for friend template declaration is " + "not supported; ignoring this friend declaration">, + InGroup; + def ext_friend_tag_redecl_outside_namespace : ExtWarn< + "unqualified friend declaration referring to type outside of the nearest " + "enclosing namespace is a Microsoft extension; add a nested name specifier">, + InGroup; + def err_pure_friend : Error<"friend declaration cannot have a pure-specifier">; + + def err_invalid_base_in_interface : Error< + "interface type cannot inherit from " + "%select{struct|non-public interface|class}0 %1">; + + def err_abstract_type_in_decl : Error< + "%select{return|parameter|variable|field|instance variable|" + "synthesized instance variable}0 type %1 is an abstract class">; + def err_allocation_of_abstract_type : Error< + "allocating an object of abstract class type %0">; + def err_throw_abstract_type : Error< + "cannot throw an object of abstract type %0">; + def err_array_of_abstract_type : Error<"array of abstract class type %0">; + def err_capture_of_abstract_type : Error< + "by-copy capture of value of abstract type %0">; + def err_capture_of_incomplete_or_sizeless_type : Error< + "by-copy capture of variable %0 with %select{incomplete|sizeless}1 type %2">; + def err_capture_default_non_local : Error< + "non-local lambda expression cannot have a capture-default">; + + def err_multiple_final_overriders : Error< + "virtual function %q0 has more than one final overrider in %1">; + def note_final_overrider : Note<"final overrider of %q0 in %1">; + + def err_type_defined_in_type_specifier : Error< + "%0 cannot be defined in a type specifier">; + def err_type_defined_in_result_type : Error< + "%0 cannot be defined in the result type of a function">; + def err_type_defined_in_param_type : Error< + "%0 cannot be defined in a parameter type">; + def err_type_defined_in_alias_template : Error< + "%0 cannot be defined in a type alias template">; + def err_type_defined_in_condition : Error< + "%0 cannot be defined in a condition">; + def err_type_defined_in_enum : Error< + "%0 cannot be defined in an enumeration">; + + def note_pure_virtual_function : Note< + "unimplemented pure virtual method %0 in %1">; + + def note_pure_qualified_call_kext : Note< + "qualified call to %0::%1 is treated as a virtual call to %1 due to -fapple-kext">; + + def err_deleted_decl_not_first : Error< + "deleted definition must be first declaration">; + + def err_deleted_override : Error< + "deleted function %0 cannot override a non-deleted function">; + def err_non_deleted_override : Error< + "non-deleted function %0 cannot override a deleted function">; + def err_consteval_override : Error< + "consteval function %0 cannot override a non-consteval function">; + def err_non_consteval_override : Error< + "non-consteval function %0 cannot override a consteval function">; + + def warn_weak_vtable : Warning< + "%0 has no out-of-line virtual method definitions; its vtable will be " + "emitted in every translation unit">, + InGroup>, DefaultIgnore; + def warn_weak_template_vtable : Warning< + "explicit template instantiation %0 will emit a vtable in every " + "translation unit">, + InGroup>, DefaultIgnore; + + def ext_using_undefined_std : ExtWarn< + "using directive refers to implicitly-defined namespace 'std'">; + + // C++ exception specifications + def err_exception_spec_in_typedef : Error< + "exception specifications are not allowed in %select{typedefs|type aliases}0">; + def err_distant_exception_spec : Error< + "exception specifications are not allowed beyond a single level " + "of indirection">; + def err_incomplete_in_exception_spec : Error< + "%select{|pointer to |reference to }0incomplete type %1 is not allowed " + "in exception specification">; + def err_sizeless_in_exception_spec : Error< + "%select{|reference to }0sizeless type %1 is not allowed " + "in exception specification">; + def ext_incomplete_in_exception_spec : ExtWarn, + InGroup; + def err_rref_in_exception_spec : Error< + "rvalue reference type %0 is not allowed in exception specification">; + def err_mismatched_exception_spec : Error< + "exception specification in declaration does not match previous declaration">; + def ext_mismatched_exception_spec : ExtWarn, + InGroup; + def err_override_exception_spec : Error< + "exception specification of overriding function is more lax than " + "base version">; + def ext_override_exception_spec : ExtWarn, + InGroup; + def err_incompatible_exception_specs : Error< + "target exception specification is not superset of source">; + def warn_incompatible_exception_specs : Warning< + err_incompatible_exception_specs.Text>, InGroup; + def err_deep_exception_specs_differ : Error< + "exception specifications of %select{return|argument}0 types differ">; + def warn_deep_exception_specs_differ : Warning< + err_deep_exception_specs_differ.Text>, InGroup; + def err_missing_exception_specification : Error< + "%0 is missing exception specification '%1'">; + def ext_missing_exception_specification : ExtWarn< + err_missing_exception_specification.Text>, + InGroup>; + def ext_ms_missing_exception_specification : ExtWarn< + err_missing_exception_specification.Text>, + InGroup; + def err_noexcept_needs_constant_expression : Error< + "argument to noexcept specifier must be a constant expression">; + def err_exception_spec_not_parsed : Error< + "exception specification is not available until end of class definition">; + def err_exception_spec_cycle : Error< + "exception specification of %0 uses itself">; + def err_exception_spec_incomplete_type : Error< + "exception specification needed for member of incomplete class %0">; + def warn_wasm_dynamic_exception_spec_ignored : ExtWarn< + "dynamic exception specifications with types are currently ignored in wasm">, + InGroup; + + // C++ access checking + def err_class_redeclared_with_different_access : Error< + "%0 redeclared with '%1' access">; + def err_access : Error< + "%1 is a %select{private|protected}0 member of %3">, AccessControl; + def ext_ms_using_declaration_inaccessible : ExtWarn< + "using declaration referring to inaccessible member '%0' (which refers " + "to accessible member '%1') is a Microsoft compatibility extension">, + AccessControl, InGroup; + def err_access_ctor : Error< + "calling a %select{private|protected}0 constructor of class %2">, + AccessControl; + def ext_rvalue_to_reference_access_ctor : Extension< + "C++98 requires an accessible copy constructor for class %2 when binding " + "a reference to a temporary; was %select{private|protected}0">, + AccessControl, InGroup; + def err_access_base_ctor : Error< + // The ERRORs represent other special members that aren't constructors, in + // hopes that someone will bother noticing and reporting if they appear + "%select{base class|inherited virtual base class}0 %1 has %select{private|" + "protected}3 %select{default |copy |move |*ERROR* |*ERROR* " + "|*ERROR*|}2constructor">, AccessControl; + def err_access_field_ctor : Error< + // The ERRORs represent other special members that aren't constructors, in + // hopes that someone will bother noticing and reporting if they appear + "field of type %0 has %select{private|protected}2 " + "%select{default |copy |move |*ERROR* |*ERROR* |*ERROR* |}1constructor">, + AccessControl; + def err_access_friend_function : Error< + "friend function %1 is a %select{private|protected}0 member of %3">, + AccessControl; + + def err_access_dtor : Error< + "calling a %select{private|protected}1 destructor of class %0">, + AccessControl; + def err_access_dtor_base : + Error<"base class %0 has %select{private|protected}1 destructor">, + AccessControl; + def err_access_dtor_vbase : + Error<"inherited virtual base class %1 has " + "%select{private|protected}2 destructor">, + AccessControl; + def err_access_dtor_temp : + Error<"temporary of type %0 has %select{private|protected}1 destructor">, + AccessControl; + def err_access_dtor_exception : + Error<"exception object of type %0 has %select{private|protected}1 " + "destructor">, AccessControl; + def err_access_dtor_field : + Error<"field of type %1 has %select{private|protected}2 destructor">, + AccessControl; + def err_access_dtor_var : + Error<"variable of type %1 has %select{private|protected}2 destructor">, + AccessControl; + def err_access_dtor_ivar : + Error<"instance variable of type %0 has %select{private|protected}1 " + "destructor">, + AccessControl; + def note_previous_access_declaration : Note< + "previously declared '%1' here">; + def note_access_natural : Note< + "%select{|implicitly }1declared %select{private|protected}0 here">; + def note_access_constrained_by_path : Note< + "constrained by %select{|implicitly }1%select{private|protected}0" + " inheritance here">; + def note_access_protected_restricted_noobject : Note< + "must name member using the type of the current context %0">; + def note_access_protected_restricted_ctordtor : Note< + "protected %select{constructor|destructor}0 can only be used to " + "%select{construct|destroy}0 a base class subobject">; + def note_access_protected_restricted_object : Note< + "can only access this member on an object of type %0">; + def warn_cxx98_compat_sfinae_access_control : Warning< + "substitution failure due to access control is incompatible with C++98">, + InGroup, DefaultIgnore, NoSFINAE; + + // C++ name lookup + def err_incomplete_nested_name_spec : Error< + "incomplete type %0 named in nested name specifier">; + def err_incomplete_enum : Error< + "enumeration %0 is incomplete">; + def err_dependent_nested_name_spec : Error< + "nested name specifier for a declaration cannot depend on a template " + "parameter">; + def err_nested_name_member_ref_lookup_ambiguous : Error< + "lookup of %0 in member access expression is ambiguous">; + def ext_nested_name_member_ref_lookup_ambiguous : ExtWarn< + "lookup of %0 in member access expression is ambiguous; using member of %1">, + InGroup; + def note_ambig_member_ref_object_type : Note< + "lookup in the object type %0 refers here">; + def note_ambig_member_ref_scope : Note< + "lookup from the current scope refers here">; + def err_qualified_member_nonclass : Error< + "qualified member access refers to a member in %0">; + def err_incomplete_member_access : Error< + "member access into incomplete type %0">; + def err_incomplete_type : Error< + "incomplete type %0 where a complete type is required">; + def warn_cxx98_compat_enum_nested_name_spec : Warning< + "enumeration type in nested name specifier is incompatible with C++98">, + InGroup, DefaultIgnore; + def err_nested_name_spec_is_not_class : Error< + "%0 cannot appear before '::' because it is not a class" + "%select{ or namespace|, namespace, or enumeration}1; did you mean ':'?">; + def ext_nested_name_spec_is_enum : ExtWarn< + "use of enumeration in a nested name specifier is a C++11 extension">, + InGroup; + def err_out_of_line_qualified_id_type_names_constructor : Error< + "qualified reference to %0 is a constructor name rather than a " + "%select{template name|type}1 in this context">; + def ext_out_of_line_qualified_id_type_names_constructor : ExtWarn< + "ISO C++ specifies that " + "qualified reference to %0 is a constructor name rather than a " + "%select{template name|type}1 in this context, despite preceding " + "%select{'typename'|'template'}2 keyword">, SFINAEFailure, + InGroup>; + + // C++ class members + def err_storageclass_invalid_for_member : Error< + "storage class specified for a member declaration">; + def err_mutable_function : Error<"'mutable' cannot be applied to functions">; + def err_mutable_reference : Error<"'mutable' cannot be applied to references">; + def ext_mutable_reference : ExtWarn< + "'mutable' on a reference type is a Microsoft extension">, + InGroup; + def err_mutable_const : Error<"'mutable' and 'const' cannot be mixed">; + def err_mutable_nonmember : Error< + "'mutable' can only be applied to member variables">; + def err_virtual_in_union : Error< + "unions cannot have virtual functions">; + def err_virtual_non_function : Error< + "'virtual' can only appear on non-static member functions">; + def err_virtual_out_of_class : Error< + "'virtual' can only be specified inside the class definition">; + def err_virtual_member_function_template : Error< + "'virtual' cannot be specified on member function templates">; + def err_static_overrides_virtual : Error< + "'static' member function %0 overrides a virtual function in a base class">; + def err_explicit_non_function : Error< + "'explicit' can only appear on non-static member functions">; + def err_explicit_out_of_class : Error< + "'explicit' can only be specified inside the class definition">; + def err_explicit_non_ctor_or_conv_function : Error< + "'explicit' can only be applied to a constructor or conversion function">; + def err_static_not_bitfield : Error<"static member %0 cannot be a bit-field">; + def err_static_out_of_line : Error< + "'static' can only be specified inside the class definition">; + def ext_static_out_of_line : ExtWarn< + err_static_out_of_line.Text>, + InGroup; + def err_storage_class_for_static_member : Error< + "static data member definition cannot specify a storage class">; + def err_typedef_not_bitfield : Error<"typedef member %0 cannot be a bit-field">; + def err_not_integral_type_bitfield : Error< + "bit-field %0 has non-integral type %1">; + def err_not_integral_type_anon_bitfield : Error< + "anonymous bit-field has non-integral type %0">; + def err_anon_bitfield_qualifiers : Error< + "anonymous bit-field cannot have qualifiers">; + def err_member_function_initialization : Error< + "initializer on function does not look like a pure-specifier">; + def err_non_virtual_pure : Error< + "%0 is not virtual and cannot be declared pure">; + def ext_pure_function_definition : ExtWarn< + "function definition with pure-specifier is a Microsoft extension">, + InGroup; + def err_qualified_member_of_unrelated : Error< + "%q0 is not a member of class %1">; + + def err_member_function_call_bad_cvr : Error< + "'this' argument to member function %0 has type %1, but function is not marked " + "%select{const|restrict|const or restrict|volatile|const or volatile|" + "volatile or restrict|const, volatile, or restrict}2">; + def err_member_function_call_bad_ref : Error< + "'this' argument to member function %0 is an %select{lvalue|rvalue}1, " + "but function has %select{non-const lvalue|rvalue}2 ref-qualifier">; + def err_member_function_call_bad_type : Error< + "cannot initialize object parameter of type %0 with an expression " + "of type %1">; + + def warn_call_to_pure_virtual_member_function_from_ctor_dtor : Warning< + "call to pure virtual member function %0 has undefined behavior; " + "overrides of %0 in subclasses are not available in the " + "%select{constructor|destructor}1 of %2">, InGroup; + + def select_special_member_kind : TextSubstitution< + "%select{default constructor|copy constructor|move constructor|" + "copy assignment operator|move assignment operator|destructor}0">; + + def note_member_declared_at : Note<"member is declared here">; + def note_ivar_decl : Note<"instance variable is declared here">; + def note_bitfield_decl : Note<"bit-field is declared here">; + def note_implicit_param_decl : Note<"%0 is an implicit parameter">; + def note_member_synthesized_at : Note< + "in %select{implicit|defaulted}0 %sub{select_special_member_kind}1 for %2 " + "first required here">; + def note_comparison_synthesized_at : Note< + "in defaulted %sub{select_defaulted_comparison_kind}0 for %1 " + "first required here">; + def err_missing_default_ctor : Error< + "%select{constructor for %1 must explicitly initialize the|" + "implicit default constructor for %1 must explicitly initialize the|" + "cannot use constructor inherited from base class %4;}0 " + "%select{base class|member}2 %3 %select{which|which|of %1}0 " + "does not have a default constructor">; + def note_due_to_dllexported_class : Note< + "due to %0 being dllexported%select{|; try compiling in C++11 mode}1">; + + def err_illegal_union_or_anon_struct_member : Error< + "%select{anonymous struct|union}0 member %1 has a non-trivial " + "%sub{select_special_member_kind}2">; + + def warn_frame_address : Warning< + "calling '%0' with a nonzero argument is unsafe">, + InGroup, DefaultIgnore; + + def warn_cxx98_compat_nontrivial_union_or_anon_struct_member : Warning< + "%select{anonymous struct|union}0 member %1 with a non-trivial " + "%sub{select_special_member_kind}2 is incompatible with C++98">, + InGroup, DefaultIgnore; + + def note_nontrivial_virtual_dtor : Note< + "destructor for %0 is not trivial because it is virtual">; + def note_nontrivial_has_virtual : Note< + "because type %0 has a virtual %select{member function|base class}1">; + def note_nontrivial_no_def_ctor : Note< + "because %select{base class of |field of |}0type %1 has no " + "default constructor">; + def note_user_declared_ctor : Note< + "implicit default constructor suppressed by user-declared constructor">; + def note_nontrivial_no_copy : Note< + "because no %select{<>|constructor|constructor|assignment operator|" + "assignment operator|<>}2 can be used to " + "%select{<>|copy|move|copy|move|<>}2 " + "%select{base class|field|an object}0 of type %3">; + def note_nontrivial_user_provided : Note< + "because %select{base class of |field of |}0type %1 has a user-provided " + "%sub{select_special_member_kind}2">; + def note_nontrivial_default_member_init : Note< + "because field %0 has an initializer">; + def note_nontrivial_param_type : Note< + "because its parameter is %diff{of type $, not $|of the wrong type}2,3">; + def note_nontrivial_default_arg : Note<"because it has a default argument">; + def note_nontrivial_variadic : Note<"because it is a variadic function">; + def note_nontrivial_subobject : Note< + "because the function selected to %select{construct|copy|move|copy|move|" + "destroy}2 %select{base class|field}0 of type %1 is not trivial">; + def note_nontrivial_objc_ownership : Note< + "because type %0 has a member with %select{no|no|__strong|__weak|" + "__autoreleasing}1 ownership">; + + /// Selector for a TagTypeKind value. + def select_tag_type_kind : TextSubstitution< + "%select{struct|interface|union|class|enum}0">; + + def err_static_data_member_not_allowed_in_anon_struct : Error< + "static data member %0 not allowed in anonymous " + "%sub{select_tag_type_kind}1">; + def ext_static_data_member_in_union : ExtWarn< + "static data member %0 in union is a C++11 extension">, InGroup; + def warn_cxx98_compat_static_data_member_in_union : Warning< + "static data member %0 in union is incompatible with C++98">, + InGroup, DefaultIgnore; + def ext_union_member_of_reference_type : ExtWarn< + "union member %0 has reference type %1, which is a Microsoft extension">, + InGroup; + def err_union_member_of_reference_type : Error< + "union member %0 has reference type %1">; + def ext_anonymous_struct_union_qualified : Extension< + "anonymous %select{struct|union}0 cannot be '%1'">; + def err_different_return_type_for_overriding_virtual_function : Error< + "virtual function %0 has a different return type " + "%diff{($) than the function it overrides (which has return type $)|" + "than the function it overrides}1,2">; + def note_overridden_virtual_function : Note< + "overridden virtual function is here">; + def err_conflicting_overriding_cc_attributes : Error< + "virtual function %0 has different calling convention attributes " + "%diff{($) than the function it overrides (which has calling convention $)|" + "than the function it overrides}1,2">; + def warn_overriding_method_missing_noescape : Warning< + "parameter of overriding method should be annotated with " + "__attribute__((noescape))">, InGroup; + def note_overridden_marked_noescape : Note< + "parameter of overridden method is annotated with __attribute__((noescape))">; + def note_cat_conform_to_noescape_prot : Note< + "%select{category|class extension}0 conforms to protocol %1 which defines method %2">; + + def err_covariant_return_inaccessible_base : Error< + "invalid covariant return for virtual function: %1 is a " + "%select{private|protected}2 base class of %0">, AccessControl; + def err_covariant_return_ambiguous_derived_to_base_conv : Error< + "return type of virtual function %3 is not covariant with the return type of " + "the function it overrides (ambiguous conversion from derived class " + "%0 to base class %1:%2)">; + def err_covariant_return_not_derived : Error< + "return type of virtual function %0 is not covariant with the return type of " + "the function it overrides (%1 is not derived from %2)">; + def err_covariant_return_incomplete : Error< + "return type of virtual function %0 is not covariant with the return type of " + "the function it overrides (%1 is incomplete)">; + def err_covariant_return_type_different_qualifications : Error< + "return type of virtual function %0 is not covariant with the return type of " + "the function it overrides (%1 has different qualifiers than %2)">; + def err_covariant_return_type_class_type_more_qualified : Error< + "return type of virtual function %0 is not covariant with the return type of " + "the function it overrides (class type %1 is more qualified than class " + "type %2">; + + // C++ implicit special member functions + def note_in_declaration_of_implicit_special_member : Note< + "while declaring the implicit %sub{select_special_member_kind}1" + " for %0">; + + // C++ constructors + def err_constructor_cannot_be : Error<"constructor cannot be declared '%0'">; + def err_invalid_qualified_constructor : Error< + "'%0' qualifier is not allowed on a constructor">; + def err_ref_qualifier_constructor : Error< + "ref-qualifier '%select{&&|&}0' is not allowed on a constructor">; + + def err_constructor_return_type : Error< + "constructor cannot have a return type">; + def err_constructor_redeclared : Error<"constructor cannot be redeclared">; + def err_constructor_byvalue_arg : Error< + "copy constructor must pass its first argument by reference">; + def warn_no_constructor_for_refconst : Warning< + "%select{struct|interface|union|class|enum}0 %1 does not declare any " + "constructor to initialize its non-modifiable members">; + def note_refconst_member_not_initialized : Note< + "%select{const|reference}0 member %1 will never be initialized">; + def ext_ms_explicit_constructor_call : ExtWarn< + "explicit constructor calls are a Microsoft extension">, + InGroup; + + // C++ destructors + def err_destructor_not_member : Error< + "destructor must be a non-static member function">; + def err_destructor_cannot_be : Error<"destructor cannot be declared '%0'">; + def err_invalid_qualified_destructor : Error< + "'%0' qualifier is not allowed on a destructor">; + def err_ref_qualifier_destructor : Error< + "ref-qualifier '%select{&&|&}0' is not allowed on a destructor">; + def err_destructor_return_type : Error<"destructor cannot have a return type">; + def err_destructor_redeclared : Error<"destructor cannot be redeclared">; + def err_destructor_with_params : Error<"destructor cannot have any parameters">; + def err_destructor_variadic : Error<"destructor cannot be variadic">; + def ext_destructor_typedef_name : ExtWarn< + "destructor cannot be declared using a %select{typedef|type alias}1 %0 " + "of the class name">, DefaultError, InGroup>; + def err_undeclared_destructor_name : Error< + "undeclared identifier %0 in destructor name">; + def err_destructor_name : Error< + "expected the class name after '~' to name the enclosing class">; + def err_destructor_name_nontype : Error< + "identifier %0 after '~' in destructor name does not name a type">; + def err_destructor_expr_mismatch : Error< + "identifier %0 in object destruction expression does not name the type " + "%1 of the object being destroyed">; + def err_destructor_expr_nontype : Error< + "identifier %0 in object destruction expression does not name a type">; + def err_destructor_expr_type_mismatch : Error< + "destructor type %0 in object destruction expression does not match the " + "type %1 of the object being destroyed">; + def note_destructor_type_here : Note< + "type %0 found by destructor name lookup">; + def note_destructor_nontype_here : Note< + "non-type declaration found by destructor name lookup">; + def ext_dtor_named_in_wrong_scope : Extension< + "ISO C++ requires the name after '::~' to be found in the same scope as " + "the name before '::~'">, InGroup; + def ext_qualified_dtor_named_in_lexical_scope : ExtWarn< + "qualified destructor name only found in lexical scope; omit the qualifier " + "to find this type name by unqualified lookup">, InGroup; + def ext_dtor_name_ambiguous : Extension< + "ISO C++ considers this destructor name lookup to be ambiguous">, + InGroup; + + def err_destroy_attr_on_non_static_var : Error< + "%select{no_destroy|always_destroy}0 attribute can only be applied to a" + " variable with static or thread storage duration">; + + def err_destructor_template : Error< + "destructor cannot be declared as a template">; + + // C++ initialization + def err_init_conversion_failed : Error< + "cannot initialize %select{a variable|a parameter|template parameter|" + "return object|statement expression result|an " + "exception object|a member subobject|an array element|a new value|a value|a " + "base class|a constructor delegation|a vector element|a block element|a " + "block element|a complex element|a lambda capture|a compound literal " + "initializer|a related result|a parameter of CF audited function}0 " + "%diff{of type $ with an %select{rvalue|lvalue}2 of type $|" + "with an %select{rvalue|lvalue}2 of incompatible type}1,3" + "%select{|: different classes%diff{ ($ vs $)|}5,6" + "|: different number of parameters (%5 vs %6)" + "|: type mismatch at %ordinal5 parameter%diff{ ($ vs $)|}6,7" + "|: different return type%diff{ ($ vs $)|}5,6" + "|: different qualifiers (%5 vs %6)" + "|: different exception specifications}4">; + def note_forward_class_conversion : Note<"%0 is not defined, but forward " + "declared here; conversion would be valid if it was derived from %1">; + + def err_lvalue_to_rvalue_ref : Error<"rvalue reference %diff{to type $ cannot " + "bind to lvalue of type $|cannot bind to incompatible lvalue}0,1">; + def err_lvalue_reference_bind_to_initlist : Error< + "%select{non-const|volatile}0 lvalue reference to type %1 cannot bind to an " + "initializer list temporary">; + def err_lvalue_reference_bind_to_temporary : Error< + "%select{non-const|volatile}0 lvalue reference %diff{to type $ cannot bind " + "to a temporary of type $|cannot bind to incompatible temporary}1,2">; + def err_lvalue_reference_bind_to_unrelated : Error< + "%select{non-const|volatile}0 lvalue reference " + "%diff{to type $ cannot bind to a value of unrelated type $|" + "cannot bind to a value of unrelated type}1,2">; + def err_reference_bind_drops_quals : Error< + "binding reference %diff{of type $ to value of type $|to value}0,1 " + "%select{drops %3 qualifier%plural{1:|2:|4:|:s}4|changes address space|" + "not permitted due to incompatible qualifiers}2">; + def err_reference_bind_failed : Error< + "reference %diff{to %select{type|incomplete type}1 $ could not bind to an " + "%select{rvalue|lvalue}2 of type $|could not bind to %select{rvalue|lvalue}2 of " + "incompatible type}0,3">; + def err_reference_bind_temporary_addrspace : Error< + "reference of type %0 cannot bind to a temporary object because of " + "address space mismatch">; + def err_reference_bind_init_list : Error< + "reference to type %0 cannot bind to an initializer list">; + def err_init_list_bad_dest_type : Error< + "%select{|non-aggregate }0type %1 cannot be initialized with an initializer " + "list">; + def warn_cxx20_compat_aggregate_init_with_ctors : Warning< + "aggregate initialization of type %0 with user-declared constructors " + "is incompatible with C++20">, DefaultIgnore, InGroup; + + def err_reference_bind_to_bitfield : Error< + "%select{non-const|volatile}0 reference cannot bind to " + "bit-field%select{| %1}2">; + def err_reference_bind_to_vector_element : Error< + "%select{non-const|volatile}0 reference cannot bind to vector element">; + def err_reference_bind_to_matrix_element : Error< + "%select{non-const|volatile}0 reference cannot bind to matrix element">; + def err_reference_var_requires_init : Error< + "declaration of reference variable %0 requires an initializer">; + def err_reference_without_init : Error< + "reference to type %0 requires an initializer">; + def note_value_initialization_here : Note< + "in value-initialization of type %0 here">; + def err_reference_has_multiple_inits : Error< + "reference cannot be initialized with multiple values">; + def err_init_non_aggr_init_list : Error< + "initialization of non-aggregate type %0 with an initializer list">; + def err_init_reference_member_uninitialized : Error< + "reference member of type %0 uninitialized">; + def note_uninit_reference_member : Note< + "uninitialized reference member is here">; + def warn_field_is_uninit : Warning<"field %0 is uninitialized when used here">, + InGroup; + def warn_base_class_is_uninit : Warning< + "base class %0 is uninitialized when used here to access %q1">, + InGroup; + def warn_reference_field_is_uninit : Warning< + "reference %0 is not yet bound to a value when used here">, + InGroup; + def note_uninit_in_this_constructor : Note< + "during field initialization in %select{this|the implicit default}0 " + "constructor">; + def warn_static_self_reference_in_init : Warning< + "static variable %0 is suspiciously used within its own initialization">, + InGroup; + def warn_uninit_self_reference_in_init : Warning< + "variable %0 is uninitialized when used within its own initialization">, + InGroup; + def warn_uninit_self_reference_in_reference_init : Warning< + "reference %0 is not yet bound to a value when used within its own" + " initialization">, + InGroup; + def warn_uninit_var : Warning< + "variable %0 is uninitialized when %select{used here|captured by block}1">, + InGroup, DefaultIgnore; + def warn_sometimes_uninit_var : Warning< + "variable %0 is %select{used|captured}1 uninitialized whenever " + "%select{'%3' condition is %select{true|false}4|" + "'%3' loop %select{is entered|exits because its condition is false}4|" + "'%3' loop %select{condition is true|exits because its condition is false}4|" + "switch %3 is taken|" + "its declaration is reached|" + "%3 is called}2">, + InGroup, DefaultIgnore; + def warn_maybe_uninit_var : Warning< + "variable %0 may be uninitialized when " + "%select{used here|captured by block}1">, + InGroup, DefaultIgnore; + def note_var_declared_here : Note<"variable %0 is declared here">; + def note_uninit_var_use : Note< + "%select{uninitialized use occurs|variable is captured by block}0 here">; + def warn_uninit_byref_blockvar_captured_by_block : Warning< + "block pointer variable %0 is %select{uninitialized|null}1 when captured by " + "block">, InGroup, DefaultIgnore; + def note_block_var_fixit_add_initialization : Note< + "did you mean to use __block %0?">; + def note_in_omitted_aggregate_initializer : Note< + "in implicit initialization of %select{" + "array element %1 with omitted initializer|" + "field %1 with omitted initializer|" + "trailing array elements in runtime-sized array new}0">; + def note_in_reference_temporary_list_initializer : Note< + "in initialization of temporary of type %0 created to " + "list-initialize this reference">; + def note_var_fixit_add_initialization : Note< + "initialize the variable %0 to silence this warning">; + def note_uninit_fixit_remove_cond : Note< + "remove the %select{'%1' if its condition|condition if it}0 " + "is always %select{false|true}2">; + def err_init_incomplete_type : Error<"initialization of incomplete type %0">; + def err_list_init_in_parens : Error< + "cannot initialize %select{non-class|reference}0 type %1 with a " + "parenthesized initializer list">; + + def warn_uninit_const_reference : Warning< + "variable %0 is uninitialized when passed as a const reference argument " + "here">, InGroup, DefaultIgnore; + + def warn_unsequenced_mod_mod : Warning< + "multiple unsequenced modifications to %0">, InGroup; + def warn_unsequenced_mod_use : Warning< + "unsequenced modification and access to %0">, InGroup; + + def select_initialized_entity_kind : TextSubstitution< + "%select{copying variable|copying parameter|initializing template parameter|" + "returning object|initializing statement expression result|" + "throwing object|copying member subobject|copying array element|" + "allocating object|copying temporary|initializing base subobject|" + "initializing vector element|capturing value}0">; + + def err_temp_copy_no_viable : Error< + "no viable constructor %sub{select_initialized_entity_kind}0 of type %1">; + def ext_rvalue_to_reference_temp_copy_no_viable : Extension< + "no viable constructor %sub{select_initialized_entity_kind}0 of type %1; " + "C++98 requires a copy constructor when binding a reference to a temporary">, + InGroup; + def err_temp_copy_ambiguous : Error< + "ambiguous constructor call when %sub{select_initialized_entity_kind}0 " + "of type %1">; + def err_temp_copy_deleted : Error< + "%sub{select_initialized_entity_kind}0 of type %1 " + "invokes deleted constructor">; + def err_temp_copy_incomplete : Error< + "copying a temporary object of incomplete type %0">; + def warn_cxx98_compat_temp_copy : Warning< + "%sub{select_initialized_entity_kind}1 " + "of type %2 when binding a reference to a temporary would %select{invoke " + "an inaccessible constructor|find no viable constructor|find ambiguous " + "constructors|invoke a deleted constructor}0 in C++98">, + InGroup, DefaultIgnore; + def err_selected_explicit_constructor : Error< + "chosen constructor is explicit in copy-initialization">; + def note_explicit_ctor_deduction_guide_here : Note< + "explicit %select{constructor|deduction guide}0 declared here">; + + // C++11 decltype + def err_decltype_in_declarator : Error< + "'decltype' cannot be used to name a declaration">; + + // C++11 auto + def warn_cxx98_compat_auto_type_specifier : Warning< + "'auto' type specifier is incompatible with C++98">, + InGroup, DefaultIgnore; + def err_auto_variable_cannot_appear_in_own_initializer : Error< + "variable %0 declared with deduced type %1 " + "cannot appear in its own initializer">; + def err_binding_cannot_appear_in_own_initializer : Error< + "binding %0 cannot appear in the initializer of its own " + "decomposition declaration">; + def err_illegal_decl_array_of_auto : Error< + "'%0' declared as array of %1">; + def err_new_array_of_auto : Error< + "cannot allocate array of 'auto'">; + def err_auto_not_allowed : Error< + "%select{'auto'|'decltype(auto)'|'__auto_type'|" + "use of " + "%select{class template|function template|variable template|alias template|" + "template template parameter|concept|template}2 %3 requires template " + "arguments; argument deduction}0 not allowed " + "%select{in function prototype" + "|in non-static struct member|in struct member" + "|in non-static union member|in union member" + "|in non-static class member|in interface member" + "|in exception declaration|in template parameter until C++17|in block literal" + "|in template argument|in typedef|in type alias|in function return type" + "|in conversion function type|here|in lambda parameter" + "|in type allocated by 'new'|in K&R-style function parameter" + "|in template parameter|in friend declaration|in function prototype that is " + "not a function declaration|in requires expression parameter}1">; + def err_dependent_deduced_tst : Error< + "typename specifier refers to " + "%select{class template|function template|variable template|alias template|" + "template template parameter|template}0 member in %1; " + "argument deduction not allowed here">; + def err_deduced_tst : Error< + "typename specifier refers to " + "%select{class template|function template|variable template|alias template|" + "template template parameter|template}0; argument deduction not allowed " + "here">; + def err_auto_not_allowed_var_inst : Error< + "'auto' variable template instantiation is not allowed">; + def err_auto_var_requires_init : Error< + "declaration of variable %0 with deduced type %1 requires an initializer">; + def err_auto_new_requires_ctor_arg : Error< + "new expression for type %0 requires a constructor argument">; + def ext_auto_new_list_init : Extension< + "ISO C++ standards before C++17 do not allow new expression for " + "type %0 to use list-initialization">, InGroup; + def err_auto_var_init_no_expression : Error< + "initializer for variable %0 with type %1 is empty">; + def err_auto_var_init_multiple_expressions : Error< + "initializer for variable %0 with type %1 contains multiple expressions">; + def err_auto_var_init_paren_braces : Error< + "cannot deduce type for variable %1 with type %2 from " + "%select{parenthesized|nested}0 initializer list">; + def err_auto_new_ctor_multiple_expressions : Error< + "new expression for type %0 contains multiple constructor arguments">; + def err_auto_missing_trailing_return : Error< + "'auto' return without trailing return type; deduced return types are a " + "C++14 extension">; + def err_deduced_return_type : Error< + "deduced return types are a C++14 extension">; + def err_trailing_return_without_auto : Error< + "function with trailing return type must specify return type 'auto', not %0">; + def err_trailing_return_in_parens : Error< + "trailing return type may not be nested within parentheses">; + def err_auto_var_deduction_failure : Error< + "variable %0 with type %1 has incompatible initializer of type %2">; + def err_auto_var_deduction_failure_from_init_list : Error< + "cannot deduce actual type for variable %0 with type %1 from initializer list">; + def err_auto_new_deduction_failure : Error< + "new expression for type %0 has incompatible constructor argument of type %1">; + def err_auto_inconsistent_deduction : Error< + "deduced conflicting types %diff{($ vs $) |}0,1" + "for initializer list element type">; + def err_auto_different_deductions : Error< + "%select{'auto'|'decltype(auto)'|'__auto_type'|template arguments}0 " + "deduced as %1 in declaration of %2 and " + "deduced as %3 in declaration of %4">; + def err_auto_non_deduced_not_alone : Error< + "%select{function with deduced return type|" + "declaration with trailing return type}0 " + "must be the only declaration in its group">; + def err_implied_std_initializer_list_not_found : Error< + "cannot deduce type of initializer list because std::initializer_list was " + "not found; include ">; + def err_malformed_std_initializer_list : Error< + "std::initializer_list must be a class template with a single type parameter">; + def err_auto_init_list_from_c : Error< + "cannot use __auto_type with initializer list in C">; + def err_auto_bitfield : Error< + "cannot pass bit-field as __auto_type initializer in C">; + + // C++1y decltype(auto) type + def err_decltype_auto_invalid : Error< + "'decltype(auto)' not allowed here">; + def err_decltype_auto_cannot_be_combined : Error< + "'decltype(auto)' cannot be combined with other type specifiers">; + def err_decltype_auto_function_declarator_not_declaration : Error< + "'decltype(auto)' can only be used as a return type " + "in a function declaration">; + def err_decltype_auto_compound_type : Error< + "cannot form %select{pointer to|reference to|array of}0 'decltype(auto)'">; + def err_decltype_auto_initializer_list : Error< + "cannot deduce 'decltype(auto)' from initializer list">; + + // C++17 deduced class template specialization types + def err_deduced_class_template_compound_type : Error< + "cannot %select{form pointer to|form reference to|form array of|" + "form function returning|use parentheses when declaring variable with}0 " + "deduced class template specialization type">; + def err_deduced_non_class_template_specialization_type : Error< + "%select{|function template|variable template|alias template|" + "template template parameter|concept|template}0 %1 requires template " + "arguments; argument deduction only allowed for class templates">; + def err_deduced_class_template_ctor_ambiguous : Error< + "ambiguous deduction for template arguments of %0">; + def err_deduced_class_template_ctor_no_viable : Error< + "no viable constructor or deduction guide for deduction of " + "template arguments of %0">; + def err_deduced_class_template_incomplete : Error< + "template %0 has no definition and no %select{|viable }1deduction guides " + "for deduction of template arguments">; + def err_deduced_class_template_deleted : Error< + "class template argument deduction for %0 selected a deleted constructor">; + def err_deduced_class_template_explicit : Error< + "class template argument deduction for %0 selected an explicit " + "%select{constructor|deduction guide}1 for copy-list-initialization">; + def err_deduction_guide_no_trailing_return_type : Error< + "deduction guide declaration without trailing return type">; + def err_deduction_guide_bad_trailing_return_type : Error< + "deduced type %1 of deduction guide is not %select{|written as }2" + "a specialization of template %0">; + def err_deduction_guide_with_complex_decl : Error< + "cannot specify any part of a return type in the " + "declaration of a deduction guide">; + def err_deduction_guide_invalid_specifier : Error< + "deduction guide cannot be declared '%0'">; + def err_deduction_guide_name_not_class_template : Error< + "cannot specify deduction guide for " + "%select{|function template|variable template|alias template|" + "template template parameter|concept|dependent template name}0 %1">; + def err_deduction_guide_wrong_scope : Error< + "deduction guide must be declared in the same scope as template %q0">; + def err_deduction_guide_defines_function : Error< + "deduction guide cannot have a function definition">; + def err_deduction_guide_redeclared : Error< + "redeclaration of deduction guide">; + def err_deduction_guide_specialized : Error<"deduction guide cannot be " + "%select{explicitly instantiated|explicitly specialized}0">; + def err_deduction_guide_template_not_deducible : Error< + "deduction guide template contains " + "%select{a template parameter|template parameters}0 that cannot be " + "deduced">; + def err_deduction_guide_wrong_access : Error< + "deduction guide has different access from the corresponding " + "member template">; + def note_deduction_guide_template_access : Note< + "member template declared %0 here">; + def note_deduction_guide_access : Note< + "deduction guide declared %0 by intervening access specifier">; + def warn_cxx14_compat_class_template_argument_deduction : Warning< + "class template argument deduction is incompatible with C++ standards " + "before C++17%select{|; for compatibility, use explicit type name %1}0">, + InGroup, DefaultIgnore; + def warn_ctad_maybe_unsupported : Warning< + "%0 may not intend to support class template argument deduction">, + InGroup, DefaultIgnore; + def note_suppress_ctad_maybe_unsupported : Note< + "add a deduction guide to suppress this warning">; + + + // C++14 deduced return types + def err_auto_fn_deduction_failure : Error< + "cannot deduce return type %0 from returned value of type %1">; + def err_auto_fn_different_deductions : Error< + "'%select{auto|decltype(auto)}0' in return type deduced as %1 here but " + "deduced as %2 in earlier return statement">; + def err_auto_fn_used_before_defined : Error< + "function %0 with deduced return type cannot be used before it is defined">; + def err_auto_fn_no_return_but_not_auto : Error< + "cannot deduce return type %0 for function with no return statements">; + def err_auto_fn_return_void_but_not_auto : Error< + "cannot deduce return type %0 from omitted return expression">; + def err_auto_fn_return_init_list : Error< + "cannot deduce return type from initializer list">; + def err_auto_fn_virtual : Error< + "function with deduced return type cannot be virtual">; + def warn_cxx11_compat_deduced_return_type : Warning< + "return type deduction is incompatible with C++ standards before C++14">, + InGroup, DefaultIgnore; + + // C++11 override control + def override_keyword_only_allowed_on_virtual_member_functions : Error< + "only virtual member functions can be marked '%0'">; + def override_keyword_hides_virtual_member_function : Error< + "non-virtual member function marked '%0' hides virtual member " + "%select{function|functions}1">; + def err_function_marked_override_not_overriding : Error< + "%0 marked 'override' but does not override any member functions">; + def warn_destructor_marked_not_override_overriding : TextSubstitution < + "%0 overrides a destructor but is not marked 'override'">; + def warn_function_marked_not_override_overriding : TextSubstitution < + "%0 overrides a member function but is not marked 'override'">; + def warn_inconsistent_destructor_marked_not_override_overriding : Warning < + "%sub{warn_destructor_marked_not_override_overriding}0">, + InGroup, DefaultIgnore; + def warn_inconsistent_function_marked_not_override_overriding : Warning < + "%sub{warn_function_marked_not_override_overriding}0">, + InGroup; + def warn_suggest_destructor_marked_not_override_overriding : Warning < + "%sub{warn_destructor_marked_not_override_overriding}0">, + InGroup, DefaultIgnore; + def warn_suggest_function_marked_not_override_overriding : Warning < + "%sub{warn_function_marked_not_override_overriding}0">, + InGroup, DefaultIgnore; + def err_class_marked_final_used_as_base : Error< + "base %0 is marked '%select{final|sealed}1'">; + def warn_abstract_final_class : Warning< + "abstract class is marked '%select{final|sealed}0'">, InGroup; + def warn_final_dtor_non_final_class : Warning< + "class with destructor marked '%select{final|sealed}0' cannot be inherited from">, + InGroup; + def note_final_dtor_non_final_class_silence : Note< + "mark %0 as '%select{final|sealed}1' to silence this warning">; + + // C++11 attributes + def err_repeat_attribute : Error<"%0 attribute cannot be repeated">; + + // C++11 final + def err_final_function_overridden : Error< + "declaration of %0 overrides a '%select{final|sealed}1' function">; + + // C++11 scoped enumerations + def err_enum_invalid_underlying : Error< + "non-integral type %0 is an invalid underlying type">; + def err_enumerator_too_large : Error< + "enumerator value is not representable in the underlying type %0">; + def ext_enumerator_too_large : Extension< + "enumerator value is not representable in the underlying type %0">, + InGroup; + def err_enumerator_wrapped : Error< + "enumerator value %0 is not representable in the underlying type %1">; + def err_enum_redeclare_type_mismatch : Error< + "enumeration redeclared with different underlying type %0 (was %1)">; + def err_enum_redeclare_fixed_mismatch : Error< + "enumeration previously declared with %select{non|}0fixed underlying type">; + def err_enum_redeclare_scoped_mismatch : Error< + "enumeration previously declared as %select{un|}0scoped">; + def err_only_enums_have_underlying_types : Error< + "only enumeration types have underlying types">; + def err_underlying_type_of_incomplete_enum : Error< + "cannot determine underlying type of incomplete enumeration type %0">; + + // C++11 delegating constructors + def err_delegating_ctor : Error< + "delegating constructors are permitted only in C++11">; + def warn_cxx98_compat_delegating_ctor : Warning< + "delegating constructors are incompatible with C++98">, + InGroup, DefaultIgnore; + def err_delegating_initializer_alone : Error< + "an initializer for a delegating constructor must appear alone">; + def warn_delegating_ctor_cycle : Warning< + "constructor for %0 creates a delegation cycle">, DefaultError, + InGroup; + def note_it_delegates_to : Note<"it delegates to">; + def note_which_delegates_to : Note<"which delegates to">; + + // C++11 range-based for loop + def err_for_range_decl_must_be_var : Error< + "for range declaration must declare a variable">; + def err_for_range_storage_class : Error< + "loop variable %0 may not be declared %select{'extern'|'static'|" + "'__private_extern__'|'auto'|'register'|'constexpr'|'thread_local'}1">; + def err_type_defined_in_for_range : Error< + "types may not be defined in a for range declaration">; + def err_for_range_deduction_failure : Error< + "cannot use type %0 as a range">; + def err_for_range_incomplete_type : Error< + "cannot use incomplete type %0 as a range">; + def err_for_range_iter_deduction_failure : Error< + "cannot use type %0 as an iterator">; + def ext_for_range_begin_end_types_differ : ExtWarn< + "'begin' and 'end' returning different types (%0 and %1) is a C++17 extension">, + InGroup; + def warn_for_range_begin_end_types_differ : Warning< + "'begin' and 'end' returning different types (%0 and %1) is incompatible " + "with C++ standards before C++17">, InGroup, DefaultIgnore; + def note_in_for_range: Note< + "when looking up '%select{begin|end}0' function for range expression " + "of type %1">; + def err_for_range_invalid: Error< + "invalid range expression of type %0; no viable '%select{begin|end}1' " + "function available">; + def note_for_range_member_begin_end_ignored : Note< + "member is not a candidate because range type %0 has no '%select{end|begin}1' member">; + def err_range_on_array_parameter : Error< + "cannot build range expression with array function parameter %0 since " + "parameter with array type %1 is treated as pointer type %2">; + def err_for_range_dereference : Error< + "invalid range expression of type %0; did you mean to dereference it " + "with '*'?">; + def note_for_range_invalid_iterator : Note < + "in implicit call to 'operator%select{!=|*|++}0' for iterator of type %1">; + def note_for_range_begin_end : Note< + "selected '%select{begin|end}0' %select{function|template }1%2 with iterator type %3">; + def warn_for_range_const_ref_binds_temp_built_from_ref : Warning< + "loop variable %0 " + "%diff{of type $ binds to a temporary constructed from type $" + "|binds to a temporary constructed from a different type}1,2">, + InGroup, DefaultIgnore; + def note_use_type_or_non_reference : Note< + "use non-reference type %0 to make construction explicit or type %1 to prevent copying">; + def warn_for_range_ref_binds_ret_temp : Warning< + "loop variable %0 binds to a temporary value produced by a range of type %1">, + InGroup, DefaultIgnore; + def note_use_non_reference_type : Note<"use non-reference type %0">; + def warn_for_range_copy : Warning< + "loop variable %0 creates a copy from type %1">, + InGroup, DefaultIgnore; + def note_use_reference_type : Note<"use reference type %0 to prevent copying">; + def err_objc_for_range_init_stmt : Error< + "initialization statement is not supported when iterating over Objective-C " + "collection">; + + // C++11 constexpr + def warn_cxx98_compat_constexpr : Warning< + "'constexpr' specifier is incompatible with C++98">, + InGroup, DefaultIgnore; + // FIXME: Maybe this should also go in -Wc++14-compat? + def warn_cxx14_compat_constexpr_not_const : Warning< + "'constexpr' non-static member function will not be implicitly 'const' " + "in C++14; add 'const' to avoid a change in behavior">, + InGroup>; + def err_invalid_consteval_take_address : Error< + "cannot take address of consteval function %0 outside" + " of an immediate invocation">; + def err_invalid_consteval_call : Error< + "call to consteval function %q0 is not a constant expression">; + def err_invalid_consteval_decl_kind : Error< + "%0 cannot be declared consteval">; + def err_invalid_constexpr : Error< + "%select{function parameter|typedef}0 " + "cannot be %sub{select_constexpr_spec_kind}1">; + def err_invalid_constexpr_member : Error<"non-static data member cannot be " + "constexpr%select{; did you intend to make it %select{const|static}0?|}1">; + def err_constexpr_tag : Error< + "%select{class|struct|interface|union|enum}0 " + "cannot be marked %sub{select_constexpr_spec_kind}1">; + def err_constexpr_dtor : Error< + "destructor cannot be declared %sub{select_constexpr_spec_kind}0">; + def err_constexpr_dtor_subobject : Error< + "destructor cannot be declared %sub{select_constexpr_spec_kind}0 because " + "%select{data member %2|base class %3}1 does not have a " + "constexpr destructor">; + def note_constexpr_dtor_subobject : Note< + "%select{data member %1|base class %2}0 declared here">; + def err_constexpr_wrong_decl_kind : Error< + "%sub{select_constexpr_spec_kind}0 can only be used " + "in %select{|variable and function|function|variable}0 declarations">; + def err_invalid_constexpr_var_decl : Error< + "constexpr variable declaration must be a definition">; + def err_constexpr_static_mem_var_requires_init : Error< + "declaration of constexpr static data member %0 requires an initializer">; + def err_constexpr_var_non_literal : Error< + "constexpr variable cannot have non-literal type %0">; + def err_constexpr_var_requires_const_init : Error< + "constexpr variable %0 must be initialized by a constant expression">; + def err_constexpr_var_requires_const_destruction : Error< + "constexpr variable %0 must have constant destruction">; + def err_constexpr_redecl_mismatch : Error< + "%select{non-constexpr|constexpr|consteval}1 declaration of %0" + " follows %select{non-constexpr|constexpr|consteval}2 declaration">; + def err_constexpr_virtual : Error<"virtual function cannot be constexpr">; + def warn_cxx17_compat_constexpr_virtual : Warning< + "virtual constexpr functions are incompatible with " + "C++ standards before C++20">, InGroup, DefaultIgnore; + def err_constexpr_virtual_base : Error< + "constexpr %select{member function|constructor}0 not allowed in " + "%select{struct|interface|class}1 with virtual base " + "%plural{1:class|:classes}2">; + def note_non_literal_incomplete : Note< + "incomplete type %0 is not a literal type">; + def note_non_literal_virtual_base : Note<"%select{struct|interface|class}0 " + "with virtual base %plural{1:class|:classes}1 is not a literal type">; + def note_constexpr_virtual_base_here : Note<"virtual base class declared here">; + def err_constexpr_non_literal_return : Error< + "%select{constexpr|consteval}0 function's return type %1 is not a literal type">; + def err_constexpr_non_literal_param : Error< + "%select{constexpr|consteval}2 %select{function|constructor}1's %ordinal0 parameter type %3 is " + "not a literal type">; + def err_constexpr_body_invalid_stmt : Error< + "statement not allowed in %select{constexpr|consteval}1 %select{function|constructor}0">; + def ext_constexpr_body_invalid_stmt : ExtWarn< + "use of this statement in a constexpr %select{function|constructor}0 " + "is a C++14 extension">, InGroup; + def warn_cxx11_compat_constexpr_body_invalid_stmt : Warning< + "use of this statement in a constexpr %select{function|constructor}0 " + "is incompatible with C++ standards before C++14">, + InGroup, DefaultIgnore; + def ext_constexpr_body_invalid_stmt_cxx20 : ExtWarn< + "use of this statement in a constexpr %select{function|constructor}0 " + "is a C++20 extension">, InGroup; + def warn_cxx17_compat_constexpr_body_invalid_stmt : Warning< + "use of this statement in a constexpr %select{function|constructor}0 " + "is incompatible with C++ standards before C++20">, + InGroup, DefaultIgnore; + def ext_constexpr_type_definition : ExtWarn< + "type definition in a constexpr %select{function|constructor}0 " + "is a C++14 extension">, InGroup; + def warn_cxx11_compat_constexpr_type_definition : Warning< + "type definition in a constexpr %select{function|constructor}0 " + "is incompatible with C++ standards before C++14">, + InGroup, DefaultIgnore; + def err_constexpr_vla : Error< + "variably-modified type %0 cannot be used in a constexpr " + "%select{function|constructor}1">; + def ext_constexpr_local_var : ExtWarn< + "variable declaration in a constexpr %select{function|constructor}0 " + "is a C++14 extension">, InGroup; + def warn_cxx11_compat_constexpr_local_var : Warning< + "variable declaration in a constexpr %select{function|constructor}0 " + "is incompatible with C++ standards before C++14">, + InGroup, DefaultIgnore; + def err_constexpr_local_var_static : Error< + "%select{static|thread_local}1 variable not permitted in a constexpr " + "%select{function|constructor}0">; + def err_constexpr_local_var_non_literal_type : Error< + "variable of non-literal type %1 cannot be defined in a constexpr " + "%select{function|constructor}0">; + def ext_constexpr_local_var_no_init : ExtWarn< + "uninitialized variable in a constexpr %select{function|constructor}0 " + "is a C++20 extension">, InGroup; + def warn_cxx17_compat_constexpr_local_var_no_init : Warning< + "uninitialized variable in a constexpr %select{function|constructor}0 " + "is incompatible with C++ standards before C++20">, + InGroup, DefaultIgnore; + def ext_constexpr_function_never_constant_expr : ExtWarn< + "%select{constexpr|consteval}1 %select{function|constructor}0 never produces a " + "constant expression">, InGroup>, DefaultError; + def err_attr_cond_never_constant_expr : Error< + "%0 attribute expression never produces a constant expression">; + def err_diagnose_if_invalid_diagnostic_type : Error< + "invalid diagnostic type for 'diagnose_if'; use \"error\" or \"warning\" " + "instead">; + def err_constexpr_body_no_return : Error< + "no return statement in %select{constexpr|consteval}0 function">; + def err_constexpr_return_missing_expr : Error< + "non-void %select{constexpr|consteval}1 function %0 should return a value">; + def warn_cxx11_compat_constexpr_body_no_return : Warning< + "constexpr function with no return statements is incompatible with C++ " + "standards before C++14">, InGroup, DefaultIgnore; + def ext_constexpr_body_multiple_return : ExtWarn< + "multiple return statements in constexpr function is a C++14 extension">, + InGroup; + def warn_cxx11_compat_constexpr_body_multiple_return : Warning< + "multiple return statements in constexpr function " + "is incompatible with C++ standards before C++14">, + InGroup, DefaultIgnore; + def note_constexpr_body_previous_return : Note< + "previous return statement is here">; + + // C++20 function try blocks in constexpr + def ext_constexpr_function_try_block_cxx20 : ExtWarn< + "function try block in constexpr %select{function|constructor}0 is " + "a C++20 extension">, InGroup; + def warn_cxx17_compat_constexpr_function_try_block : Warning< + "function try block in constexpr %select{function|constructor}0 is " + "incompatible with C++ standards before C++20">, + InGroup, DefaultIgnore; + + def ext_constexpr_union_ctor_no_init : ExtWarn< + "constexpr union constructor that does not initialize any member " + "is a C++20 extension">, InGroup; + def warn_cxx17_compat_constexpr_union_ctor_no_init : Warning< + "constexpr union constructor that does not initialize any member " + "is incompatible with C++ standards before C++20">, + InGroup, DefaultIgnore; + def ext_constexpr_ctor_missing_init : ExtWarn< + "constexpr constructor that does not initialize all members " + "is a C++20 extension">, InGroup; + def warn_cxx17_compat_constexpr_ctor_missing_init : Warning< + "constexpr constructor that does not initialize all members " + "is incompatible with C++ standards before C++20">, + InGroup, DefaultIgnore; + def note_constexpr_ctor_missing_init : Note< + "member not initialized by constructor">; + def note_non_literal_no_constexpr_ctors : Note< + "%0 is not literal because it is not an aggregate and has no constexpr " + "constructors other than copy or move constructors">; + def note_non_literal_base_class : Note< + "%0 is not literal because it has base class %1 of non-literal type">; + def note_non_literal_field : Note< + "%0 is not literal because it has data member %1 of " + "%select{non-literal|volatile}3 type %2">; + def note_non_literal_user_provided_dtor : Note< + "%0 is not literal because it has a user-provided destructor">; + def note_non_literal_nontrivial_dtor : Note< + "%0 is not literal because it has a non-trivial destructor">; + def note_non_literal_non_constexpr_dtor : Note< + "%0 is not literal because its destructor is not constexpr">; + def note_non_literal_lambda : Note< + "lambda closure types are non-literal types before C++17">; + def warn_private_extern : Warning< + "use of __private_extern__ on a declaration may not produce external symbol " + "private to the linkage unit and is deprecated">, InGroup; + def note_private_extern : Note< + "use __attribute__((visibility(\"hidden\"))) attribute instead">; + + // C++ Concepts + def err_concept_decls_may_only_appear_in_global_namespace_scope : Error< + "concept declarations may only appear in global or namespace scope">; + def err_concept_no_parameters : Error< + "concept template parameter list must have at least one parameter; explicit " + "specialization of concepts is not allowed">; + def err_concept_extra_headers : Error< + "extraneous template parameter list in concept definition">; + def err_concept_no_associated_constraints : Error< + "concept cannot have associated constraints">; + def err_non_constant_constraint_expression : Error< + "substitution into constraint expression resulted in a non-constant " + "expression">; + def err_non_bool_atomic_constraint : Error< + "atomic constraint must be of type 'bool' (found %0)">; + def err_template_arg_list_constraints_not_satisfied : Error< + "constraints not satisfied for %select{class template|function template|variable template|alias template|" + "template template parameter|template}0 %1%2">; + def note_substituted_constraint_expr_is_ill_formed : Note< + "because substituted constraint expression is ill-formed%0">; + def note_atomic_constraint_evaluated_to_false : Note< + "%select{and|because}0 '%1' evaluated to false">; + def note_concept_specialization_constraint_evaluated_to_false : Note< + "%select{and|because}0 '%1' evaluated to false">; + def note_single_arg_concept_specialization_constraint_evaluated_to_false : Note< + "%select{and|because}0 %1 does not satisfy %2">; + def note_atomic_constraint_evaluated_to_false_elaborated : Note< + "%select{and|because}0 '%1' (%2 %3 %4) evaluated to false">; + def err_constrained_virtual_method : Error< + "virtual function cannot have a requires clause">; + def err_trailing_requires_clause_on_deduction_guide : Error< + "deduction guide cannot have a requires clause">; + def err_reference_to_function_with_unsatisfied_constraints : Error< + "invalid reference to function %0: constraints not satisfied">; + def err_requires_expr_local_parameter_default_argument : Error< + "default arguments not allowed for parameters of a requires expression">; + def err_requires_expr_parameter_referenced_in_evaluated_context : Error< + "constraint variable %0 cannot be used in an evaluated context">; + def note_expr_requirement_expr_substitution_error : Note< + "%select{and|because}0 '%1' would be invalid: %2">; + def note_expr_requirement_expr_unknown_substitution_error : Note< + "%select{and|because}0 '%1' would be invalid">; + def note_expr_requirement_noexcept_not_met : Note< + "%select{and|because}0 '%1' may throw an exception">; + def note_expr_requirement_type_requirement_substitution_error : Note< + "%select{and|because}0 '%1' would be invalid: %2">; + def note_expr_requirement_type_requirement_unknown_substitution_error : Note< + "%select{and|because}0 '%1' would be invalid">; + def note_expr_requirement_constraints_not_satisfied : Note< + "%select{and|because}0 type constraint '%1' was not satisfied:">; + def note_expr_requirement_constraints_not_satisfied_simple : Note< + "%select{and|because}0 %1 does not satisfy %2:">; + def note_type_requirement_substitution_error : Note< + "%select{and|because}0 '%1' would be invalid: %2">; + def note_type_requirement_unknown_substitution_error : Note< + "%select{and|because}0 '%1' would be invalid">; + def note_nested_requirement_substitution_error : Note< + "%select{and|because}0 '%1' would be invalid: %2">; + def note_nested_requirement_unknown_substitution_error : Note< + "%select{and|because}0 '%1' would be invalid">; + def note_ambiguous_atomic_constraints : Note< + "similar constraint expressions not considered equivalent; constraint " + "expressions cannot be considered equivalent unless they originate from the " + "same concept">; + def note_ambiguous_atomic_constraints_similar_expression : Note< + "similar constraint expression here">; + def err_unsupported_placeholder_constraint : Error< + "constrained placeholder types other than simple 'auto' on non-type template " + "parameters not supported yet">; + + def err_template_different_requires_clause : Error< + "requires clause differs in template redeclaration">; + def err_template_different_type_constraint : Error< + "type constraint differs in template redeclaration">; + def err_template_template_parameter_not_at_least_as_constrained : Error< + "template template argument %0 is more constrained than template template " + "parameter %1">; + + def err_type_constraint_non_type_concept : Error< + "concept named in type constraint is not a type concept">; + def err_type_constraint_missing_arguments : Error< + "%0 requires more than 1 template argument; provide the remaining arguments " + "explicitly to use it here">; + def err_placeholder_constraints_not_satisfied : Error< + "deduced type %0 does not satisfy %1">; + + // C++11 char16_t/char32_t + def warn_cxx98_compat_unicode_type : Warning< + "'%0' type specifier is incompatible with C++98">, + InGroup, DefaultIgnore; + def warn_cxx17_compat_unicode_type : Warning< + "'char8_t' type specifier is incompatible with C++ standards before C++20">, + InGroup, DefaultIgnore; + + // __make_integer_seq + def err_integer_sequence_negative_length : Error< + "integer sequences must have non-negative sequence length">; + def err_integer_sequence_integral_element_type : Error< + "integer sequences must have integral element type">; + + // __type_pack_element + def err_type_pack_element_out_of_bounds : Error< + "a parameter pack may not be accessed at an out of bounds index">; + + // Objective-C++ + def err_objc_decls_may_only_appear_in_global_scope : Error< + "Objective-C declarations may only appear in global scope">; + def warn_auto_var_is_id : Warning< + "'auto' deduced as 'id' in declaration of %0">, + InGroup>; + + // Attributes + def warn_nomerge_attribute_ignored_in_stmt: Warning< + "%0 attribute is ignored because there exists no call expression inside the " + "statement">, + InGroup; + + def err_musttail_needs_trivial_args : Error< + "tail call requires that the return value, all parameters, and any " + "temporaries created by the expression are trivially destructible">; + def err_musttail_needs_call : Error< + "%0 attribute requires that the return value is the result of a function call" + >; + def err_musttail_needs_prototype : Error< + "%0 attribute requires that both caller and callee functions have a " + "prototype">; + def note_musttail_fix_non_prototype : Note< + "add 'void' to the parameter list to turn an old-style K&R function " + "declaration into a prototype">; + def err_musttail_structors_forbidden : Error<"cannot perform a tail call " + "%select{from|to}0 a %select{constructor|destructor}1">; + def note_musttail_structors_forbidden : Note<"target " + "%select{constructor|destructor}0 is declared here">; + def err_musttail_forbidden_from_this_context : Error< + "%0 attribute cannot be used from " + "%select{a block|an Objective-C function|this context}1">; + def err_musttail_member_mismatch : Error< + "%select{non-member|static member|non-static member}0 " + "function cannot perform a tail call to " + "%select{non-member|static member|non-static member|pointer-to-member}1 " + "function%select{| %3}2">; + def note_musttail_callee_defined_here : Note<"%0 declared here">; + def note_tail_call_required : Note<"tail call required by %0 attribute here">; + def err_musttail_mismatch : Error< + "cannot perform a tail call to function%select{| %1}0 because its signature " + "is incompatible with the calling function">; + def note_musttail_mismatch : Note< + "target function " + "%select{is a member of different class%diff{ (expected $ but has $)|}1,2" + "|has different number of parameters (expected %1 but has %2)" + "|has type mismatch at %ordinal3 parameter" + "%diff{ (expected $ but has $)|}1,2" + "|has different return type%diff{ ($ expected but has $)|}1,2}0">; + def err_musttail_callconv_mismatch : Error< + "cannot perform a tail call to function%select{| %1}0 because it uses an " + "incompatible calling convention">; + def note_musttail_callconv_mismatch : Note< + "target function has calling convention %1 (expected %0)">; + def err_musttail_scope : Error< + "cannot perform a tail call from this return statement">; + def err_musttail_no_variadic : Error< + "%0 attribute may not be used with variadic functions">; + + def err_nsobject_attribute : Error< + "'NSObject' attribute is for pointer types only">; + def err_attributes_are_not_compatible : Error< + "%0 and %1 attributes are not compatible">; + def err_attribute_invalid_argument : Error< + "%select{a reference type|an array type|a non-vector or " + "non-vectorizable scalar type}0 is an invalid argument to attribute %1">; + def err_attribute_wrong_number_arguments : Error< + "%0 attribute %plural{0:takes no arguments|1:takes one argument|" + ":requires exactly %1 arguments}1">; + def err_attribute_too_many_arguments : Error< + "%0 attribute takes no more than %1 argument%s1">; + def err_attribute_too_few_arguments : Error< + "%0 attribute takes at least %1 argument%s1">; + def err_attribute_invalid_vector_type : Error<"invalid vector element type %0">; + def err_attribute_invalid_matrix_type : Error<"invalid matrix element type %0">; + def err_attribute_bad_neon_vector_size : Error< + "Neon vector size must be 64 or 128 bits">; + def err_attribute_invalid_sve_type : Error< + "%0 attribute applied to non-SVE type %1">; + def err_attribute_bad_sve_vector_size : Error< + "invalid SVE vector size '%0', must match value set by " + "'-msve-vector-bits' ('%1')">; + def err_attribute_arm_feature_sve_bits_unsupported : Error< + "%0 is only supported when '-msve-vector-bits=' is specified with a " + "value of 128, 256, 512, 1024 or 2048.">; + def err_attribute_requires_positive_integer : Error< + "%0 attribute requires a %select{positive|non-negative}1 " + "integral compile time constant expression">; + def err_attribute_requires_opencl_version : Error< + "attribute %0 is supported in the OpenCL version %1%select{| onwards}2">; + def err_invalid_branch_protection_spec : Error< + "invalid or misplaced branch protection specification '%0'">; + def warn_unsupported_target_attribute + : Warning<"%select{unsupported|duplicate|unknown}0%select{| architecture|" + " tune CPU}1 '%2' in the 'target' attribute string; 'target' " + "attribute ignored">, + InGroup; + def err_attribute_unsupported + : Error<"%0 attribute is not supported on targets missing %1;" + " specify an appropriate -march= or -mcpu=">; + // The err_*_attribute_argument_not_int are separate because they're used by + // VerifyIntegerConstantExpression. + def err_aligned_attribute_argument_not_int : Error< + "'aligned' attribute requires integer constant">; + def err_align_value_attribute_argument_not_int : Error< + "'align_value' attribute requires integer constant">; + def err_alignas_attribute_wrong_decl_type : Error< + "%0 attribute cannot be applied to a %select{function parameter|" + "variable with 'register' storage class|'catch' variable|bit-field}1">; + def err_alignas_missing_on_definition : Error< + "%0 must be specified on definition if it is specified on any declaration">; + def note_alignas_on_declaration : Note<"declared with %0 attribute here">; + def err_alignas_mismatch : Error< + "redeclaration has different alignment requirement (%1 vs %0)">; + def err_alignas_underaligned : Error< + "requested alignment is less than minimum alignment of %1 for type %0">; + def warn_aligned_attr_underaligned : Warning, + InGroup; + def err_attribute_sizeless_type : Error< + "%0 attribute cannot be applied to sizeless type %1">; + def err_attribute_argument_n_type : Error< + "%0 attribute requires parameter %1 to be %select{int or bool|an integer " + "constant|a string|an identifier|a constant expression}2">; + def err_attribute_argument_type : Error< + "%0 attribute requires %select{int or bool|an integer " + "constant|a string|an identifier}1">; + def err_attribute_argument_out_of_range : Error< + "%0 attribute requires integer constant between %1 and %2 inclusive">; + def err_init_priority_object_attr : Error< + "can only use 'init_priority' attribute on file-scope definitions " + "of objects of class type">; + def err_attribute_argument_out_of_bounds : Error< + "%0 attribute parameter %1 is out of bounds">; + def err_attribute_only_once_per_parameter : Error< + "%0 attribute can only be applied once per parameter">; + def err_mismatched_uuid : Error<"uuid does not match previous declaration">; + def note_previous_uuid : Note<"previous uuid specified here">; + def warn_attribute_pointers_only : Warning< + "%0 attribute only applies to%select{| constant}1 pointer arguments">, + InGroup; + def err_attribute_pointers_only : Error; + def err_attribute_integers_only : Error< + "%0 attribute argument may only refer to a function parameter of integer " + "type">; + def warn_attribute_return_pointers_only : Warning< + "%0 attribute only applies to return values that are pointers">, + InGroup; + def warn_attribute_return_pointers_refs_only : Warning< + "%0 attribute only applies to return values that are pointers or references">, + InGroup; + def warn_attribute_pointer_or_reference_only : Warning< + "%0 attribute only applies to a pointer or reference (%1 is invalid)">, + InGroup; + def err_attribute_no_member_pointers : Error< + "%0 attribute cannot be used with pointers to members">; + def err_attribute_invalid_implicit_this_argument : Error< + "%0 attribute is invalid for the implicit this argument">; + def err_ownership_type : Error< + "%0 attribute only applies to %select{pointer|integer}1 arguments">; + def err_ownership_returns_index_mismatch : Error< + "'ownership_returns' attribute index does not match; here it is %0">; + def note_ownership_returns_index_mismatch : Note< + "declared with index %0 here">; + def err_format_strftime_third_parameter : Error< + "strftime format attribute requires 3rd parameter to be 0">; + def err_format_attribute_requires_variadic : Error< + "format attribute requires variadic function">; + def err_format_attribute_not : Error<"format argument not %0">; + def err_format_attribute_result_not : Error<"function does not return %0">; + def err_format_attribute_implicit_this_format_string : Error< + "format attribute cannot specify the implicit this argument as the format " + "string">; + def err_callback_attribute_no_callee : Error< + "'callback' attribute specifies no callback callee">; + def err_callback_attribute_invalid_callee : Error< + "'callback' attribute specifies invalid callback callee">; + def err_callback_attribute_multiple : Error< + "multiple 'callback' attributes specified">; + def err_callback_attribute_argument_unknown : Error< + "'callback' attribute argument %0 is not a known function parameter">; + def err_callback_callee_no_function_type : Error< + "'callback' attribute callee does not have function type">; + def err_callback_callee_is_variadic : Error< + "'callback' attribute callee may not be variadic">; + def err_callback_implicit_this_not_available : Error< + "'callback' argument at position %0 references unavailable implicit 'this'">; + def err_init_method_bad_return_type : Error< + "init methods must return an object pointer type, not %0">; + def err_attribute_invalid_size : Error< + "vector size not an integral multiple of component size">; + def err_attribute_zero_size : Error<"zero %0 size">; + def err_attribute_size_too_large : Error<"%0 size too large">; + def err_typecheck_sve_ambiguous : Error< + "cannot combine fixed-length and sizeless SVE vectors in expression, result is ambiguous (%0 and %1)">; + def err_typecheck_sve_gnu_ambiguous : Error< + "cannot combine GNU and SVE vectors in expression, result is ambiguous (%0 and %1)">; + def err_typecheck_vector_not_convertable_implict_truncation : Error< + "cannot convert between %select{scalar|vector}0 type %1 and vector type" + " %2 as implicit conversion would cause truncation">; + def err_typecheck_vector_not_convertable : Error< + "cannot convert between vector values of different size (%0 and %1)">; + def err_typecheck_vector_not_convertable_non_scalar : Error< + "cannot convert between vector and non-scalar values (%0 and %1)">; + def err_typecheck_vector_lengths_not_equal : Error< + "vector operands do not have the same number of elements (%0 and %1)">; + def warn_typecheck_vector_element_sizes_not_equal : Warning< + "vector operands do not have the same elements sizes (%0 and %1)">, + InGroup>, DefaultError; + def err_ext_vector_component_exceeds_length : Error< + "vector component access exceeds type %0">; + def err_ext_vector_component_name_illegal : Error< + "illegal vector component name '%0'">; + def err_attribute_address_space_negative : Error< + "address space is negative">; + def err_attribute_address_space_too_high : Error< + "address space is larger than the maximum supported (%0)">; + def err_attribute_address_multiple_qualifiers : Error< + "multiple address spaces specified for type">; + def warn_attribute_address_multiple_identical_qualifiers : Warning< + "multiple identical address spaces specified for type">, + InGroup; + def err_attribute_not_clinkage : Error< + "function type with %0 attribute must have C linkage">; + def err_function_decl_cmse_ns_call : Error< + "functions may not be declared with 'cmse_nonsecure_call' attribute">; + def err_attribute_address_function_type : Error< + "function type may not be qualified with an address space">; + def err_as_qualified_auto_decl : Error< + "automatic variable qualified with an%select{| invalid}0 address space">; + def err_arg_with_address_space : Error< + "parameter may not be qualified with an address space">; + def err_field_with_address_space : Error< + "field may not be qualified with an address space">; + def err_compound_literal_with_address_space : Error< + "compound literal in function scope may not be qualified with an address space">; + def err_address_space_mismatch_templ_inst : Error< + "conflicting address space qualifiers are provided between types %0 and %1">; + def err_attr_objc_ownership_redundant : Error< + "the type %0 is already explicitly ownership-qualified">; + def err_invalid_nsnumber_type : Error< + "%0 is not a valid literal type for NSNumber">; + def err_objc_illegal_boxed_expression_type : Error< + "illegal type %0 used in a boxed expression">; + def err_objc_non_trivially_copyable_boxed_expression_type : Error< + "non-trivially copyable type %0 cannot be used in a boxed expression">; + def err_objc_incomplete_boxed_expression_type : Error< + "incomplete type %0 used in a boxed expression">; + def err_undeclared_objc_literal_class : Error< + "definition of class %0 must be available to use Objective-C " + "%select{array literals|dictionary literals|numeric literals|boxed expressions|" + "string literals}1">; + def err_undeclared_boxing_method : Error< + "declaration of %0 is missing in %1 class">; + def err_objc_literal_method_sig : Error< + "literal construction method %0 has incompatible signature">; + def note_objc_literal_method_param : Note< + "%select{first|second|third}0 parameter has unexpected type %1 " + "(should be %2)">; + def note_objc_literal_method_return : Note< + "method returns unexpected type %0 (should be an object type)">; + def err_invalid_collection_element : Error< + "collection element of type %0 is not an Objective-C object">; + def err_box_literal_collection : Error< + "%select{string|character|boolean|numeric}0 literal must be prefixed by '@' " + "in a collection">; + def warn_objc_literal_comparison : Warning< + "direct comparison of %select{an array literal|a dictionary literal|" + "a numeric literal|a boxed expression|}0 has undefined behavior">, + InGroup; + def err_missing_atsign_prefix : Error< + "%select{string|numeric}0 literal must be prefixed by '@'">; + def warn_objc_string_literal_comparison : Warning< + "direct comparison of a string literal has undefined behavior">, + InGroup; + def warn_concatenated_literal_array_init : Warning< + "suspicious concatenation of string literals in an array initialization; " + "did you mean to separate the elements with a comma?">, + InGroup, DefaultIgnore; + def warn_concatenated_nsarray_literal : Warning< + "concatenated NSString literal for an NSArray expression - " + "possibly missing a comma">, + InGroup; + def note_objc_literal_comparison_isequal : Note< + "use 'isEqual:' instead">; + def warn_objc_collection_literal_element : Warning< + "object of type %0 is not compatible with " + "%select{array element type|dictionary key type|dictionary value type}1 %2">, + InGroup; + def warn_nsdictionary_duplicate_key : Warning< + "duplicate key in dictionary literal">, + InGroup>; + def note_nsdictionary_duplicate_key_here : Note< + "previous equal key is here">; + def err_swift_param_attr_not_swiftcall : Error< + "'%0' parameter can only be used with swiftcall%select{ or swiftasynccall|}1 " + "calling convention%select{|s}1">; + def err_swift_indirect_result_not_first : Error< + "'swift_indirect_result' parameters must be first parameters of function">; + def err_swift_error_result_not_after_swift_context : Error< + "'swift_error_result' parameter must follow 'swift_context' parameter">; + def err_swift_abi_parameter_wrong_type : Error< + "'%0' parameter must have pointer%select{| to unqualified pointer}1 type; " + "type here is %2">; + + def err_attribute_argument_invalid : Error< + "%0 attribute argument is invalid: %select{max must be 0 since min is 0|" + "min must not be greater than max}1">; + def err_attribute_argument_is_zero : Error< + "%0 attribute must be greater than 0">; + def warn_attribute_argument_n_negative : Warning< + "%0 attribute parameter %1 is negative and will be ignored">, + InGroup; + def err_property_function_in_objc_container : Error< + "use of Objective-C property in function nested in Objective-C " + "container not supported, move function outside its container">; + + let CategoryName = "Cocoa API Issue" in { + def warn_objc_redundant_literal_use : Warning< + "using %0 with a literal is redundant">, InGroup; + } + + def err_attr_tlsmodel_arg : Error<"tls_model must be \"global-dynamic\", " + "\"local-dynamic\", \"initial-exec\" or \"local-exec\"">; + + def err_aix_attr_unsupported_tls_model : Error<"TLS model '%0' is not yet supported on AIX">; + + def err_tls_var_aligned_over_maximum : Error< + "alignment (%0) of thread-local variable %1 is greater than the maximum supported " + "alignment (%2) for a thread-local variable on this target">; + + def err_only_annotate_after_access_spec : Error< + "access specifier can only have annotation attributes">; + + def err_attribute_section_invalid_for_target : Error< + "argument to %select{'code_seg'|'section'}1 attribute is not valid for this target: %0">; + def err_pragma_section_invalid_for_target : Error< + "argument to #pragma section is not valid for this target: %0">; + def warn_attribute_section_drectve : Warning< + "#pragma %0(\".drectve\") has undefined behavior, " + "use #pragma comment(linker, ...) instead">, InGroup; + def warn_mismatched_section : Warning< + "%select{codeseg|section}0 does not match previous declaration">, InGroup
; + def warn_attribute_section_on_redeclaration : Warning< + "section attribute is specified on redeclared variable">, InGroup
; + def err_mismatched_code_seg_base : Error< + "derived class must specify the same code segment as its base classes">; + def err_mismatched_code_seg_override : Error< + "overriding virtual function must specify the same code segment as its overridden function">; + def err_conflicting_codeseg_attribute : Error< + "conflicting code segment specifiers">; + def warn_duplicate_codeseg_attribute : Warning< + "duplicate code segment specifiers">, InGroup
; + + def err_anonymous_property: Error< + "anonymous property is not supported">; + def err_property_is_variably_modified : Error< + "property %0 has a variably modified type">; + def err_no_accessor_for_property : Error< + "no %select{getter|setter}0 defined for property %1">; + def err_cannot_find_suitable_accessor : Error< + "cannot find suitable %select{getter|setter}0 for property %1">; + + def warn_alloca : Warning< + "use of function %0 is discouraged; there is no way to check for failure but " + "failure may still occur, resulting in a possibly exploitable security vulnerability">, + InGroup>, DefaultIgnore; + + def warn_alloca_align_alignof : Warning< + "second argument to __builtin_alloca_with_align is supposed to be in bits">, + InGroup>; + + def err_alignment_too_small : Error< + "requested alignment must be %0 or greater">; + def err_alignment_too_big : Error< + "requested alignment must be %0 or smaller">; + def err_alignment_not_power_of_two : Error< + "requested alignment is not a power of 2">; + def warn_alignment_not_power_of_two : Warning< + err_alignment_not_power_of_two.Text>, + InGroup>; + def err_alignment_dependent_typedef_name : Error< + "requested alignment is dependent but declaration is not dependent">; + + def warn_alignment_builtin_useless : Warning< + "%select{aligning a value|the result of checking whether a value is aligned}0" + " to 1 byte is %select{a no-op|always true}0">, InGroup; + def err_attribute_aligned_too_great : Error< + "requested alignment must be %0 bytes or smaller">; + def warn_assume_aligned_too_great + : Warning<"requested alignment must be %0 bytes or smaller; maximum " + "alignment assumed">, + InGroup>; + def warn_not_xl_compatible + : Warning<"requesting an alignment of 16 bytes or greater for struct" + " members is not binary compatible with AIX XL 16.1 and older">, + InGroup; + def warn_redeclaration_without_attribute_prev_attribute_ignored : Warning< + "%q0 redeclared without %1 attribute: previous %1 ignored">, + InGroup; + def warn_redeclaration_without_import_attribute : Warning< + "%q0 redeclared without 'dllimport' attribute: 'dllexport' attribute added">, + InGroup; + def warn_dllimport_dropped_from_inline_function : Warning< + "%q0 redeclared inline; %1 attribute ignored">, + InGroup; + def warn_attribute_ignored : Warning<"%0 attribute ignored">, + InGroup; + def warn_nothrow_attribute_ignored : Warning<"'nothrow' attribute conflicts with" + " exception specification; attribute ignored">, + InGroup; + def warn_attribute_ignored_on_non_definition : + Warning<"%0 attribute ignored on a non-definition declaration">, + InGroup; + def warn_attribute_ignored_on_inline : + Warning<"%0 attribute ignored on inline function">, + InGroup; + def warn_nocf_check_attribute_ignored : + Warning<"'nocf_check' attribute ignored; use -fcf-protection to enable the attribute">, + InGroup; + def warn_attribute_after_definition_ignored : Warning< + "attribute %0 after definition is ignored">, + InGroup; + def warn_attributes_likelihood_ifstmt_conflict + : Warning<"conflicting attributes %0 are ignored">, + InGroup; + def warn_cxx11_gnu_attribute_on_type : Warning< + "attribute %0 ignored, because it cannot be applied to a type">, + InGroup; + def warn_unhandled_ms_attribute_ignored : Warning< + "__declspec attribute %0 is not supported">, + InGroup; + def warn_attribute_has_no_effect_on_infinite_loop : Warning< + "attribute %0 has no effect when annotating an infinite loop">, + InGroup; + def note_attribute_has_no_effect_on_infinite_loop_here : Note< + "annotating the infinite loop here">; + def warn_attribute_has_no_effect_on_if_constexpr : Warning< + "attribute %0 has no effect when annotating an 'if constexpr' statement">, + InGroup; + def note_attribute_has_no_effect_on_if_constexpr_here : Note< + "annotating the 'if constexpr' statement here">; + def err_decl_attribute_invalid_on_stmt : Error< + "%0 attribute cannot be applied to a statement">; + def err_stmt_attribute_invalid_on_decl : Error< + "%0 attribute cannot be applied to a declaration">; + def warn_declspec_attribute_ignored : Warning< + "attribute %0 is ignored, place it after " + "\"%select{class|struct|interface|union|enum}1\" to apply attribute to " + "type declaration">, InGroup; + def warn_attribute_precede_definition : Warning< + "attribute declaration must precede definition">, + InGroup; + def warn_attribute_void_function_method : Warning< + "attribute %0 cannot be applied to " + "%select{functions|Objective-C method}1 without return value">, + InGroup; + def warn_attribute_weak_on_field : Warning< + "__weak attribute cannot be specified on a field declaration">, + InGroup; + def warn_gc_attribute_weak_on_local : Warning< + "Objective-C GC does not allow weak variables on the stack">, + InGroup; + def warn_nsobject_attribute : Warning< + "'NSObject' attribute may be put on a typedef only; attribute is ignored">, + InGroup; + def warn_independentclass_attribute : Warning< + "'objc_independent_class' attribute may be put on a typedef only; " + "attribute is ignored">, + InGroup; + def warn_ptr_independentclass_attribute : Warning< + "'objc_independent_class' attribute may be put on Objective-C object " + "pointer type only; attribute is ignored">, + InGroup; + def warn_attribute_weak_on_local : Warning< + "__weak attribute cannot be specified on an automatic variable when ARC " + "is not enabled">, + InGroup; + def warn_weak_identifier_undeclared : Warning< + "weak identifier %0 never declared">; + def warn_attribute_cmse_entry_static : Warning< + "'cmse_nonsecure_entry' cannot be applied to functions with internal linkage">, + InGroup; + def warn_cmse_nonsecure_union : Warning< + "passing union across security boundary via %select{parameter %1|return value}0 " + "may leak information">, + InGroup>; + def err_attribute_weak_static : Error< + "weak declaration cannot have internal linkage">; + def err_attribute_selectany_non_extern_data : Error< + "'selectany' can only be applied to data items with external linkage">; + def err_declspec_thread_on_thread_variable : Error< + "'__declspec(thread)' applied to variable that already has a " + "thread-local storage specifier">; + def err_attribute_dll_not_extern : Error< + "%q0 must have external linkage when declared %q1">; + def err_attribute_dll_thread_local : Error< + "%q0 cannot be thread local when declared %q1">; + def err_attribute_dll_lambda : Error< + "lambda cannot be declared %0">; + def warn_attribute_invalid_on_definition : Warning< + "'%0' attribute cannot be specified on a definition">, + InGroup; + def err_attribute_dll_redeclaration : Error< + "redeclaration of %q0 cannot add %q1 attribute">; + def warn_attribute_dll_redeclaration : Warning< + "redeclaration of %q0 should not add %q1 attribute">, + InGroup>; + def err_attribute_dllimport_function_definition : Error< + "dllimport cannot be applied to non-inline function definition">; + def err_attribute_dll_deleted : Error< + "attribute %q0 cannot be applied to a deleted function">; + def err_attribute_dllimport_data_definition : Error< + "definition of dllimport data">; + def err_attribute_dllimport_static_field_definition : Error< + "definition of dllimport static field not allowed">; + def warn_attribute_dllimport_static_field_definition : Warning< + "definition of dllimport static field">, + InGroup>; + def warn_attribute_dllexport_explicit_instantiation_decl : Warning< + "explicit instantiation declaration should not be 'dllexport'">, + InGroup>; + def warn_attribute_dllexport_explicit_instantiation_def : Warning< + "'dllexport' attribute ignored on explicit instantiation definition">, + InGroup; + def warn_invalid_initializer_from_system_header : Warning< + "invalid constructor from class in system header, should not be explicit">, + InGroup>; + def note_used_in_initialization_here : Note<"used in initialization here">; + def err_attribute_dll_member_of_dll_class : Error< + "attribute %q0 cannot be applied to member of %q1 class">; + def warn_attribute_dll_instantiated_base_class : Warning< + "propagating dll attribute to %select{already instantiated|explicitly specialized}0 " + "base class template without dll attribute is not supported">, + InGroup>, DefaultIgnore; + def err_attribute_dll_ambiguous_default_ctor : Error< + "'__declspec(dllexport)' cannot be applied to more than one default constructor in %0">; + def err_attribute_weakref_not_static : Error< + "weakref declaration must have internal linkage">; + def err_attribute_weakref_not_global_context : Error< + "weakref declaration of %0 must be in a global context">; + def err_attribute_weakref_without_alias : Error< + "weakref declaration of %0 must also have an alias attribute">; + def err_alias_not_supported_on_darwin : Error < + "aliases are not supported on darwin">; + def warn_attribute_wrong_decl_type_str : Warning< + "%0 attribute only applies to %1">, InGroup; + def err_attribute_wrong_decl_type_str : Error< + warn_attribute_wrong_decl_type_str.Text>; + def warn_attribute_wrong_decl_type : Warning< + "%0 attribute only applies to %select{" + "functions" + "|unions" + "|variables and functions" + "|functions and methods" + "|functions, methods and blocks" + "|functions, methods, and parameters" + "|variables" + "|variables and fields" + "|variables, data members and tag types" + "|types and namespaces" + "|variables, functions and classes" + "|kernel functions" + "|non-K&R-style functions}1">, + InGroup; + def err_attribute_wrong_decl_type : Error; + def warn_type_attribute_wrong_type : Warning< + "'%0' only applies to %select{function|pointer|" + "Objective-C object or block pointer}1 types; type here is %2">, + InGroup; + def warn_incomplete_encoded_type : Warning< + "encoding of %0 type is incomplete because %1 component has unknown encoding">, + InGroup>; + def warn_gnu_inline_attribute_requires_inline : Warning< + "'gnu_inline' attribute requires function to be marked 'inline'," + " attribute ignored">, + InGroup; + def warn_gnu_inline_cplusplus_without_extern : Warning< + "'gnu_inline' attribute without 'extern' in C++ treated as externally" + " available, this changed in Clang 10">, + InGroup>; + def err_attribute_vecreturn_only_vector_member : Error< + "the vecreturn attribute can only be used on a class or structure with one member, which must be a vector">; + def err_attribute_vecreturn_only_pod_record : Error< + "the vecreturn attribute can only be used on a POD (plain old data) class or structure (i.e. no virtual functions)">; + def err_cconv_change : Error< + "function declared '%0' here was previously declared " + "%select{'%2'|without calling convention}1">; + def warn_cconv_unsupported : Warning< + "%0 calling convention is not supported %select{" + // Use CallingConventionIgnoredReason Enum to specify these. + "for this target" + "|on variadic function" + "|on constructor/destructor" + "|on builtin function" + "}1">, + InGroup; + def error_cconv_unsupported : Error; + def err_cconv_knr : Error< + "function with no prototype cannot use the %0 calling convention">; + def warn_cconv_knr : Warning< + err_cconv_knr.Text>, + InGroup>; + def err_cconv_varargs : Error< + "variadic function cannot use %0 calling convention">; + def err_regparm_mismatch : Error<"function declared with regparm(%0) " + "attribute was previously declared " + "%plural{0:without the regparm|:with the regparm(%1)}1 attribute">; + def err_function_attribute_mismatch : Error< + "function declared with %0 attribute " + "was previously declared without the %0 attribute">; + def err_objc_precise_lifetime_bad_type : Error< + "objc_precise_lifetime only applies to retainable types; type here is %0">; + def warn_objc_precise_lifetime_meaningless : Error< + "objc_precise_lifetime is not meaningful for " + "%select{__unsafe_unretained|__autoreleasing}0 objects">; + def err_invalid_pcs : Error<"invalid PCS type">; + def warn_attribute_not_on_decl : Warning< + "%0 attribute ignored when parsing type">, InGroup; + def err_base_specifier_attribute : Error< + "%0 attribute cannot be applied to a base specifier">; + def err_invalid_attribute_on_virtual_function : Error< + "%0 attribute cannot be applied to virtual functions">; + def warn_declspec_allocator_nonpointer : Warning< + "ignoring __declspec(allocator) because the function return type %0 is not " + "a pointer or reference type">, InGroup; + def err_cconv_incomplete_param_type : Error< + "parameter %0 must have a complete type to use function %1 with the %2 " + "calling convention">; + def err_attribute_output_parameter : Error< + "attribute only applies to output parameters">; + + def ext_cannot_use_trivial_abi : ExtWarn< + "'trivial_abi' cannot be applied to %0">, InGroup; + def note_cannot_use_trivial_abi_reason : Note< + "'trivial_abi' is disallowed on %0 because %select{" + "its copy constructors and move constructors are all deleted|" + "it is polymorphic|" + "it has a base of a non-trivial class type|it has a virtual base|" + "it has a __weak field|it has a field of a non-trivial class type}1">; + + // Availability attribute + def warn_availability_unknown_platform : Warning< + "unknown platform %0 in availability macro">, InGroup; + def warn_availability_version_ordering : Warning< + "feature cannot be %select{introduced|deprecated|obsoleted}0 in %1 version " + "%2 before it was %select{introduced|deprecated|obsoleted}3 in version %4; " + "attribute ignored">, InGroup; + def warn_mismatched_availability: Warning< + "availability does not match previous declaration">, InGroup; + def warn_mismatched_availability_override : Warning< + "%select{|overriding }4method %select{introduced after|" + "deprecated before|obsoleted before}0 " + "%select{the protocol method it implements|overridden method}4 " + "on %1 (%2 vs. %3)">, InGroup; + def warn_mismatched_availability_override_unavail : Warning< + "%select{|overriding }1method cannot be unavailable on %0 when " + "%select{the protocol method it implements|its overridden method}1 is " + "available">, + InGroup; + def warn_availability_on_static_initializer : Warning< + "ignoring availability attribute %select{on '+load' method|" + "with constructor attribute|with destructor attribute}0">, + InGroup; + def note_overridden_method : Note< + "overridden method is here">; + def warn_availability_swift_unavailable_deprecated_only : Warning< + "only 'unavailable' and 'deprecated' are supported for Swift availability">, + InGroup; + def note_protocol_method : Note< + "protocol method is here">; + + def warn_unguarded_availability : + Warning<"%0 is only available on %1 %2 or newer">, + InGroup, DefaultIgnore; + def warn_unguarded_availability_new : + Warning, + InGroup; + def note_decl_unguarded_availability_silence : Note< + "annotate %select{%1|anonymous %1}0 with an availability attribute to silence this warning">; + def note_unguarded_available_silence : Note< + "enclose %0 in %select{an @available|a __builtin_available}1 check to silence" + " this warning">; + def warn_at_available_unchecked_use : Warning< + "%select{@available|__builtin_available}0 does not guard availability here; " + "use if (%select{@available|__builtin_available}0) instead">, + InGroup>; + + def warn_missing_sdksettings_for_availability_checking : Warning< + "%0 availability is ignored without a valid 'SDKSettings.json' in the SDK">, + InGroup>; + + // Thread Safety Attributes + def warn_thread_attribute_ignored : Warning< + "ignoring %0 attribute because its argument is invalid">, + InGroup, DefaultIgnore; + def warn_thread_attribute_not_on_non_static_member : Warning< + "%0 attribute without capability arguments can only be applied to non-static " + "methods of a class">, + InGroup, DefaultIgnore; + def warn_thread_attribute_not_on_capability_member : Warning< + "%0 attribute without capability arguments refers to 'this', but %1 isn't " + "annotated with 'capability' or 'scoped_lockable' attribute">, + InGroup, DefaultIgnore; + def warn_thread_attribute_argument_not_lockable : Warning< + "%0 attribute requires arguments whose type is annotated " + "with 'capability' attribute; type here is %1">, + InGroup, DefaultIgnore; + def warn_thread_attribute_decl_not_lockable : Warning< + "%0 attribute can only be applied in a context annotated " + "with 'capability' attribute">, + InGroup, DefaultIgnore; + def warn_thread_attribute_decl_not_pointer : Warning< + "%0 only applies to pointer types; type here is %1">, + InGroup, DefaultIgnore; + def err_attribute_argument_out_of_bounds_extra_info : Error< + "%0 attribute parameter %1 is out of bounds: " + "%plural{0:no parameters to index into|" + "1:can only be 1, since there is one parameter|" + ":must be between 1 and %2}2">; + + // Thread Safety Analysis + def warn_unlock_but_no_lock : Warning<"releasing %0 '%1' that was not held">, + InGroup, DefaultIgnore; + def warn_unlock_kind_mismatch : Warning< + "releasing %0 '%1' using %select{shared|exclusive}2 access, expected " + "%select{shared|exclusive}3 access">, + InGroup, DefaultIgnore; + def warn_double_lock : Warning<"acquiring %0 '%1' that is already held">, + InGroup, DefaultIgnore; + def warn_no_unlock : Warning< + "%0 '%1' is still held at the end of function">, + InGroup, DefaultIgnore; + def warn_expecting_locked : Warning< + "expecting %0 '%1' to be held at the end of function">, + InGroup, DefaultIgnore; + // FIXME: improve the error message about locks not in scope + def warn_lock_some_predecessors : Warning< + "%0 '%1' is not held on every path through here">, + InGroup, DefaultIgnore; + def warn_expecting_lock_held_on_loop : Warning< + "expecting %0 '%1' to be held at start of each loop">, + InGroup, DefaultIgnore; + def note_locked_here : Note<"%0 acquired here">; + def note_unlocked_here : Note<"%0 released here">; + def warn_lock_exclusive_and_shared : Warning< + "%0 '%1' is acquired exclusively and shared in the same scope">, + InGroup, DefaultIgnore; + def note_lock_exclusive_and_shared : Note< + "the other acquisition of %0 '%1' is here">; + def warn_variable_requires_any_lock : Warning< + "%select{reading|writing}1 variable %0 requires holding " + "%select{any mutex|any mutex exclusively}1">, + InGroup, DefaultIgnore; + def warn_var_deref_requires_any_lock : Warning< + "%select{reading|writing}1 the value pointed to by %0 requires holding " + "%select{any mutex|any mutex exclusively}1">, + InGroup, DefaultIgnore; + def warn_fun_excludes_mutex : Warning< + "cannot call function '%1' while %0 '%2' is held">, + InGroup, DefaultIgnore; + def warn_cannot_resolve_lock : Warning< + "cannot resolve lock expression">, + InGroup, DefaultIgnore; + def warn_acquired_before : Warning< + "%0 '%1' must be acquired before '%2'">, + InGroup, DefaultIgnore; + def warn_acquired_before_after_cycle : Warning< + "Cycle in acquired_before/after dependencies, starting with '%0'">, + InGroup, DefaultIgnore; + + + // Thread safety warnings negative capabilities + def warn_acquire_requires_negative_cap : Warning< + "acquiring %0 '%1' requires negative capability '%2'">, + InGroup, DefaultIgnore; + def warn_fun_requires_negative_cap : Warning< + "calling function %0 requires negative capability '%1'">, + InGroup, DefaultIgnore; + + // Thread safety warnings on pass by reference + def warn_guarded_pass_by_reference : Warning< + "passing variable %1 by reference requires holding %0 " + "%select{'%2'|'%2' exclusively}3">, + InGroup, DefaultIgnore; + def warn_pt_guarded_pass_by_reference : Warning< + "passing the value that %1 points to by reference requires holding %0 " + "%select{'%2'|'%2' exclusively}3">, + InGroup, DefaultIgnore; + + // Imprecise thread safety warnings + def warn_variable_requires_lock : Warning< + "%select{reading|writing}3 variable %1 requires holding %0 " + "%select{'%2'|'%2' exclusively}3">, + InGroup, DefaultIgnore; + def warn_var_deref_requires_lock : Warning< + "%select{reading|writing}3 the value pointed to by %1 requires " + "holding %0 %select{'%2'|'%2' exclusively}3">, + InGroup, DefaultIgnore; + def warn_fun_requires_lock : Warning< + "calling function %1 requires holding %0 %select{'%2'|'%2' exclusively}3">, + InGroup, DefaultIgnore; + + // Precise thread safety warnings + def warn_variable_requires_lock_precise : + Warning, + InGroup, DefaultIgnore; + def warn_var_deref_requires_lock_precise : + Warning, + InGroup, DefaultIgnore; + def warn_fun_requires_lock_precise : + Warning, + InGroup, DefaultIgnore; + def note_found_mutex_near_match : Note<"found near match '%0'">; + + // Verbose thread safety warnings + def warn_thread_safety_verbose : Warning<"thread safety verbose warning">, + InGroup, DefaultIgnore; + def note_thread_warning_in_fun : Note<"thread warning in function %0">; + def note_guarded_by_declared_here : Note<"guarded_by declared here">; + + // Dummy warning that will trigger "beta" warnings from the analysis if enabled. + def warn_thread_safety_beta : Warning<"thread safety beta warning">, + InGroup, DefaultIgnore; + + // Consumed warnings + def warn_use_in_invalid_state : Warning< + "invalid invocation of method '%0' on object '%1' while it is in the '%2' " + "state">, InGroup, DefaultIgnore; + def warn_use_of_temp_in_invalid_state : Warning< + "invalid invocation of method '%0' on a temporary object while it is in the " + "'%1' state">, InGroup, DefaultIgnore; + def warn_attr_on_unconsumable_class : Warning< + "consumed analysis attribute is attached to member of class %0 which isn't " + "marked as consumable">, InGroup, DefaultIgnore; + def warn_return_typestate_for_unconsumable_type : Warning< + "return state set for an unconsumable type '%0'">, InGroup, + DefaultIgnore; + def warn_return_typestate_mismatch : Warning< + "return value not in expected state; expected '%0', observed '%1'">, + InGroup, DefaultIgnore; + def warn_loop_state_mismatch : Warning< + "state of variable '%0' must match at the entry and exit of loop">, + InGroup, DefaultIgnore; + def warn_param_return_typestate_mismatch : Warning< + "parameter '%0' not in expected state when the function returns: expected " + "'%1', observed '%2'">, InGroup, DefaultIgnore; + def warn_param_typestate_mismatch : Warning< + "argument not in expected state; expected '%0', observed '%1'">, + InGroup, DefaultIgnore; + + // no_sanitize attribute + def warn_unknown_sanitizer_ignored : Warning< + "unknown sanitizer '%0' ignored">, InGroup; + + def warn_impcast_vector_scalar : Warning< + "implicit conversion turns vector to scalar: %0 to %1">, + InGroup, DefaultIgnore; + def warn_impcast_complex_scalar : Warning< + "implicit conversion discards imaginary component: %0 to %1">, + InGroup, DefaultIgnore; + def err_impcast_complex_scalar : Error< + "implicit conversion from %0 to %1 is not permitted in C++">; + def warn_impcast_float_precision : Warning< + "implicit conversion loses floating-point precision: %0 to %1">, + InGroup, DefaultIgnore; + def warn_impcast_float_result_precision : Warning< + "implicit conversion when assigning computation result loses floating-point precision: %0 to %1">, + InGroup, DefaultIgnore; + def warn_impcast_double_promotion : Warning< + "implicit conversion increases floating-point precision: %0 to %1">, + InGroup, DefaultIgnore; + def warn_impcast_integer_sign : Warning< + "implicit conversion changes signedness: %0 to %1">, + InGroup, DefaultIgnore; + def warn_impcast_integer_sign_conditional : Warning< + "operand of ? changes signedness: %0 to %1">, + InGroup, DefaultIgnore; + def warn_impcast_integer_precision : Warning< + "implicit conversion loses integer precision: %0 to %1">, + InGroup, DefaultIgnore; + def warn_impcast_high_order_zero_bits : Warning< + "higher order bits are zeroes after implicit conversion">, + InGroup, DefaultIgnore; + def warn_impcast_nonnegative_result : Warning< + "the resulting value is always non-negative after implicit conversion">, + InGroup, DefaultIgnore; + def warn_impcast_integer_64_32 : Warning< + "implicit conversion loses integer precision: %0 to %1">, + InGroup, DefaultIgnore; + def warn_impcast_integer_precision_constant : Warning< + "implicit conversion from %2 to %3 changes value from %0 to %1">, + InGroup; + def warn_impcast_bitfield_precision_constant : Warning< + "implicit truncation from %2 to bit-field changes value from %0 to %1">, + InGroup; + def warn_impcast_constant_value_to_objc_bool : Warning< + "implicit conversion from constant value %0 to 'BOOL'; " + "the only well defined values for 'BOOL' are YES and NO">, + InGroup; + + def warn_impcast_fixed_point_range : Warning< + "implicit conversion from %0 cannot fit within the range of values for %1">, + InGroup; + + def warn_impcast_literal_float_to_integer : Warning< + "implicit conversion from %0 to %1 changes value from %2 to %3">, + InGroup; + def warn_impcast_literal_float_to_integer_out_of_range : Warning< + "implicit conversion of out of range value from %0 to %1 is undefined">, + InGroup; + def warn_impcast_float_integer : Warning< + "implicit conversion turns floating-point number into integer: %0 to %1">, + InGroup, DefaultIgnore; + def warn_impcast_float_to_objc_signed_char_bool : Warning< + "implicit conversion from floating-point type %0 to 'BOOL'">, + InGroup; + def warn_impcast_int_to_objc_signed_char_bool : Warning< + "implicit conversion from integral type %0 to 'BOOL'">, + InGroup, DefaultIgnore; + + // Implicit int -> float conversion precision loss warnings. + def warn_impcast_integer_float_precision : Warning< + "implicit conversion from %0 to %1 may lose precision">, + InGroup, DefaultIgnore; + def warn_impcast_integer_float_precision_constant : Warning< + "implicit conversion from %2 to %3 changes value from %0 to %1">, + InGroup; + + def warn_impcast_float_to_integer : Warning< + "implicit conversion from %0 to %1 changes value from %2 to %3">, + InGroup, DefaultIgnore; + def warn_impcast_float_to_integer_out_of_range : Warning< + "implicit conversion of out of range value from %0 to %1 is undefined">, + InGroup, DefaultIgnore; + def warn_impcast_float_to_integer_zero : Warning< + "implicit conversion from %0 to %1 changes non-zero value from %2 to %3">, + InGroup, DefaultIgnore; + + def warn_impcast_string_literal_to_bool : Warning< + "implicit conversion turns string literal into bool: %0 to %1">, + InGroup, DefaultIgnore; + def warn_impcast_different_enum_types : Warning< + "implicit conversion from enumeration type %0 to different enumeration type " + "%1">, InGroup; + def warn_impcast_bool_to_null_pointer : Warning< + "initialization of pointer of type %0 to null from a constant boolean " + "expression">, InGroup; + def warn_non_literal_null_pointer : Warning< + "expression which evaluates to zero treated as a null pointer constant of " + "type %0">, InGroup; + def warn_pointer_compare : Warning< + "comparing a pointer to a null character constant; did you mean " + "to compare to %select{NULL|(void *)0}0?">, + InGroup>; + def warn_impcast_null_pointer_to_integer : Warning< + "implicit conversion of %select{NULL|nullptr}0 constant to %1">, + InGroup; + def warn_impcast_floating_point_to_bool : Warning< + "implicit conversion turns floating-point number into bool: %0 to %1">, + InGroup; + def ext_ms_impcast_fn_obj : ExtWarn< + "implicit conversion between pointer-to-function and pointer-to-object is a " + "Microsoft extension">, InGroup; + + def warn_impcast_pointer_to_bool : Warning< + "address of%select{| function| array}0 '%1' will always evaluate to " + "'true'">, + InGroup; + def warn_cast_nonnull_to_bool : Warning< + "nonnull %select{function call|parameter}0 '%1' will evaluate to " + "'true' on first encounter">, + InGroup; + def warn_this_bool_conversion : Warning< + "'this' pointer cannot be null in well-defined C++ code; pointer may be " + "assumed to always convert to true">, InGroup; + def warn_address_of_reference_bool_conversion : Warning< + "reference cannot be bound to dereferenced null pointer in well-defined C++ " + "code; pointer may be assumed to always convert to true">, + InGroup; + + def warn_xor_used_as_pow : Warning< + "result of '%0' is %1; did you mean exponentiation?">, + InGroup; + def warn_xor_used_as_pow_base_extra : Warning< + "result of '%0' is %1; did you mean '%2' (%3)?">, + InGroup; + def warn_xor_used_as_pow_base : Warning< + "result of '%0' is %1; did you mean '%2'?">, + InGroup; + def note_xor_used_as_pow_silence : Note< + "replace expression with '%0' %select{|or use 'xor' instead of '^' }1to silence this warning">; + + def warn_null_pointer_compare : Warning< + "comparison of %select{address of|function|array}0 '%1' %select{not |}2" + "equal to a null pointer is always %select{true|false}2">, + InGroup; + def warn_nonnull_expr_compare : Warning< + "comparison of nonnull %select{function call|parameter}0 '%1' " + "%select{not |}2equal to a null pointer is '%select{true|false}2' on first " + "encounter">, + InGroup; + def warn_this_null_compare : Warning< + "'this' pointer cannot be null in well-defined C++ code; comparison may be " + "assumed to always evaluate to %select{true|false}0">, + InGroup; + def warn_address_of_reference_null_compare : Warning< + "reference cannot be bound to dereferenced null pointer in well-defined C++ " + "code; comparison may be assumed to always evaluate to " + "%select{true|false}0">, + InGroup; + def note_reference_is_return_value : Note<"%0 returns a reference">; + + def note_pointer_declared_here : Note< + "pointer %0 declared here">; + def warn_division_sizeof_ptr : Warning< + "'%0' will return the size of the pointer, not the array itself">, + InGroup>; + def warn_division_sizeof_array : Warning< + "expression does not compute the number of elements in this array; element " + "type is %0, not %1">, + InGroup>; + + def note_function_warning_silence : Note< + "prefix with the address-of operator to silence this warning">; + def note_function_to_function_call : Note< + "suffix with parentheses to turn this into a function call">; + def warn_impcast_objective_c_literal_to_bool : Warning< + "implicit boolean conversion of Objective-C object literal always " + "evaluates to true">, + InGroup; + + def warn_cast_align : Warning< + "cast from %0 to %1 increases required alignment from %2 to %3">, + InGroup, DefaultIgnore; + def warn_old_style_cast : Warning< + "use of old-style cast">, InGroup, DefaultIgnore; + + // Separate between casts to void* and non-void* pointers. + // Some APIs use (abuse) void* for something like a user context, + // and often that value is an integer even if it isn't a pointer itself. + // Having a separate warning flag allows users to control the warning + // for their workflow. + def warn_int_to_pointer_cast : Warning< + "cast to %1 from smaller integer type %0">, + InGroup; + def warn_int_to_void_pointer_cast : Warning< + "cast to %1 from smaller integer type %0">, + InGroup; + def warn_pointer_to_int_cast : Warning< + "cast to smaller integer type %1 from %0">, + InGroup; + def warn_pointer_to_enum_cast : Warning< + warn_pointer_to_int_cast.Text>, + InGroup; + def warn_void_pointer_to_int_cast : Warning< + "cast to smaller integer type %1 from %0">, + InGroup; + def warn_void_pointer_to_enum_cast : Warning< + warn_void_pointer_to_int_cast.Text>, + InGroup; + + def warn_attribute_ignored_for_field_of_type : Warning< + "%0 attribute ignored for field of type %1">, + InGroup; + def warn_no_underlying_type_specified_for_enum_bitfield : Warning< + "enums in the Microsoft ABI are signed integers by default; consider giving " + "the enum %0 an unsigned underlying type to make this code portable">, + InGroup, DefaultIgnore; + def warn_attribute_packed_for_bitfield : Warning< + "'packed' attribute was ignored on bit-fields with single-byte alignment " + "in older versions of GCC and Clang">, + InGroup>; + def warn_transparent_union_attribute_field_size_align : Warning< + "%select{alignment|size}0 of field %1 (%2 bits) does not match the " + "%select{alignment|size}0 of the first field in transparent union; " + "transparent_union attribute ignored">, + InGroup; + def note_transparent_union_first_field_size_align : Note< + "%select{alignment|size}0 of first field is %1 bits">; + def warn_transparent_union_attribute_not_definition : Warning< + "transparent_union attribute can only be applied to a union definition; " + "attribute ignored">, + InGroup; + def warn_transparent_union_attribute_floating : Warning< + "first field of a transparent union cannot have %select{floating point|" + "vector}0 type %1; transparent_union attribute ignored">, + InGroup; + def warn_transparent_union_attribute_zero_fields : Warning< + "transparent union definition must contain at least one field; " + "transparent_union attribute ignored">, + InGroup; + def warn_attribute_type_not_supported : Warning< + "%0 attribute argument not supported: %1">, + InGroup; + def warn_attribute_unknown_visibility : Warning<"unknown visibility %0">, + InGroup; + def warn_attribute_protected_visibility : + Warning<"target does not support 'protected' visibility; using 'default'">, + InGroup>; + def err_mismatched_visibility: Error<"visibility does not match previous declaration">; + def note_previous_attribute : Note<"previous attribute is here">; + def note_conflicting_attribute : Note<"conflicting attribute is here">; + def note_attribute : Note<"attribute is here">; + def err_mismatched_ms_inheritance : Error< + "inheritance model does not match %select{definition|previous declaration}0">; + def warn_ignored_ms_inheritance : Warning< + "inheritance model ignored on %select{primary template|partial specialization}0">, + InGroup; + def note_previous_ms_inheritance : Note< + "previous inheritance model specified here">; + def err_machine_mode : Error<"%select{unknown|unsupported}0 machine mode %1">; + def err_mode_not_primitive : Error< + "mode attribute only supported for integer and floating-point types">; + def err_mode_wrong_type : Error< + "type of machine mode does not match type of base type">; + def warn_vector_mode_deprecated : Warning< + "specifying vector types with the 'mode' attribute is deprecated; " + "use the 'vector_size' attribute instead">, + InGroup; + def err_complex_mode_vector_type : Error< + "type of machine mode does not support base vector types">; + def err_enum_mode_vector_type : Error< + "mode %0 is not supported for enumeration types">; + def warn_attribute_nonnull_no_pointers : Warning< + "'nonnull' attribute applied to function with no pointer arguments">, + InGroup; + def warn_attribute_nonnull_parm_no_args : Warning< + "'nonnull' attribute when used on parameters takes no arguments">, + InGroup; + def note_declared_nonnull : Note< + "declared %select{'returns_nonnull'|'nonnull'}0 here">; + def warn_attribute_sentinel_named_arguments : Warning< + "'sentinel' attribute requires named arguments">, + InGroup; + def warn_attribute_sentinel_not_variadic : Warning< + "'sentinel' attribute only supported for variadic %select{functions|blocks}0">, + InGroup; + def warn_deprecated_ignored_on_using : Warning< + "%0 currently has no effect on a using declaration">, + InGroup; + def err_attribute_sentinel_less_than_zero : Error< + "'sentinel' parameter 1 less than zero">; + def err_attribute_sentinel_not_zero_or_one : Error< + "'sentinel' parameter 2 not 0 or 1">; + def warn_cleanup_ext : Warning< + "GCC does not allow the 'cleanup' attribute argument to be anything other " + "than a simple identifier">, + InGroup; + def err_attribute_cleanup_arg_not_function : Error< + "'cleanup' argument %select{|%1 |%1 }0is not a %select{||single }0function">; + def err_attribute_cleanup_func_must_take_one_arg : Error< + "'cleanup' function %0 must take 1 parameter">; + def err_attribute_cleanup_func_arg_incompatible_type : Error< + "'cleanup' function %0 parameter has " + "%diff{type $ which is incompatible with type $|incompatible type}1,2">; + def err_attribute_regparm_wrong_platform : Error< + "'regparm' is not valid on this platform">; + def err_attribute_regparm_invalid_number : Error< + "'regparm' parameter must be between 0 and %0 inclusive">; + def err_attribute_not_supported_in_lang : Error< + "%0 attribute is not supported in %select{C|C++|Objective-C}1">; + def err_attribute_not_supported_on_arch + : Error<"%0 attribute is not supported on '%1'">; + def warn_gcc_ignores_type_attr : Warning< + "GCC does not allow the %0 attribute to be written on a type">, + InGroup; + + // Clang-Specific Attributes + def warn_attribute_iboutlet : Warning< + "%0 attribute can only be applied to instance variables or properties">, + InGroup; + def err_iboutletcollection_type : Error< + "invalid type %0 as argument of iboutletcollection attribute">; + def err_iboutletcollection_builtintype : Error< + "type argument of iboutletcollection attribute cannot be a builtin type">; + def warn_iboutlet_object_type : Warning< + "%select{instance variable|property}2 with %0 attribute must " + "be an object type (invalid %1)">, InGroup; + def warn_iboutletcollection_property_assign : Warning< + "IBOutletCollection properties should be copy/strong and not assign">, + InGroup; + + def err_attribute_overloadable_mismatch : Error< + "redeclaration of %0 must %select{not |}1have the 'overloadable' attribute">; + def note_attribute_overloadable_prev_overload : Note< + "previous %select{unmarked |}0overload of function is here">; + def err_attribute_overloadable_no_prototype : Error< + "'overloadable' function %0 must have a prototype">; + def err_attribute_overloadable_multiple_unmarked_overloads : Error< + "at most one overload for a given name may lack the 'overloadable' " + "attribute">; + def warn_attribute_no_builtin_invalid_builtin_name : Warning< + "'%0' is not a valid builtin name for %1">, + InGroup>; + def err_attribute_no_builtin_wildcard_or_builtin_name : Error< + "empty %0 cannot be composed with named ones">; + def err_attribute_no_builtin_on_non_definition : Error< + "%0 attribute is permitted on definitions only">; + def err_attribute_no_builtin_on_defaulted_deleted_function : Error< + "%0 attribute has no effect on defaulted or deleted functions">; + def warn_ns_attribute_wrong_return_type : Warning< + "%0 attribute only applies to %select{functions|methods|properties}1 that " + "return %select{an Objective-C object|a pointer|a non-retainable pointer}2">, + InGroup; + def err_ns_attribute_wrong_parameter_type : Error< + "%0 attribute only applies to " + "%select{Objective-C object|pointer|pointer-to-CF-pointer}1 parameters">; + def warn_ns_attribute_wrong_parameter_type : Warning< + "%0 attribute only applies to " + "%select{Objective-C object|pointer|pointer-to-CF-pointer|pointer/reference-to-OSObject-pointer}1 parameters">, + InGroup; + def warn_objc_requires_super_protocol : Warning< + "%0 attribute cannot be applied to %select{methods in protocols|dealloc}1">, + InGroup>; + def note_protocol_decl : Note< + "protocol is declared here">; + def note_protocol_decl_undefined : Note< + "protocol %0 has no definition">; + def err_attribute_preferred_name_arg_invalid : Error< + "argument %0 to 'preferred_name' attribute is not a typedef for " + "a specialization of %1">; + def err_attribute_builtin_alias : Error< + "%0 attribute can only be applied to a ARM or RISC-V builtin">; + + // called-once attribute diagnostics. + def err_called_once_attribute_wrong_type : Error< + "'called_once' attribute only applies to function-like parameters">; + + def warn_completion_handler_never_called : Warning< + "%select{|captured }1completion handler is never called">, + InGroup, DefaultIgnore; + def warn_called_once_never_called : Warning< + "%select{|captured }1%0 parameter marked 'called_once' is never called">, + InGroup; + + def warn_completion_handler_never_called_when : Warning< + "completion handler is never %select{used|called}1 when " + "%select{taking true branch|taking false branch|" + "handling this case|none of the cases applies|" + "entering the loop|skipping the loop|taking one of the branches}2">, + InGroup, DefaultIgnore; + def warn_called_once_never_called_when : Warning< + "%0 parameter marked 'called_once' is never %select{used|called}1 when " + "%select{taking true branch|taking false branch|" + "handling this case|none of the cases applies|" + "entering the loop|skipping the loop|taking one of the branches}2">, + InGroup; + + def warn_completion_handler_called_twice : Warning< + "completion handler is called twice">, + InGroup, DefaultIgnore; + def warn_called_once_gets_called_twice : Warning< + "%0 parameter marked 'called_once' is called twice">, + InGroup; + def note_called_once_gets_called_twice : Note< + "previous call is here%select{; set to nil to indicate " + "it cannot be called afterwards|}0">; + + // objc_designated_initializer attribute diagnostics. + def warn_objc_designated_init_missing_super_call : Warning< + "designated initializer missing a 'super' call to a designated initializer of the super class">, + InGroup; + def note_objc_designated_init_marked_here : Note< + "method marked as designated initializer of the class here">; + def warn_objc_designated_init_non_super_designated_init_call : Warning< + "designated initializer should only invoke a designated initializer on 'super'">, + InGroup; + def warn_objc_designated_init_non_designated_init_call : Warning< + "designated initializer invoked a non-designated initializer">, + InGroup; + def warn_objc_secondary_init_super_init_call : Warning< + "convenience initializer should not invoke an initializer on 'super'">, + InGroup; + def warn_objc_secondary_init_missing_init_call : Warning< + "convenience initializer missing a 'self' call to another initializer">, + InGroup; + def warn_objc_implementation_missing_designated_init_override : Warning< + "method override for the designated initializer of the superclass %objcinstance0 not found">, + InGroup; + def err_designated_init_attr_non_init : Error< + "'objc_designated_initializer' attribute only applies to init methods " + "of interface or class extension declarations">; + + // objc_bridge attribute diagnostics. + def err_objc_attr_not_id : Error< + "parameter of %0 attribute must be a single name of an Objective-C %select{class|protocol}1">; + def err_objc_attr_typedef_not_id : Error< + "parameter of %0 attribute must be 'id' when used on a typedef">; + def err_objc_attr_typedef_not_void_pointer : Error< + "'objc_bridge(id)' is only allowed on structs and typedefs of void pointers">; + def err_objc_cf_bridged_not_interface : Error< + "CF object of type %0 is bridged to %1, which is not an Objective-C class">; + def err_objc_ns_bridged_invalid_cfobject : Error< + "ObjectiveC object of type %0 is bridged to %1, which is not valid CF object">; + def warn_objc_invalid_bridge : Warning< + "%0 bridges to %1, not %2">, InGroup; + def warn_objc_invalid_bridge_to_cf : Warning< + "%0 cannot bridge to %1">, InGroup; + + // objc_bridge_related attribute diagnostics. + def err_objc_bridged_related_invalid_class : Error< + "could not find Objective-C class %0 to convert %1 to %2">; + def err_objc_bridged_related_invalid_class_name : Error< + "%0 must be name of an Objective-C class to be able to convert %1 to %2">; + def err_objc_bridged_related_known_method : Error< + "%0 must be explicitly converted to %1; use %select{%objcclass2|%objcinstance2}3 " + "method for this conversion">; + + def err_objc_attr_protocol_requires_definition : Error< + "attribute %0 can only be applied to @protocol definitions, not forward declarations">; + + // Swift attributes. + def warn_attr_swift_name_function + : Warning<"%0 attribute argument must be a string literal specifying a Swift function name">, + InGroup; + def warn_attr_swift_name_invalid_identifier + : Warning<"%0 attribute has invalid identifier for the %select{base|context|parameter}1 name">, + InGroup; + def warn_attr_swift_name_decl_kind + : Warning<"%0 attribute cannot be applied to this declaration">, + InGroup; + def warn_attr_swift_name_subscript_invalid_parameter + : Warning<"%0 attribute for 'subscript' must %select{be a getter or setter|" + "have at least one parameter|" + "have a 'self:' parameter}1">, + InGroup; + def warn_attr_swift_name_missing_parameters + : Warning<"%0 attribute is missing parameter label clause">, + InGroup; + def warn_attr_swift_name_setter_parameters + : Warning<"%0 attribute for setter must have one parameter for new value">, + InGroup; + def warn_attr_swift_name_multiple_selfs + : Warning<"%0 attribute cannot specify more than one 'self:' parameter">, + InGroup; + def warn_attr_swift_name_getter_parameters + : Warning<"%0 attribute for getter must not have any parameters besides 'self:'">, + InGroup; + def warn_attr_swift_name_subscript_setter_no_newValue + : Warning<"%0 attribute for 'subscript' setter must have a 'newValue:' parameter">, + InGroup; + def warn_attr_swift_name_subscript_setter_multiple_newValues + : Warning<"%0 attribute for 'subscript' setter cannot have multiple 'newValue:' parameters">, + InGroup; + def warn_attr_swift_name_subscript_getter_newValue + : Warning<"%0 attribute for 'subscript' getter cannot have a 'newValue:' parameter">, + InGroup; + def warn_attr_swift_name_num_params + : Warning<"too %select{few|many}0 parameters in the signature specified by " + "the %1 attribute (expected %2; got %3)">, + InGroup; + def warn_attr_swift_name_decl_missing_params + : Warning<"%0 attribute cannot be applied to a %select{function|method}1 " + "with no parameters">, + InGroup; + + def err_attr_swift_error_no_error_parameter : Error< + "%0 attribute can only be applied to a %select{function|method}1 with an " + "error parameter">; + def err_attr_swift_error_return_type : Error< + "%0 attribute with '%1' convention can only be applied to a " + "%select{function|method}2 returning %select{an integral type|a pointer}3">; + + def err_swift_async_no_access : Error< + "first argument to 'swift_async' must be either 'none', 'swift_private', or " + "'not_swift_private'">; + def err_swift_async_bad_block_type : Error< + "'swift_async' completion handler parameter must have block type returning" + " 'void', type here is %0">; + + def err_swift_async_error_without_swift_async : Error< + "%0 attribute must be applied to a %select{function|method}1 annotated " + "with non-'none' attribute 'swift_async'">; + def err_swift_async_error_no_error_parameter : Error< + "%0 attribute with 'nonnull_error' convention can only be applied to a " + "%select{function|method}1 with a completion handler with an error " + "parameter">; + def err_swift_async_error_non_integral : Error< + "%0 attribute with '%1' convention must have an integral-typed parameter " + "in completion handler at index %2, type here is %3">; + + def warn_ignored_objc_externally_retained : Warning< + "'objc_externally_retained' can only be applied to local variables " + "%select{of retainable type|with strong ownership}0">, + InGroup; + + // Function Parameter Semantic Analysis. + def err_param_with_void_type : Error<"argument may not have 'void' type">; + def err_void_only_param : Error< + "'void' must be the first and only parameter if specified">; + def err_void_param_qualified : Error< + "'void' as parameter must not have type qualifiers">; + def err_ident_list_in_fn_declaration : Error< + "a parameter list without types is only allowed in a function definition">; + def ext_param_not_declared : Extension< + "parameter %0 was not declared, defaulting to type 'int'">; + def err_param_default_argument : Error< + "C does not support default arguments">; + def err_param_default_argument_redefinition : Error< + "redefinition of default argument">; + def ext_param_default_argument_redefinition : ExtWarn< + err_param_default_argument_redefinition.Text>, + InGroup; + def err_param_default_argument_missing : Error< + "missing default argument on parameter">; + def err_param_default_argument_missing_name : Error< + "missing default argument on parameter %0">; + def err_param_default_argument_references_param : Error< + "default argument references parameter %0">; + def err_param_default_argument_references_local : Error< + "default argument references local variable %0 of enclosing function">; + def err_param_default_argument_references_this : Error< + "default argument references 'this'">; + def err_param_default_argument_nonfunc : Error< + "default arguments can only be specified for parameters in a function " + "declaration">; + def err_param_default_argument_template_redecl : Error< + "default arguments cannot be added to a function template that has already " + "been declared">; + def err_param_default_argument_member_template_redecl : Error< + "default arguments cannot be added to an out-of-line definition of a member " + "of a %select{class template|class template partial specialization|nested " + "class in a template}0">; + def err_param_default_argument_on_parameter_pack : Error< + "parameter pack cannot have a default argument">; + def err_uninitialized_member_for_assign : Error< + "cannot define the implicit copy assignment operator for %0, because " + "non-static %select{reference|const}1 member %2 cannot use copy " + "assignment operator">; + def err_uninitialized_member_in_ctor : Error< + "%select{constructor for %1|" + "implicit default constructor for %1|" + "cannot use constructor inherited from %1:}0 must explicitly " + "initialize the %select{reference|const}2 member %3">; + def err_default_arg_makes_ctor_special : Error< + "addition of default argument on redeclaration makes this constructor a " + "%select{default|copy|move}0 constructor">; + + def err_use_of_default_argument_to_function_declared_later : Error< + "use of default argument to function %0 that is declared later in class %1">; + def note_default_argument_declared_here : Note< + "default argument declared here">; + def err_recursive_default_argument : Error<"recursive evaluation of default argument">; + def note_recursive_default_argument_used_here : Note< + "default argument used here">; + + def ext_param_promoted_not_compatible_with_prototype : ExtWarn< + "%diff{promoted type $ of K&R function parameter is not compatible with the " + "parameter type $|promoted type of K&R function parameter is not compatible " + "with parameter type}0,1 declared in a previous prototype">, + InGroup; + + + // C++ Overloading Semantic Analysis. + def err_ovl_diff_return_type : Error< + "functions that differ only in their return type cannot be overloaded">; + def err_ovl_static_nonstatic_member : Error< + "static and non-static member functions with the same parameter types " + "cannot be overloaded">; + + let Deferrable = 1 in { + + def err_ovl_no_viable_function_in_call : Error< + "no matching function for call to %0">; + def err_ovl_no_viable_member_function_in_call : Error< + "no matching member function for call to %0">; + def err_ovl_ambiguous_call : Error< + "call to %0 is ambiguous">; + def err_ovl_deleted_call : Error<"call to deleted function %0">; + def err_ovl_ambiguous_member_call : Error< + "call to member function %0 is ambiguous">; + def err_ovl_deleted_member_call : Error< + "call to deleted member function %0">; + def note_ovl_too_many_candidates : Note< + "remaining %0 candidate%s0 omitted; " + "pass -fshow-overloads=all to show them">; + + def select_ovl_candidate_kind : TextSubstitution< + "%select{function|function|function (with reversed parameter order)|" + "constructor|" + "constructor (the implicit default constructor)|" + "constructor (the implicit copy constructor)|" + "constructor (the implicit move constructor)|" + "function (the implicit copy assignment operator)|" + "function (the implicit move assignment operator)|" + "function (the implicit 'operator==' for this 'operator<=>)'|" + "inherited constructor}0%select{| template| %2}1">; + + def note_ovl_candidate : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,3" + "%select{| has different class%diff{ (expected $ but has $)|}5,6" + "| has different number of parameters (expected %5 but has %6)" + "| has type mismatch at %ordinal5 parameter" + "%diff{ (expected $ but has $)|}6,7" + "| has different return type%diff{ ($ expected but has $)|}5,6" + "| has different qualifiers (expected %5 but found %6)" + "| has different exception specification}4">; + + def note_ovl_candidate_explicit : Note< + "explicit %select{constructor|conversion function|deduction guide}0 " + "is not a candidate%select{| (explicit specifier evaluates to true)}1">; + def note_ovl_candidate_inherited_constructor : Note< + "constructor from base class %0 inherited here">; + def note_ovl_candidate_inherited_constructor_slice : Note< + "candidate %select{constructor|template}0 ignored: " + "inherited constructor cannot be used to %select{copy|move}1 object">; + def note_ovl_candidate_illegal_constructor : Note< + "candidate %select{constructor|template}0 ignored: " + "instantiation %select{takes|would take}0 its own class type by value">; + def note_ovl_candidate_illegal_constructor_adrspace_mismatch : Note< + "candidate constructor ignored: cannot be used to construct an object " + "in address space %0">; + def note_ovl_candidate_bad_deduction : Note< + "candidate template ignored: failed template argument deduction">; + def note_ovl_candidate_incomplete_deduction : Note<"candidate template ignored: " + "couldn't infer template argument %0">; + def note_ovl_candidate_incomplete_deduction_pack : Note< + "candidate template ignored: " + "deduced too few arguments for expanded pack %0; no argument for %ordinal1 " + "expanded parameter in deduced argument pack %2">; + def note_ovl_candidate_inconsistent_deduction : Note< + "candidate template ignored: deduced %select{conflicting types|" + "conflicting values|conflicting templates|packs of different lengths}0 " + "for parameter %1%diff{ ($ vs. $)|}2,3">; + def note_ovl_candidate_inconsistent_deduction_types : Note< + "candidate template ignored: deduced values %diff{" + "of conflicting types for parameter %0 (%1 of type $ vs. %3 of type $)|" + "%1 and %3 of conflicting types for parameter %0}2,4">; + def note_ovl_candidate_explicit_arg_mismatch_named : Note< + "candidate template ignored: invalid explicitly-specified argument " + "for template parameter %0">; + def note_ovl_candidate_unsatisfied_constraints : Note< + "candidate template ignored: constraints not satisfied%0">; + def note_ovl_candidate_explicit_arg_mismatch_unnamed : Note< + "candidate template ignored: invalid explicitly-specified argument " + "for %ordinal0 template parameter">; + def note_ovl_candidate_instantiation_depth : Note< + "candidate template ignored: substitution exceeded maximum template " + "instantiation depth">; + def note_ovl_candidate_underqualified : Note< + "candidate template ignored: cannot deduce a type for %0 that would " + "make %2 equal %1">; + def note_ovl_candidate_substitution_failure : Note< + "candidate template ignored: substitution failure%0%1">; + def note_ovl_candidate_disabled_by_enable_if : Note< + "candidate template ignored: disabled by %0%1">; + def note_ovl_candidate_disabled_by_requirement : Note< + "candidate template ignored: requirement '%0' was not satisfied%1">; + def note_ovl_candidate_has_pass_object_size_params: Note< + "candidate address cannot be taken because parameter %0 has " + "pass_object_size attribute">; + def err_diagnose_if_succeeded : Error<"%0">; + def warn_diagnose_if_succeeded : Warning<"%0">, InGroup, + ShowInSystemHeader; + def note_ovl_candidate_disabled_by_function_cond_attr : Note< + "candidate disabled: %0">; + def err_addrof_function_disabled_by_enable_if_attr : Error< + "cannot take address of function %0 because it has one or more " + "non-tautological enable_if conditions">; + def err_addrof_function_constraints_not_satisfied : Error< + "cannot take address of function %0 because its constraints are not " + "satisfied">; + def note_addrof_ovl_candidate_disabled_by_enable_if_attr : Note< + "candidate function made ineligible by enable_if">; + def note_ovl_candidate_deduced_mismatch : Note< + "candidate template ignored: deduced type " + "%diff{$ of %select{|element of }4%ordinal0 parameter does not match " + "adjusted type $ of %select{|element of }4argument" + "|of %select{|element of }4%ordinal0 parameter does not match " + "adjusted type of %select{|element of }4argument}1,2%3">; + def note_ovl_candidate_non_deduced_mismatch : Note< + "candidate template ignored: could not match %diff{$ against $|types}0,1">; + // This note is needed because the above note would sometimes print two + // different types with the same name. Remove this note when the above note + // can handle that case properly. + def note_ovl_candidate_non_deduced_mismatch_qualified : Note< + "candidate template ignored: could not match %q0 against %q1">; + + // Note that we don't treat templates differently for this diagnostic. + def note_ovl_candidate_arity : Note<"candidate " + "%sub{select_ovl_candidate_kind}0,1,2 not viable: " + "requires%select{ at least| at most|}3 %4 argument%s4, but %5 " + "%plural{1:was|:were}5 provided">; + + def note_ovl_candidate_arity_one : Note<"candidate " + "%sub{select_ovl_candidate_kind}0,1,2 not viable: " + "%select{requires at least|allows at most single|requires single}3 " + "argument %4, but %plural{0:no|:%5}5 arguments were provided">; + + def note_ovl_candidate_deleted : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 has been " + "%select{explicitly made unavailable|explicitly deleted|" + "implicitly deleted}3">; + + // Giving the index of the bad argument really clutters this message, and + // it's relatively unimportant because 1) it's generally obvious which + // argument(s) are of the given object type and 2) the fix is usually + // to complete the type, which doesn't involve changes to the call line + // anyway. If people complain, we can change it. + def note_ovl_candidate_bad_conv_incomplete : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "cannot convert argument of incomplete type " + "%diff{$ to $|to parameter type}3,4 for " + "%select{%ordinal6 argument|object argument}5" + "%select{|; dereference the argument with *|" + "; take the address of the argument with &|" + "; remove *|" + "; remove &}7">; + def note_ovl_candidate_bad_list_argument : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "%select{cannot convert initializer list|too few initializers in list" + "|too many initializers in list}7 argument to %4">; + def note_ovl_candidate_bad_overload : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "no overload of %4 matching %3 for %ordinal5 argument">; + def note_ovl_candidate_bad_conv : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "no known conversion " + "%diff{from $ to $|from argument type to parameter type}3,4 for " + "%select{%ordinal6 argument|object argument}5" + "%select{|; dereference the argument with *|" + "; take the address of the argument with &|" + "; remove *|" + "; remove &}7">; + def note_ovl_candidate_bad_arc_conv : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "cannot implicitly convert argument " + "%diff{of type $ to $|type to parameter type}3,4 for " + "%select{%ordinal6 argument|object argument}5 under ARC">; + def note_ovl_candidate_bad_value_category : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "expects an %select{lvalue|rvalue}5 for " + "%select{%ordinal4 argument|object argument}3">; + def note_ovl_candidate_bad_addrspace : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "cannot %select{pass pointer to|bind reference in}5 %3 " + "%select{as a pointer to|to object in}5 %4 in %ordinal6 " + "argument">; + def note_ovl_candidate_bad_addrspace_this : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "'this' object is in %3, but method expects object in %4">; + def note_ovl_candidate_bad_gc : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "%select{%ordinal7|'this'}6 argument (%3) has %select{no|__weak|__strong}4 " + "ownership, but parameter has %select{no|__weak|__strong}5 ownership">; + def note_ovl_candidate_bad_ownership : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "%select{%ordinal7|'this'}6 argument (%3) has " + "%select{no|__unsafe_unretained|__strong|__weak|__autoreleasing}4 ownership," + " but parameter has %select{no|__unsafe_unretained|__strong|__weak|" + "__autoreleasing}5 ownership">; + def note_ovl_candidate_bad_cvr_this : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "'this' argument has type %3, but method is not marked " + "%select{const|restrict|const or restrict|volatile|const or volatile|" + "volatile or restrict|const, volatile, or restrict}4">; + def note_ovl_candidate_bad_cvr : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "%ordinal5 argument (%3) would lose " + "%select{const|restrict|const and restrict|volatile|const and volatile|" + "volatile and restrict|const, volatile, and restrict}4 qualifier" + "%select{||s||s|s|s}4">; + def note_ovl_candidate_bad_unaligned : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "%ordinal5 argument (%3) would lose __unaligned qualifier">; + def note_ovl_candidate_bad_base_to_derived_conv : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "cannot %select{convert from|convert from|bind}3 " + "%select{base class pointer|superclass|base class object of type}3 %4 to " + "%select{derived class pointer|subclass|derived class reference}3 %5 for " + "%ordinal6 argument">; + def note_ovl_candidate_bad_target : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "call to " + "%select{__device__|__global__|__host__|__host__ __device__|invalid}3 function from" + " %select{__device__|__global__|__host__|__host__ __device__|invalid}4 function">; + def note_ovl_candidate_constraints_not_satisfied : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: constraints " + "not satisfied">; + def note_implicit_member_target_infer_collision : Note< + "implicit %sub{select_special_member_kind}0 inferred target collision: call to both " + "%select{__device__|__global__|__host__|__host__ __device__}1 and " + "%select{__device__|__global__|__host__|__host__ __device__}2 members">; + + def note_ambiguous_type_conversion: Note< + "because of ambiguity in conversion %diff{of $ to $|between types}0,1">; + def note_ovl_builtin_candidate : Note<"built-in candidate %0">; + def err_ovl_no_viable_function_in_init : Error< + "no matching constructor for initialization of %0">; + def err_ovl_no_conversion_in_cast : Error< + "cannot convert %1 to %2 without a conversion operator">; + def err_ovl_no_viable_conversion_in_cast : Error< + "no matching conversion for %select{|static_cast|reinterpret_cast|" + "dynamic_cast|C-style cast|functional-style cast|}0 from %1 to %2">; + def err_ovl_ambiguous_conversion_in_cast : Error< + "ambiguous conversion for %select{|static_cast|reinterpret_cast|" + "dynamic_cast|C-style cast|functional-style cast|}0 from %1 to %2">; + def err_ovl_deleted_conversion_in_cast : Error< + "%select{|static_cast|reinterpret_cast|dynamic_cast|C-style cast|" + "functional-style cast|}0 from %1 to %2 uses deleted function">; + def err_ovl_ambiguous_init : Error<"call to constructor of %0 is ambiguous">; + def err_ref_init_ambiguous : Error< + "reference initialization of type %0 with initializer of type %1 is ambiguous">; + def err_ovl_deleted_init : Error< + "call to deleted constructor of %0">; + def err_ovl_deleted_special_init : Error< + "call to implicitly-deleted %select{default constructor|copy constructor|" + "move constructor|copy assignment operator|move assignment operator|" + "destructor|function}0 of %1">; + def err_ovl_ambiguous_oper_unary : Error< + "use of overloaded operator '%0' is ambiguous (operand type %1)">; + def err_ovl_ambiguous_oper_binary : Error< + "use of overloaded operator '%0' is ambiguous (with operand types %1 and %2)">; + def ext_ovl_ambiguous_oper_binary_reversed : ExtWarn< + "ISO C++20 considers use of overloaded operator '%0' (with operand types %1 " + "and %2) to be ambiguous despite there being a unique best viable function" + "%select{ with non-reversed arguments|}3">, + InGroup>, SFINAEFailure; + def note_ovl_ambiguous_oper_binary_reversed_self : Note< + "ambiguity is between a regular call to this operator and a call with the " + "argument order reversed">; + def note_ovl_ambiguous_oper_binary_selected_candidate : Note< + "candidate function with non-reversed arguments">; + def note_ovl_ambiguous_oper_binary_reversed_candidate : Note< + "ambiguous candidate function with reversed arguments">; + def err_ovl_no_viable_oper : Error<"no viable overloaded '%0'">; + def note_assign_lhs_incomplete : Note<"type %0 is incomplete">; + def err_ovl_deleted_oper : Error< + "overload resolution selected deleted operator '%0'">; + def err_ovl_deleted_special_oper : Error< + "object of type %0 cannot be %select{constructed|copied|moved|assigned|" + "assigned|destroyed}1 because its %sub{select_special_member_kind}1 is " + "implicitly deleted">; + def err_ovl_deleted_comparison : Error< + "object of type %0 cannot be compared because its %1 is implicitly deleted">; + def err_ovl_rewrite_equalequal_not_bool : Error< + "return type %0 of selected 'operator==' function for rewritten " + "'%1' comparison is not 'bool'">; + def ext_ovl_rewrite_equalequal_not_bool : ExtWarn< + "ISO C++20 requires return type of selected 'operator==' function for " + "rewritten '%1' comparison to be 'bool', not %0">, + InGroup>, SFINAEFailure; + def err_ovl_no_viable_subscript : + Error<"no viable overloaded operator[] for type %0">; + def err_ovl_no_oper : + Error<"type %0 does not provide a %select{subscript|call}1 operator">; + def err_ovl_unresolvable : Error< + "reference to %select{overloaded|multiversioned}1 function could not be " + "resolved; did you mean to call it%select{| with no arguments}0?">; + def err_bound_member_function : Error< + "reference to non-static member function must be called" + "%select{|; did you mean to call it with no arguments?}0">; + def note_possible_target_of_call : Note<"possible target for call">; + + def err_ovl_no_viable_object_call : Error< + "no matching function for call to object of type %0">; + def err_ovl_ambiguous_object_call : Error< + "call to object of type %0 is ambiguous">; + def err_ovl_deleted_object_call : Error< + "call to deleted function call operator in type %0">; + def note_ovl_surrogate_cand : Note<"conversion candidate of type %0">; + def err_member_call_without_object : Error< + "call to non-static member function without an object argument">; + + // C++ Address of Overloaded Function + def err_addr_ovl_no_viable : Error< + "address of overloaded function %0 does not match required type %1">; + def err_addr_ovl_ambiguous : Error< + "address of overloaded function %0 is ambiguous">; + def err_addr_ovl_not_func_ptrref : Error< + "address of overloaded function %0 cannot be converted to type %1">; + def err_addr_ovl_no_qualifier : Error< + "cannot form member pointer of type %0 without '&' and class name">; + + } // let Deferrable + + // C++11 Literal Operators + def err_ovl_no_viable_literal_operator : Error< + "no matching literal operator for call to %0" + "%select{| with argument of type %2| with arguments of types %2 and %3}1" + "%select{| or 'const char *'}4" + "%select{|, and no matching literal operator template}5">; + + // C++ Template Declarations + def err_template_param_shadow : Error< + "declaration of %0 shadows template parameter">; + def ext_template_param_shadow : ExtWarn< + err_template_param_shadow.Text>, InGroup; + def note_template_param_here : Note<"template parameter is declared here">; + def warn_template_export_unsupported : Warning< + "exported templates are unsupported">; + def err_template_outside_namespace_or_class_scope : Error< + "templates can only be declared in namespace or class scope">; + def err_template_inside_local_class : Error< + "templates cannot be declared inside of a local class">; + def err_template_linkage : Error<"templates must have C++ linkage">; + def err_template_typedef : Error<"a typedef cannot be a template">; + def err_template_unnamed_class : Error< + "cannot declare a class template with no name">; + def err_template_param_list_different_arity : Error< + "%select{too few|too many}0 template parameters in template " + "%select{|template parameter }1redeclaration">; + def note_template_param_list_different_arity : Note< + "%select{too few|too many}0 template parameters in template template " + "argument">; + def note_template_prev_declaration : Note< + "previous template %select{declaration|template parameter}0 is here">; + def err_template_param_different_kind : Error< + "template parameter has a different kind in template " + "%select{|template parameter }0redeclaration">; + def note_template_param_different_kind : Note< + "template parameter has a different kind in template argument">; + + def err_invalid_decl_specifier_in_nontype_parm : Error< + "invalid declaration specifier in template non-type parameter">; + + def err_template_nontype_parm_different_type : Error< + "template non-type parameter has a different type %0 in template " + "%select{|template parameter }1redeclaration">; + + def note_template_nontype_parm_different_type : Note< + "template non-type parameter has a different type %0 in template argument">; + def note_template_nontype_parm_prev_declaration : Note< + "previous non-type template parameter with type %0 is here">; + def err_template_nontype_parm_bad_type : Error< + "a non-type template parameter cannot have type %0">; + def err_template_nontype_parm_bad_structural_type : Error< + "a non-type template parameter cannot have type %0 before C++20">; + def err_template_nontype_parm_incomplete : Error< + "non-type template parameter has incomplete type %0">; + def err_template_nontype_parm_not_literal : Error< + "non-type template parameter has non-literal type %0">; + def err_template_nontype_parm_rvalue_ref : Error< + "non-type template parameter has rvalue reference type %0">; + def err_template_nontype_parm_not_structural : Error< + "type %0 of non-type template parameter is not a structural type">; + def note_not_structural_non_public : Note< + "%0 is not a structural type because it has a " + "%select{non-static data member|base class}1 that is not public">; + def note_not_structural_mutable_field : Note< + "%0 is not a structural type because it has a mutable " + "non-static data member">; + def note_not_structural_rvalue_ref_field : Note< + "%0 is not a structural type because it has a non-static data member " + "of rvalue reference type">; + def note_not_structural_subobject : Note< + "%0 is not a structural type because it has a " + "%select{non-static data member|base class}1 of non-structural type %2">; + def warn_cxx17_compat_template_nontype_parm_type : Warning< + "non-type template parameter of type %0 is incompatible with " + "C++ standards before C++20">, + DefaultIgnore, InGroup; + def warn_cxx14_compat_template_nontype_parm_auto_type : Warning< + "non-type template parameters declared with %0 are incompatible with C++ " + "standards before C++17">, + DefaultIgnore, InGroup; + def err_template_param_default_arg_redefinition : Error< + "template parameter redefines default argument">; + def note_template_param_prev_default_arg : Note< + "previous default template argument defined here">; + def err_template_param_default_arg_missing : Error< + "template parameter missing a default argument">; + def ext_template_parameter_default_in_function_template : ExtWarn< + "default template arguments for a function template are a C++11 extension">, + InGroup; + def warn_cxx98_compat_template_parameter_default_in_function_template : Warning< + "default template arguments for a function template are incompatible with C++98">, + InGroup, DefaultIgnore; + def err_template_parameter_default_template_member : Error< + "cannot add a default template argument to the definition of a member of a " + "class template">; + def err_template_parameter_default_friend_template : Error< + "default template argument not permitted on a friend template">; + def err_template_template_parm_no_parms : Error< + "template template parameter must have its own template parameters">; + + def ext_variable_template : ExtWarn<"variable templates are a C++14 extension">, + InGroup; + def warn_cxx11_compat_variable_template : Warning< + "variable templates are incompatible with C++ standards before C++14">, + InGroup, DefaultIgnore; + def err_template_variable_noparams : Error< + "extraneous 'template<>' in declaration of variable %0">; + def err_template_member : Error<"member %0 declared as a template">; + def err_template_member_noparams : Error< + "extraneous 'template<>' in declaration of member %0">; + def err_template_tag_noparams : Error< + "extraneous 'template<>' in declaration of %0 %1">; + + def warn_cxx17_compat_adl_only_template_id : Warning< + "use of function template name with no prior function template " + "declaration in function call with explicit template arguments " + "is incompatible with C++ standards before C++20">, + InGroup, DefaultIgnore; + def ext_adl_only_template_id : ExtWarn< + "use of function template name with no prior declaration in function call " + "with explicit template arguments is a C++20 extension">, InGroup; + + // C++ Template Argument Lists + def err_template_missing_args : Error< + "use of " + "%select{class template|function template|variable template|alias template|" + "template template parameter|concept|template}0 %1 requires template " + "arguments">; + def err_template_arg_list_different_arity : Error< + "%select{too few|too many}0 template arguments for " + "%select{class template|function template|variable template|alias template|" + "template template parameter|concept|template}1 %2">; + def note_template_decl_here : Note<"template is declared here">; + def err_template_arg_must_be_type : Error< + "template argument for template type parameter must be a type">; + def err_template_arg_must_be_type_suggest : Error< + "template argument for template type parameter must be a type; " + "did you forget 'typename'?">; + def ext_ms_template_type_arg_missing_typename : ExtWarn< + "template argument for template type parameter must be a type; " + "omitted 'typename' is a Microsoft extension">, + InGroup; + def err_template_arg_must_be_expr : Error< + "template argument for non-type template parameter must be an expression">; + def err_template_arg_nontype_ambig : Error< + "template argument for non-type template parameter is treated as function type %0">; + def err_template_arg_must_be_template : Error< + "template argument for template template parameter must be a class template%select{| or type alias template}0">; + def ext_template_arg_local_type : ExtWarn< + "template argument uses local type %0">, InGroup; + def ext_template_arg_unnamed_type : ExtWarn< + "template argument uses unnamed type">, InGroup; + def warn_cxx98_compat_template_arg_local_type : Warning< + "local type %0 as template argument is incompatible with C++98">, + InGroup, DefaultIgnore; + def warn_cxx98_compat_template_arg_unnamed_type : Warning< + "unnamed type as template argument is incompatible with C++98">, + InGroup, DefaultIgnore; + def note_template_unnamed_type_here : Note< + "unnamed type used in template argument was declared here">; + def err_template_arg_overload_type : Error< + "template argument is the type of an unresolved overloaded function">; + def err_template_arg_not_valid_template : Error< + "template argument does not refer to a class or alias template, or template " + "template parameter">; + def note_template_arg_refers_here_func : Note< + "template argument refers to function template %0, here">; + def err_template_arg_template_params_mismatch : Error< + "template template argument has different template parameters than its " + "corresponding template template parameter">; + def err_template_arg_not_integral_or_enumeral : Error< + "non-type template argument of type %0 must have an integral or enumeration" + " type">; + def err_template_arg_not_ice : Error< + "non-type template argument of type %0 is not an integral constant " + "expression">; + def err_template_arg_not_address_constant : Error< + "non-type template argument of type %0 is not a constant expression">; + def warn_cxx98_compat_template_arg_null : Warning< + "use of null pointer as non-type template argument is incompatible with " + "C++98">, InGroup, DefaultIgnore; + def err_template_arg_untyped_null_constant : Error< + "null non-type template argument must be cast to template parameter type %0">; + def err_template_arg_wrongtype_null_constant : Error< + "null non-type template argument of type %0 does not match template parameter " + "of type %1">; + def err_non_type_template_parm_type_deduction_failure : Error< + "non-type template parameter %0 with type %1 has incompatible initializer of type %2">; + def err_deduced_non_type_template_arg_type_mismatch : Error< + "deduced non-type template argument does not have the same type as the " + "corresponding template parameter%diff{ ($ vs $)|}0,1">; + def err_non_type_template_arg_subobject : Error< + "non-type template argument refers to subobject '%0'">; + def err_non_type_template_arg_addr_label_diff : Error< + "template argument / label address difference / what did you expect?">; + def err_non_type_template_arg_unsupported : Error< + "sorry, non-type template argument of type %0 is not yet supported">; + def err_template_arg_not_convertible : Error< + "non-type template argument of type %0 cannot be converted to a value " + "of type %1">; + def warn_template_arg_negative : Warning< + "non-type template argument with value '%0' converted to '%1' for unsigned " + "template parameter of type %2">, InGroup, DefaultIgnore; + def warn_template_arg_too_large : Warning< + "non-type template argument value '%0' truncated to '%1' for " + "template parameter of type %2">, InGroup, DefaultIgnore; + def err_template_arg_no_ref_bind : Error< + "non-type template parameter of reference type " + "%diff{$ cannot bind to template argument of type $" + "|cannot bind to template of incompatible argument type}0,1">; + def err_template_arg_ref_bind_ignores_quals : Error< + "reference binding of non-type template parameter " + "%diff{of type $ to template argument of type $|to template argument}0,1 " + "ignores qualifiers">; + def err_template_arg_not_decl_ref : Error< + "non-type template argument does not refer to any declaration">; + def err_template_arg_not_address_of : Error< + "non-type template argument for template parameter of pointer type %0 must " + "have its address taken">; + def err_template_arg_address_of_non_pointer : Error< + "address taken in non-type template argument for template parameter of " + "reference type %0">; + def err_template_arg_reference_var : Error< + "non-type template argument of reference type %0 is not an object">; + def err_template_arg_field : Error< + "non-type template argument refers to non-static data member %0">; + def err_template_arg_method : Error< + "non-type template argument refers to non-static member function %0">; + def err_template_arg_object_no_linkage : Error< + "non-type template argument refers to %select{function|object}0 %1 that " + "does not have linkage">; + def warn_cxx98_compat_template_arg_object_internal : Warning< + "non-type template argument referring to %select{function|object}0 %1 with " + "internal linkage is incompatible with C++98">, + InGroup, DefaultIgnore; + def ext_template_arg_object_internal : ExtWarn< + "non-type template argument referring to %select{function|object}0 %1 with " + "internal linkage is a C++11 extension">, InGroup; + def err_template_arg_thread_local : Error< + "non-type template argument refers to thread-local object">; + def note_template_arg_internal_object : Note< + "non-type template argument refers to %select{function|object}0 here">; + def note_template_arg_refers_here : Note< + "non-type template argument refers here">; + def err_template_arg_not_object_or_func : Error< + "non-type template argument does not refer to an object or function">; + def err_template_arg_not_pointer_to_member_form : Error< + "non-type template argument is not a pointer to member constant">; + def err_template_arg_member_ptr_base_derived_not_supported : Error< + "sorry, non-type template argument of pointer-to-member type %1 that refers " + "to member %q0 of a different class is not supported yet">; + def ext_template_arg_extra_parens : ExtWarn< + "address non-type template argument cannot be surrounded by parentheses">; + def warn_cxx98_compat_template_arg_extra_parens : Warning< + "redundant parentheses surrounding address non-type template argument are " + "incompatible with C++98">, InGroup, DefaultIgnore; + def err_pointer_to_member_type : Error< + "invalid use of pointer to member type after %select{.*|->*}0">; + def err_pointer_to_member_call_drops_quals : Error< + "call to pointer to member function of type %0 drops '%1' qualifier%s2">; + def err_pointer_to_member_oper_value_classify: Error< + "pointer-to-member function type %0 can only be called on an " + "%select{rvalue|lvalue}1">; + def ext_pointer_to_const_ref_member_on_rvalue : Extension< + "invoking a pointer to a 'const &' member function on an rvalue is a C++20 extension">, + InGroup, SFINAEFailure; + def warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue : Warning< + "invoking a pointer to a 'const &' member function on an rvalue is " + "incompatible with C++ standards before C++20">, + InGroup, DefaultIgnore; + def ext_ms_deref_template_argument: ExtWarn< + "non-type template argument containing a dereference operation is a " + "Microsoft extension">, InGroup; + def ext_ms_delayed_template_argument: ExtWarn< + "using the undeclared type %0 as a default template argument is a " + "Microsoft extension">, InGroup; + def err_template_arg_deduced_incomplete_pack : Error< + "deduced incomplete pack %0 for template parameter %1">; + + // C++ template specialization + def err_template_spec_unknown_kind : Error< + "can only provide an explicit specialization for a class template, function " + "template, variable template, or a member function, static data member, " + "%select{or member class|member class, or member enumeration}0 of a " + "class template">; + def note_specialized_entity : Note< + "explicitly specialized declaration is here">; + def note_explicit_specialization_declared_here : Note< + "explicit specialization declared here">; + def err_template_spec_decl_function_scope : Error< + "explicit specialization of %0 in function scope">; + def err_template_spec_decl_friend : Error< + "cannot declare an explicit specialization in a friend">; + def err_template_spec_redecl_out_of_scope : Error< + "%select{class template|class template partial|variable template|" + "variable template partial|function template|member " + "function|static data member|member class|member enumeration}0 " + "specialization of %1 not in %select{a namespace enclosing %2|" + "class %2 or an enclosing namespace}3">; + def ext_ms_template_spec_redecl_out_of_scope: ExtWarn< + "%select{class template|class template partial|variable template|" + "variable template partial|function template|member " + "function|static data member|member class|member enumeration}0 " + "specialization of %1 not in %select{a namespace enclosing %2|" + "class %2 or an enclosing namespace}3 " + "is a Microsoft extension">, InGroup; + def err_template_spec_redecl_global_scope : Error< + "%select{class template|class template partial|variable template|" + "variable template partial|function template|member " + "function|static data member|member class|member enumeration}0 " + "specialization of %1 must occur at global scope">; + def err_spec_member_not_instantiated : Error< + "specialization of member %q0 does not specialize an instantiated member">; + def note_specialized_decl : Note<"attempt to specialize declaration here">; + def err_specialization_after_instantiation : Error< + "explicit specialization of %0 after instantiation">; + def note_instantiation_required_here : Note< + "%select{implicit|explicit}0 instantiation first required here">; + def err_template_spec_friend : Error< + "template specialization declaration cannot be a friend">; + def err_template_spec_default_arg : Error< + "default argument not permitted on an explicit " + "%select{instantiation|specialization}0 of function %1">; + def err_not_class_template_specialization : Error< + "cannot specialize a %select{dependent template|template template " + "parameter}0">; + def ext_explicit_specialization_storage_class : ExtWarn< + "explicit specialization cannot have a storage class">; + def err_explicit_specialization_inconsistent_storage_class : Error< + "explicit specialization has extraneous, inconsistent storage class " + "'%select{none|extern|static|__private_extern__|auto|register}0'">; + def err_dependent_function_template_spec_no_match : Error< + "no candidate function template was found for dependent" + " friend function template specialization">; + def note_dependent_function_template_spec_discard_reason : Note< + "candidate ignored: %select{not a function template" + "|not a member of the enclosing namespace;" + " did you mean to explicitly qualify the specialization?}0">; + + // C++ class template specializations and out-of-line definitions + def err_template_spec_needs_header : Error< + "template specialization requires 'template<>'">; + def err_template_spec_needs_template_parameters : Error< + "template specialization or definition requires a template parameter list " + "corresponding to the nested type %0">; + def err_template_param_list_matches_nontemplate : Error< + "template parameter list matching the non-templated nested type %0 should " + "be empty ('template<>')">; + def err_alias_template_extra_headers : Error< + "extraneous template parameter list in alias template declaration">; + def err_template_spec_extra_headers : Error< + "extraneous template parameter list in template specialization or " + "out-of-line template definition">; + def warn_template_spec_extra_headers : Warning< + "extraneous template parameter list in template specialization">; + def note_explicit_template_spec_does_not_need_header : Note< + "'template<>' header not required for explicitly-specialized class %0 " + "declared here">; + def err_template_qualified_declarator_no_match : Error< + "nested name specifier '%0' for declaration does not refer into a class, " + "class template or class template partial specialization">; + def err_specialize_member_of_template : Error< + "cannot specialize %select{|(with 'template<>') }0a member of an " + "unspecialized template">; + + // C++ Class Template Partial Specialization + def err_default_arg_in_partial_spec : Error< + "default template argument in a class template partial specialization">; + def err_dependent_non_type_arg_in_partial_spec : Error< + "type of specialized non-type template argument depends on a template " + "parameter of the partial specialization">; + def note_dependent_non_type_default_arg_in_partial_spec : Note< + "template parameter is used in default argument declared here">; + def err_dependent_typed_non_type_arg_in_partial_spec : Error< + "non-type template argument specializes a template parameter with " + "dependent type %0">; + def err_partial_spec_args_match_primary_template : Error< + "%select{class|variable}0 template partial specialization does not " + "specialize any template argument; to %select{declare|define}1 the " + "primary template, remove the template argument list">; + def ext_partial_spec_not_more_specialized_than_primary : ExtWarn< + "%select{class|variable}0 template partial specialization is not " + "more specialized than the primary template">, DefaultError, + InGroup>; + def note_partial_spec_not_more_specialized_than_primary : Note<"%0">; + def ext_partial_specs_not_deducible : ExtWarn< + "%select{class|variable}0 template partial specialization contains " + "%select{a template parameter|template parameters}1 that cannot be " + "deduced; this partial specialization will never be used">, + DefaultError, InGroup>; + def note_non_deducible_parameter : Note< + "non-deducible template parameter %0">; + def err_partial_spec_ordering_ambiguous : Error< + "ambiguous partial specializations of %0">; + def note_partial_spec_match : Note<"partial specialization matches %0">; + def err_partial_spec_redeclared : Error< + "class template partial specialization %0 cannot be redeclared">; + def note_partial_specialization_declared_here : Note< + "explicit specialization declared here">; + def note_prev_partial_spec_here : Note< + "previous declaration of class template partial specialization %0 is here">; + def err_partial_spec_fully_specialized : Error< + "partial specialization of %0 does not use any of its template parameters">; + + // C++ Variable Template Partial Specialization + def err_var_partial_spec_redeclared : Error< + "variable template partial specialization %0 cannot be redefined">; + def note_var_prev_partial_spec_here : Note< + "previous declaration of variable template partial specialization is here">; + def err_var_spec_no_template : Error< + "no variable template matches%select{| partial}0 specialization">; + def err_var_spec_no_template_but_method : Error< + "no variable template matches specialization; " + "did you mean to use %0 as function template instead?">; + + // C++ Function template specializations + def err_function_template_spec_no_match : Error< + "no function template matches function template specialization %0">; + def err_function_template_spec_ambiguous : Error< + "function template specialization %0 ambiguously refers to more than one " + "function template; explicitly specify%select{| additional}1 template " + "arguments to identify a particular function template">; + def note_function_template_spec_matched : Note< + "function template %q0 matches specialization %1">; + def err_function_template_partial_spec : Error< + "function template partial specialization is not allowed">; + + // C++ Template Instantiation + def err_template_recursion_depth_exceeded : Error< + "recursive template instantiation exceeded maximum depth of %0">, + DefaultFatal, NoSFINAE; + def note_template_recursion_depth : Note< + "use -ftemplate-depth=N to increase recursive template instantiation depth">; + + def err_template_instantiate_within_definition : Error< + "%select{implicit|explicit}0 instantiation of template %1 within its" + " own definition">; + def err_template_instantiate_undefined : Error< + "%select{implicit|explicit}0 instantiation of undefined template %1">; + def err_implicit_instantiate_member_undefined : Error< + "implicit instantiation of undefined member %0">; + def note_template_class_instantiation_was_here : Note< + "class template %0 was instantiated here">; + def note_template_class_explicit_specialization_was_here : Note< + "class template %0 was explicitly specialized here">; + def note_template_class_instantiation_here : Note< + "in instantiation of template class %q0 requested here">; + def note_template_member_class_here : Note< + "in instantiation of member class %q0 requested here">; + def note_template_member_function_here : Note< + "in instantiation of member function %q0 requested here">; + def note_function_template_spec_here : Note< + "in instantiation of function template specialization %q0 requested here">; + def note_template_static_data_member_def_here : Note< + "in instantiation of static data member %q0 requested here">; + def note_template_variable_def_here : Note< + "in instantiation of variable template specialization %q0 requested here">; + def note_template_enum_def_here : Note< + "in instantiation of enumeration %q0 requested here">; + def note_template_nsdmi_here : Note< + "in instantiation of default member initializer %q0 requested here">; + def note_template_type_alias_instantiation_here : Note< + "in instantiation of template type alias %0 requested here">; + def note_template_exception_spec_instantiation_here : Note< + "in instantiation of exception specification for %0 requested here">; + def note_template_requirement_instantiation_here : Note< + "in instantiation of requirement here">; + def warn_var_template_missing : Warning<"instantiation of variable %q0 " + "required here, but no definition is available">, + InGroup; + def warn_func_template_missing : Warning<"instantiation of function %q0 " + "required here, but no definition is available">, + InGroup, DefaultIgnore; + def note_forward_template_decl : Note< + "forward declaration of template entity is here">; + def note_inst_declaration_hint : Note<"add an explicit instantiation " + "declaration to suppress this warning if %q0 is explicitly instantiated in " + "another translation unit">; + def note_evaluating_exception_spec_here : Note< + "in evaluation of exception specification for %q0 needed here">; + + def note_default_arg_instantiation_here : Note< + "in instantiation of default argument for '%0' required here">; + def note_default_function_arg_instantiation_here : Note< + "in instantiation of default function argument expression " + "for '%0' required here">; + def note_explicit_template_arg_substitution_here : Note< + "while substituting explicitly-specified template arguments into function " + "template %0 %1">; + def note_function_template_deduction_instantiation_here : Note< + "while substituting deduced template arguments into function template %0 " + "%1">; + def note_deduced_template_arg_substitution_here : Note< + "during template argument deduction for %select{class|variable}0 template " + "%select{partial specialization |}1%2 %3">; + def note_prior_template_arg_substitution : Note< + "while substituting prior template arguments into %select{non-type|template}0" + " template parameter%1 %2">; + def note_template_default_arg_checking : Note< + "while checking a default template argument used here">; + def note_concept_specialization_here : Note< + "while checking the satisfaction of concept '%0' requested here">; + def note_nested_requirement_here : Note< + "while checking the satisfaction of nested requirement requested here">; + def note_checking_constraints_for_template_id_here : Note< + "while checking constraint satisfaction for template '%0' required here">; + def note_checking_constraints_for_var_spec_id_here : Note< + "while checking constraint satisfaction for variable template " + "partial specialization '%0' required here">; + def note_checking_constraints_for_class_spec_id_here : Note< + "while checking constraint satisfaction for class template partial " + "specialization '%0' required here">; + def note_checking_constraints_for_function_here : Note< + "while checking constraint satisfaction for function '%0' required here">; + def note_constraint_substitution_here : Note< + "while substituting template arguments into constraint expression here">; + def note_constraint_normalization_here : Note< + "while calculating associated constraint of template '%0' here">; + def note_parameter_mapping_substitution_here : Note< + "while substituting into concept arguments here; substitution failures not " + "allowed in concept arguments">; + def note_instantiation_contexts_suppressed : Note< + "(skipping %0 context%s0 in backtrace; use -ftemplate-backtrace-limit=0 to " + "see all)">; + + def err_field_instantiates_to_function : Error< + "data member instantiated with function type %0">; + def err_variable_instantiates_to_function : Error< + "%select{variable|static data member}0 instantiated with function type %1">; + def err_nested_name_spec_non_tag : Error< + "type %0 cannot be used prior to '::' because it has no members">; + + def err_using_pack_expansion_empty : Error< + "%select{|member}0 using declaration %1 instantiates to an empty pack">; + + // C++ Explicit Instantiation + def err_explicit_instantiation_duplicate : Error< + "duplicate explicit instantiation of %0">; + def ext_explicit_instantiation_duplicate : ExtWarn< + "duplicate explicit instantiation of %0 ignored as a Microsoft extension">, + InGroup; + def note_previous_explicit_instantiation : Note< + "previous explicit instantiation is here">; + def warn_explicit_instantiation_after_specialization : Warning< + "explicit instantiation of %0 that occurs after an explicit " + "specialization has no effect">, + InGroup>; + def note_previous_template_specialization : Note< + "previous template specialization is here">; + def err_explicit_instantiation_nontemplate_type : Error< + "explicit instantiation of non-templated type %0">; + def note_nontemplate_decl_here : Note< + "non-templated declaration is here">; + def err_explicit_instantiation_in_class : Error< + "explicit instantiation of %0 in class scope">; + def err_explicit_instantiation_out_of_scope : Error< + "explicit instantiation of %0 not in a namespace enclosing %1">; + def err_explicit_instantiation_must_be_global : Error< + "explicit instantiation of %0 must occur at global scope">; + def warn_explicit_instantiation_out_of_scope_0x : Warning< + "explicit instantiation of %0 not in a namespace enclosing %1">, + InGroup, DefaultIgnore; + def warn_explicit_instantiation_must_be_global_0x : Warning< + "explicit instantiation of %0 must occur at global scope">, + InGroup, DefaultIgnore; + + def err_explicit_instantiation_requires_name : Error< + "explicit instantiation declaration requires a name">; + def err_explicit_instantiation_of_typedef : Error< + "explicit instantiation of typedef %0">; + def err_explicit_instantiation_storage_class : Error< + "explicit instantiation cannot have a storage class">; + def err_explicit_instantiation_internal_linkage : Error< + "explicit instantiation declaration of %0 with internal linkage">; + def err_explicit_instantiation_not_known : Error< + "explicit instantiation of %0 does not refer to a function template, " + "variable template, member function, member class, or static data member">; + def note_explicit_instantiation_here : Note< + "explicit instantiation refers here">; + def err_explicit_instantiation_data_member_not_instantiated : Error< + "explicit instantiation refers to static data member %q0 that is not an " + "instantiation">; + def err_explicit_instantiation_member_function_not_instantiated : Error< + "explicit instantiation refers to member function %q0 that is not an " + "instantiation">; + def err_explicit_instantiation_ambiguous : Error< + "partial ordering for explicit instantiation of %0 is ambiguous">; + def note_explicit_instantiation_candidate : Note< + "explicit instantiation candidate function %q0 template here %1">; + def err_explicit_instantiation_inline : Error< + "explicit instantiation cannot be 'inline'">; + def warn_explicit_instantiation_inline_0x : Warning< + "explicit instantiation cannot be 'inline'">, InGroup, + DefaultIgnore; + def err_explicit_instantiation_constexpr : Error< + "explicit instantiation cannot be 'constexpr'">; + def ext_explicit_instantiation_without_qualified_id : Extension< + "qualifier in explicit instantiation of %q0 requires a template-id " + "(a typedef is not permitted)">; + def err_explicit_instantiation_without_template_id : Error< + "explicit instantiation of %q0 must specify a template argument list">; + def err_explicit_instantiation_unqualified_wrong_namespace : Error< + "explicit instantiation of %q0 must occur in namespace %1">; + def warn_explicit_instantiation_unqualified_wrong_namespace_0x : Warning< + "explicit instantiation of %q0 must occur in namespace %1">, + InGroup, DefaultIgnore; + def err_explicit_instantiation_undefined_member : Error< + "explicit instantiation of undefined %select{member class|member function|" + "static data member}0 %1 of class template %2">; + def err_explicit_instantiation_undefined_func_template : Error< + "explicit instantiation of undefined function template %0">; + def err_explicit_instantiation_undefined_var_template : Error< + "explicit instantiation of undefined variable template %q0">; + def err_explicit_instantiation_declaration_after_definition : Error< + "explicit instantiation declaration (with 'extern') follows explicit " + "instantiation definition (without 'extern')">; + def note_explicit_instantiation_definition_here : Note< + "explicit instantiation definition is here">; + def err_invalid_var_template_spec_type : Error<"type %2 " + "of %select{explicit instantiation|explicit specialization|" + "partial specialization|redeclaration}0 of %1 does not match" + " expected type %3">; + def err_mismatched_exception_spec_explicit_instantiation : Error< + "exception specification in explicit instantiation does not match " + "instantiated one">; + def ext_mismatched_exception_spec_explicit_instantiation : ExtWarn< + err_mismatched_exception_spec_explicit_instantiation.Text>, + InGroup; + def err_explicit_instantiation_dependent : Error< + "explicit instantiation has dependent template arguments">; + + // C++ typename-specifiers + def err_typename_nested_not_found : Error<"no type named %0 in %1">; + def err_typename_nested_not_found_enable_if : Error< + "no type named 'type' in %0; 'enable_if' cannot be used to disable " + "this declaration">; + def err_typename_nested_not_found_requirement : Error< + "failed requirement '%0'; 'enable_if' cannot be used to disable this " + "declaration">; + def err_typename_nested_not_type : Error< + "typename specifier refers to non-type member %0 in %1">; + def err_typename_not_type : Error< + "typename specifier refers to non-type %0">; + def note_typename_member_refers_here : Note< + "referenced member %0 is declared here">; + def note_typename_refers_here : Note< + "referenced %0 is declared here">; + def err_typename_missing : Error< + "missing 'typename' prior to dependent type name '%0%1'">; + def err_typename_missing_template : Error< + "missing 'typename' prior to dependent type template name '%0%1'">; + def ext_typename_missing : ExtWarn< + "missing 'typename' prior to dependent type name '%0%1'">, + InGroup>; + def ext_typename_outside_of_template : ExtWarn< + "'typename' occurs outside of a template">, InGroup; + def warn_cxx98_compat_typename_outside_of_template : Warning< + "use of 'typename' outside of a template is incompatible with C++98">, + InGroup, DefaultIgnore; + def err_typename_refers_to_using_value_decl : Error< + "typename specifier refers to a dependent using declaration for a value " + "%0 in %1">; + def note_using_value_decl_missing_typename : Note< + "add 'typename' to treat this using declaration as a type">; + + def err_template_kw_refers_to_non_template : Error< + "%0%select{| following the 'template' keyword}1 " + "does not refer to a template">; + def note_template_kw_refers_to_non_template : Note< + "declared as a non-template here">; + def err_template_kw_refers_to_dependent_non_template : Error< + "%0%select{| following the 'template' keyword}1 " + "cannot refer to a dependent template">; + def err_template_kw_refers_to_class_template : Error< + "'%0%1' instantiated to a class template, not a function template">; + def note_referenced_class_template : Note< + "class template declared here">; + def err_template_kw_missing : Error< + "missing 'template' keyword prior to dependent template name '%0%1'">; + def ext_template_outside_of_template : ExtWarn< + "'template' keyword outside of a template">, InGroup; + def warn_cxx98_compat_template_outside_of_template : Warning< + "use of 'template' keyword outside of a template is incompatible with C++98">, + InGroup, DefaultIgnore; + + def err_non_type_template_in_nested_name_specifier : Error< + "qualified name refers into a specialization of %select{function|variable}0 " + "template %1">; + def err_template_id_not_a_type : Error< + "template name refers to non-type template %0">; + def note_template_declared_here : Note< + "%select{function template|class template|variable template" + "|type alias template|template template parameter}0 " + "%1 declared here">; + def err_template_expansion_into_fixed_list : Error< + "pack expansion used as argument for non-pack parameter of %select{alias " + "template|concept}0">; + def note_parameter_type : Note< + "parameter of type %0 is declared here">; + + // C++11 Variadic Templates + def err_template_param_pack_default_arg : Error< + "template parameter pack cannot have a default argument">; + def err_template_param_pack_must_be_last_template_parameter : Error< + "template parameter pack must be the last template parameter">; + + def err_template_parameter_pack_non_pack : Error< + "%select{template type|non-type template|template template}0 parameter" + "%select{| pack}1 conflicts with previous %select{template type|" + "non-type template|template template}0 parameter%select{ pack|}1">; + def note_template_parameter_pack_non_pack : Note< + "%select{template type|non-type template|template template}0 parameter" + "%select{| pack}1 does not match %select{template type|non-type template" + "|template template}0 parameter%select{ pack|}1 in template argument">; + def note_template_parameter_pack_here : Note< + "previous %select{template type|non-type template|template template}0 " + "parameter%select{| pack}1 declared here">; + + def err_unexpanded_parameter_pack : Error< + "%select{expression|base type|declaration type|data member type|bit-field " + "size|static assertion|fixed underlying type|enumerator value|" + "using declaration|friend declaration|qualifier|initializer|default argument|" + "non-type template parameter type|exception type|partial specialization|" + "__if_exists name|__if_not_exists name|lambda|block|type constraint|" + "requirement|requires clause}0 " + "contains%plural{0: an|:}1 unexpanded parameter pack" + "%plural{0:|1: %2|2:s %2 and %3|:s %2, %3, ...}1">; + + def err_pack_expansion_without_parameter_packs : Error< + "pack expansion does not contain any unexpanded parameter packs">; + def err_pack_expansion_length_conflict : Error< + "pack expansion contains parameter packs %0 and %1 that have different " + "lengths (%2 vs. %3)">; + def err_pack_expansion_length_conflict_multilevel : Error< + "pack expansion contains parameter pack %0 that has a different " + "length (%1 vs. %2) from outer parameter packs">; + def err_pack_expansion_length_conflict_partial : Error< + "pack expansion contains parameter pack %0 that has a different " + "length (at least %1 vs. %2) from outer parameter packs">; + def err_pack_expansion_member_init : Error< + "pack expansion for initialization of member %0">; + + def err_function_parameter_pack_without_parameter_packs : Error< + "type %0 of function parameter pack does not contain any unexpanded " + "parameter packs">; + def err_ellipsis_in_declarator_not_parameter : Error< + "only function and template parameters can be parameter packs">; + + def err_sizeof_pack_no_pack_name : Error< + "%0 does not refer to the name of a parameter pack">; + + def err_fold_expression_packs_both_sides : Error< + "binary fold expression has unexpanded parameter packs in both operands">; + def err_fold_expression_empty : Error< + "unary fold expression has empty expansion for operator '%0' " + "with no fallback value">; + def err_fold_expression_bad_operand : Error< + "expression not permitted as operand of fold expression">; + def err_fold_expression_limit_exceeded: Error< + "instantiating fold expression with %0 arguments exceeded expression nesting " + "limit of %1">, DefaultFatal, NoSFINAE; + + def err_unexpected_typedef : Error< + "unexpected type name %0: expected expression">; + def err_unexpected_namespace : Error< + "unexpected namespace name %0: expected expression">; + def err_undeclared_var_use : Error<"use of undeclared identifier %0">; + def ext_undeclared_unqual_id_with_dependent_base : ExtWarn< + "use of undeclared identifier %0; " + "unqualified lookup into dependent bases of class template %1 is a Microsoft extension">, + InGroup; + def err_found_in_dependent_base : Error< + "explicit qualification required to use member %0 from dependent base class">; + def ext_found_in_dependent_base : ExtWarn<"use of member %0 " + "found via unqualified lookup into dependent bases of class templates is a " + "Microsoft extension">, InGroup; + def err_found_later_in_class : Error<"member %0 used before its declaration">; + def ext_found_later_in_class : ExtWarn< + "use of member %0 before its declaration is a Microsoft extension">, + InGroup; + def note_dependent_member_use : Note< + "must qualify identifier to find this declaration in dependent base class">; + def err_not_found_by_two_phase_lookup : Error<"call to function %0 that is neither " + "visible in the template definition nor found by argument-dependent lookup">; + def note_not_found_by_two_phase_lookup : Note<"%0 should be declared prior to the " + "call site%select{| or in %2| or in an associated namespace of one of its arguments}1">; + def err_undeclared_use : Error<"use of undeclared %0">; + def warn_deprecated : Warning<"%0 is deprecated">, + InGroup; + def note_from_diagnose_if : Note<"from 'diagnose_if' attribute on %0:">; + def warn_property_method_deprecated : + Warning<"property access is using %0 method which is deprecated">, + InGroup; + def warn_deprecated_message : Warning<"%0 is deprecated: %1">, + InGroup; + def warn_deprecated_anonymous_namespace : Warning< + "'deprecated' attribute on anonymous namespace ignored">, + InGroup; + def warn_deprecated_fwdclass_message : Warning< + "%0 may be deprecated because the receiver type is unknown">, + InGroup; + def warn_deprecated_def : Warning< + "implementing deprecated %select{method|class|category}0">, + InGroup, DefaultIgnore; + def warn_unavailable_def : Warning< + "implementing unavailable method">, + InGroup, DefaultIgnore; + def err_unavailable : Error<"%0 is unavailable">; + def err_property_method_unavailable : + Error<"property access is using %0 method which is unavailable">; + def err_unavailable_message : Error<"%0 is unavailable: %1">; + def warn_unavailable_fwdclass_message : Warning< + "%0 may be unavailable because the receiver type is unknown">, + InGroup; + def note_availability_specified_here : Note< + "%0 has been explicitly marked " + "%select{unavailable|deleted|deprecated}1 here">; + def note_partial_availability_specified_here : Note< + "%0 has been marked as being introduced in %1 %2 here, " + "but the deployment target is %1 %3">; + def note_implicitly_deleted : Note< + "explicitly defaulted function was implicitly deleted here">; + def warn_not_enough_argument : Warning< + "not enough variable arguments in %0 declaration to fit a sentinel">, + InGroup; + def warn_missing_sentinel : Warning < + "missing sentinel in %select{function call|method dispatch|block call}0">, + InGroup; + def note_sentinel_here : Note< + "%select{function|method|block}0 has been explicitly marked sentinel here">; + def warn_missing_prototype : Warning< + "no previous prototype for function %0">, + InGroup>, DefaultIgnore; + def note_declaration_not_a_prototype : Note< + "this declaration is not a prototype; add %select{'void'|parameter declarations}0 " + "to make it %select{a prototype for a zero-parameter function|one}0">; + def warn_strict_prototypes : Warning< + "this %select{function declaration is not|block declaration is not|" + "old-style function definition is not preceded by}0 a prototype">, + InGroup>, DefaultIgnore; + def warn_missing_variable_declarations : Warning< + "no previous extern declaration for non-static variable %0">, + InGroup>, DefaultIgnore; + def note_static_for_internal_linkage : Note< + "declare 'static' if the %select{variable|function}0 is not intended to be " + "used outside of this translation unit">; + def err_static_data_member_reinitialization : + Error<"static data member %0 already has an initializer">; + def err_redefinition : Error<"redefinition of %0">; + def err_alias_after_tentative : + Error<"alias definition of %0 after tentative definition">; + def err_alias_is_definition : + Error<"definition %0 cannot also be an %select{alias|ifunc}1">; + def err_definition_of_implicitly_declared_member : Error< + "definition of implicitly declared %select{default constructor|copy " + "constructor|move constructor|copy assignment operator|move assignment " + "operator|destructor|function}1">; + def err_definition_of_explicitly_defaulted_member : Error< + "definition of explicitly defaulted %select{default constructor|copy " + "constructor|move constructor|copy assignment operator|move assignment " + "operator|destructor|function}0">; + def err_redefinition_extern_inline : Error< + "redefinition of a 'extern inline' function %0 is not supported in " + "%select{C99 mode|C++}1">; + def warn_attr_abi_tag_namespace : Warning< + "'abi_tag' attribute on %select{non-inline|anonymous}0 namespace ignored">, + InGroup; + def err_abi_tag_on_redeclaration : Error< + "cannot add 'abi_tag' attribute in a redeclaration">; + def err_new_abi_tag_on_redeclaration : Error< + "'abi_tag' %0 missing in original declaration">; + def note_use_ifdef_guards : Note< + "unguarded header; consider using #ifdef guards or #pragma once">; + + def note_deleted_dtor_no_operator_delete : Note< + "virtual destructor requires an unambiguous, accessible 'operator delete'">; + def note_deleted_special_member_class_subobject : Note< + "%select{default constructor of|copy constructor of|move constructor of|" + "copy assignment operator of|move assignment operator of|destructor of|" + "constructor inherited by}0 " + "%1 is implicitly deleted because " + "%select{base class %3|%select{||||variant }4field %3}2 " + "%select{has " + "%select{no|a deleted|multiple|an inaccessible|a non-trivial}4 " + "%select{%select{default constructor|copy constructor|move constructor|copy " + "assignment operator|move assignment operator|destructor|" + "%select{default|corresponding|default|default|default}4 constructor}0|" + "destructor}5" + "%select{||s||}4" + "|is an ObjC pointer}6">; + def note_deleted_default_ctor_uninit_field : Note< + "%select{default constructor of|constructor inherited by}0 " + "%1 is implicitly deleted because field %2 of " + "%select{reference|const-qualified}4 type %3 would not be initialized">; + def note_deleted_default_ctor_all_const : Note< + "%select{default constructor of|constructor inherited by}0 " + "%1 is implicitly deleted because all " + "%select{data members|data members of an anonymous union member}2" + " are const-qualified">; + def note_deleted_copy_ctor_rvalue_reference : Note< + "copy constructor of %0 is implicitly deleted because field %1 is of " + "rvalue reference type %2">; + def note_deleted_copy_user_declared_move : Note< + "copy %select{constructor|assignment operator}0 is implicitly deleted because" + " %1 has a user-declared move %select{constructor|assignment operator}2">; + def note_deleted_assign_field : Note< + "%select{copy|move}0 assignment operator of %1 is implicitly deleted " + "because field %2 is of %select{reference|const-qualified}4 type %3">; + + // These should be errors. + def warn_undefined_internal : Warning< + "%select{function|variable}0 %q1 has internal linkage but is not defined">, + InGroup>; + def err_undefined_internal_type : Error< + "%select{function|variable}0 %q1 is used but not defined in this " + "translation unit, and cannot be defined in any other translation unit " + "because its type does not have linkage">; + def ext_undefined_internal_type : Extension< + "ISO C++ requires a definition in this translation unit for " + "%select{function|variable}0 %q1 because its type does not have linkage">, + InGroup>; + def warn_undefined_inline : Warning<"inline function %q0 is not defined">, + InGroup>; + def err_undefined_inline_var : Error<"inline variable %q0 is not defined">; + def note_used_here : Note<"used here">; + + def err_attribute_missing_on_first_decl : Error< + "%0 attribute does not appear on the first declaration">; + def warn_internal_linkage_local_storage : Warning< + "'internal_linkage' attribute on a non-static local variable is ignored">, + InGroup; + + def ext_internal_in_extern_inline : ExtWarn< + "static %select{function|variable}0 %1 is used in an inline function with " + "external linkage">, InGroup; + def ext_internal_in_extern_inline_quiet : Extension< + "static %select{function|variable}0 %1 is used in an inline function with " + "external linkage">, InGroup; + def warn_static_local_in_extern_inline : Warning< + "non-constant static local variable in inline function may be different " + "in different files">, InGroup; + def note_convert_inline_to_static : Note< + "use 'static' to give inline function %0 internal linkage">; + + def ext_redefinition_of_typedef : ExtWarn< + "redefinition of typedef %0 is a C11 feature">, + InGroup >; + def err_redefinition_variably_modified_typedef : Error< + "redefinition of %select{typedef|type alias}0 for variably-modified type %1">; + + def err_inline_decl_follows_def : Error< + "inline declaration of %0 follows non-inline definition">; + def err_inline_declaration_block_scope : Error< + "inline declaration of %0 not allowed in block scope">; + def err_static_non_static : Error< + "static declaration of %0 follows non-static declaration">; + def err_different_language_linkage : Error< + "declaration of %0 has a different language linkage">; + def ext_retained_language_linkage : Extension< + "friend function %0 retaining previous language linkage is an extension">, + InGroup>; + def err_extern_c_global_conflict : Error< + "declaration of %1 %select{with C language linkage|in global scope}0 " + "conflicts with declaration %select{in global scope|with C language linkage}0">; + def note_extern_c_global_conflict : Note< + "declared %select{in global scope|with C language linkage}0 here">; + def note_extern_c_begins_here : Note< + "extern \"C\" language linkage specification begins here">; + def warn_weak_import : Warning < + "an already-declared variable is made a weak_import declaration %0">; + def ext_static_non_static : Extension< + "redeclaring non-static %0 as static is a Microsoft extension">, + InGroup; + def err_non_static_static : Error< + "non-static declaration of %0 follows static declaration">; + def err_extern_non_extern : Error< + "extern declaration of %0 follows non-extern declaration">; + def err_non_extern_extern : Error< + "non-extern declaration of %0 follows extern declaration">; + def err_non_thread_thread : Error< + "non-thread-local declaration of %0 follows thread-local declaration">; + def err_thread_non_thread : Error< + "thread-local declaration of %0 follows non-thread-local declaration">; + def err_thread_thread_different_kind : Error< + "thread-local declaration of %0 with %select{static|dynamic}1 initialization " + "follows declaration with %select{dynamic|static}1 initialization">; + def err_mismatched_owning_module : Error< + "declaration of %0 in %select{the global module|module %2}1 follows " + "declaration in %select{the global module|module %4}3">; + def err_redefinition_different_type : Error< + "redefinition of %0 with a different type%diff{: $ vs $|}1,2">; + def err_redefinition_different_kind : Error< + "redefinition of %0 as different kind of symbol">; + def err_redefinition_different_namespace_alias : Error< + "redefinition of %0 as an alias for a different namespace">; + def note_previous_namespace_alias : Note< + "previously defined as an alias for %0">; + def warn_forward_class_redefinition : Warning< + "redefinition of forward class %0 of a typedef name of an object type is ignored">, + InGroup>; + def err_redefinition_different_typedef : Error< + "%select{typedef|type alias|type alias template}0 " + "redefinition with different types%diff{ ($ vs $)|}1,2">; + def err_tag_reference_non_tag : Error< + "%select{non-struct type|non-class type|non-union type|non-enum " + "type|typedef|type alias|template|type alias template|template " + "template argument}1 %0 cannot be referenced with a " + "%select{struct|interface|union|class|enum}2 specifier">; + def err_tag_reference_conflict : Error< + "implicit declaration introduced by elaborated type conflicts with a " + "%select{non-struct type|non-class type|non-union type|non-enum " + "type|typedef|type alias|template|type alias template|template " + "template argument}0 of the same name">; + def err_dependent_tag_decl : Error< + "%select{declaration|definition}0 of " + "%select{struct|interface|union|class|enum}1 in a dependent scope">; + def err_tag_definition_of_typedef : Error< + "definition of type %0 conflicts with %select{typedef|type alias}1 of the same name">; + def err_conflicting_types : Error<"conflicting types for %0">; + def err_different_pass_object_size_params : Error< + "conflicting pass_object_size attributes on parameters">; + def err_late_asm_label_name : Error< + "cannot apply asm label to %select{variable|function}0 after its first use">; + def err_different_asm_label : Error<"conflicting asm label">; + def err_nested_redefinition : Error<"nested redefinition of %0">; + def err_use_with_wrong_tag : Error< + "use of %0 with tag type that does not match previous declaration">; + def warn_struct_class_tag_mismatch : Warning< + "%select{struct|interface|class}0%select{| template}1 %2 was previously " + "declared as a %select{struct|interface|class}3%select{| template}1; " + "this is valid, but may result in linker errors under the Microsoft C++ ABI">, + InGroup, DefaultIgnore; + def warn_struct_class_previous_tag_mismatch : Warning< + "%2 defined as %select{a struct|an interface|a class}0%select{| template}1 " + "here but previously declared as " + "%select{a struct|an interface|a class}3%select{| template}1; " + "this is valid, but may result in linker errors under the Microsoft C++ ABI">, + InGroup, DefaultIgnore; + def note_struct_class_suggestion : Note< + "did you mean %select{struct|interface|class}0 here?">; + def ext_forward_ref_enum : Extension< + "ISO C forbids forward references to 'enum' types">; + def err_forward_ref_enum : Error< + "ISO C++ forbids forward references to 'enum' types">; + def ext_ms_forward_ref_enum : ExtWarn< + "forward references to 'enum' types are a Microsoft extension">, + InGroup; + def ext_forward_ref_enum_def : Extension< + "redeclaration of already-defined enum %0 is a GNU extension">, + InGroup; + + def err_redefinition_of_enumerator : Error<"redefinition of enumerator %0">; + def err_duplicate_member : Error<"duplicate member %0">; + def err_misplaced_ivar : Error< + "instance variables may not be placed in %select{categories|class extension}0">; + def warn_ivars_in_interface : Warning< + "declaration of instance variables in the interface is deprecated">, + InGroup>, DefaultIgnore; + def ext_enum_value_not_int : Extension< + "ISO C restricts enumerator values to range of 'int' (%0 is too " + "%select{small|large}1)">; + def ext_enum_too_large : ExtWarn< + "enumeration values exceed range of largest integer">, InGroup; + def ext_enumerator_increment_too_large : ExtWarn< + "incremented enumerator value %0 is not representable in the " + "largest integer type">, InGroup; + def warn_flag_enum_constant_out_of_range : Warning< + "enumeration value %0 is out of range of flags in enumeration type %1">, + InGroup; + + def err_vm_decl_in_file_scope : Error< + "variably modified type declaration not allowed at file scope">; + def err_vm_decl_has_extern_linkage : Error< + "variably modified type declaration cannot have 'extern' linkage">; + def err_typecheck_field_variable_size : Error< + "fields must have a constant size: 'variable length array in structure' " + "extension will never be supported">; + def err_vm_func_decl : Error< + "function declaration cannot have variably modified type">; + def err_array_too_large : Error< + "array is too large (%0 elements)">; + + def err_typecheck_negative_array_size : Error<"array size is negative">; + def warn_typecheck_function_qualifiers_ignored : Warning< + "'%0' qualifier on function type %1 has no effect">, + InGroup; + def warn_typecheck_function_qualifiers_unspecified : Warning< + "'%0' qualifier on function type %1 has unspecified behavior">; + def warn_typecheck_reference_qualifiers : Warning< + "'%0' qualifier on reference type %1 has no effect">, + InGroup; + def err_typecheck_invalid_restrict_not_pointer : Error< + "restrict requires a pointer or reference (%0 is invalid)">; + def err_typecheck_invalid_restrict_not_pointer_noarg : Error< + "restrict requires a pointer or reference">; + def err_typecheck_invalid_restrict_invalid_pointee : Error< + "pointer to function type %0 may not be 'restrict' qualified">; + def ext_typecheck_zero_array_size : Extension< + "zero size arrays are an extension">, InGroup; + def err_typecheck_zero_array_size : Error< + "zero-length arrays are not permitted in C++">; + def err_array_size_non_int : Error<"size of array has non-integer type %0">; + def err_init_element_not_constant : Error< + "initializer element is not a compile-time constant">; + def ext_aggregate_init_not_constant : Extension< + "initializer for aggregate is not a compile-time constant">, InGroup; + def err_local_cant_init : Error< + "'__local' variable cannot have an initializer">; + def err_loader_uninitialized_cant_init + : Error<"variable with 'loader_uninitialized' attribute cannot have an " + "initializer">; + def err_loader_uninitialized_trivial_ctor + : Error<"variable with 'loader_uninitialized' attribute must have a " + "trivial default constructor">; + def err_loader_uninitialized_redeclaration + : Error<"redeclaration cannot add 'loader_uninitialized' attribute">; + def err_loader_uninitialized_extern_decl + : Error<"variable %0 cannot be declared both 'extern' and with the " + "'loader_uninitialized' attribute">; + def err_block_extern_cant_init : Error< + "'extern' variable cannot have an initializer">; + def warn_extern_init : Warning<"'extern' variable has an initializer">, + InGroup>; + def err_variable_object_no_init : Error< + "variable-sized object may not be initialized">; + def err_excess_initializers : Error< + "excess elements in %select{array|vector|scalar|union|struct}0 initializer">; + def ext_excess_initializers : ExtWarn< + "excess elements in %select{array|vector|scalar|union|struct}0 initializer">, + InGroup; + def err_excess_initializers_for_sizeless_type : Error< + "excess elements in initializer for indivisible sizeless type %0">; + def ext_excess_initializers_for_sizeless_type : ExtWarn< + "excess elements in initializer for indivisible sizeless type %0">, + InGroup; + def err_excess_initializers_in_char_array_initializer : Error< + "excess elements in char array initializer">; + def ext_excess_initializers_in_char_array_initializer : ExtWarn< + "excess elements in char array initializer">, + InGroup; + def err_initializer_string_for_char_array_too_long : Error< + "initializer-string for char array is too long">; + def ext_initializer_string_for_char_array_too_long : ExtWarn< + "initializer-string for char array is too long">, + InGroup; + def warn_missing_field_initializers : Warning< + "missing field %0 initializer">, + InGroup, DefaultIgnore; + def warn_braces_around_init : Warning< + "braces around %select{scalar |}0initializer">, + InGroup>; + def ext_many_braces_around_init : ExtWarn< + "too many braces around %select{scalar |}0initializer">, + InGroup>, SFINAEFailure; + def ext_complex_component_init : Extension< + "complex initialization specifying real and imaginary components " + "is an extension">, InGroup>; + def err_empty_scalar_initializer : Error<"scalar initializer cannot be empty">; + def err_empty_sizeless_initializer : Error< + "initializer for sizeless type %0 cannot be empty">; + def warn_cxx98_compat_empty_scalar_initializer : Warning< + "scalar initialized from empty initializer list is incompatible with C++98">, + InGroup, DefaultIgnore; + def warn_cxx98_compat_empty_sizeless_initializer : Warning< + "initializing %0 from an empty initializer list is incompatible with C++98">, + InGroup, DefaultIgnore; + def warn_cxx98_compat_reference_list_init : Warning< + "reference initialized from initializer list is incompatible with C++98">, + InGroup, DefaultIgnore; + def warn_cxx98_compat_initializer_list_init : Warning< + "initialization of initializer_list object is incompatible with C++98">, + InGroup, DefaultIgnore; + def warn_cxx98_compat_ctor_list_init : Warning< + "constructor call from initializer list is incompatible with C++98">, + InGroup, DefaultIgnore; + def err_illegal_initializer : Error< + "illegal initializer (only variables can be initialized)">; + def err_illegal_initializer_type : Error<"illegal initializer type %0">; + def ext_init_list_type_narrowing : ExtWarn< + "type %0 cannot be narrowed to %1 in initializer list">, + InGroup, DefaultError, SFINAEFailure; + def ext_init_list_variable_narrowing : ExtWarn< + "non-constant-expression cannot be narrowed from type %0 to %1 in " + "initializer list">, InGroup, DefaultError, SFINAEFailure; + def ext_init_list_constant_narrowing : ExtWarn< + "constant expression evaluates to %0 which cannot be narrowed to type %1">, + InGroup, DefaultError, SFINAEFailure; + def warn_init_list_type_narrowing : Warning< + "type %0 cannot be narrowed to %1 in initializer list in C++11">, + InGroup, DefaultIgnore; + def warn_init_list_variable_narrowing : Warning< + "non-constant-expression cannot be narrowed from type %0 to %1 in " + "initializer list in C++11">, + InGroup, DefaultIgnore; + def warn_init_list_constant_narrowing : Warning< + "constant expression evaluates to %0 which cannot be narrowed to type %1 in " + "C++11">, + InGroup, DefaultIgnore; + def note_init_list_narrowing_silence : Note< + "insert an explicit cast to silence this issue">; + def err_init_objc_class : Error< + "cannot initialize Objective-C class type %0">; + def err_implicit_empty_initializer : Error< + "initializer for aggregate with no elements requires explicit braces">; + def err_bitfield_has_negative_width : Error< + "bit-field %0 has negative width (%1)">; + def err_anon_bitfield_has_negative_width : Error< + "anonymous bit-field has negative width (%0)">; + def err_bitfield_has_zero_width : Error<"named bit-field %0 has zero width">; + def err_bitfield_width_exceeds_type_width : Error< + "width of%select{ anonymous|}0 bit-field%select{| %1}0 (%2 bits) exceeds the " + "%select{width|size}3 of its type (%4 bit%s4)">; + def err_incorrect_number_of_vector_initializers : Error< + "number of elements must be either one or match the size of the vector">; + + // Used by C++ which allows bit-fields that are wider than the type. + def warn_bitfield_width_exceeds_type_width: Warning< + "width of bit-field %0 (%1 bits) exceeds the width of its type; value will " + "be truncated to %2 bit%s2">, InGroup; + def err_bitfield_too_wide : Error< + "%select{bit-field %1|anonymous bit-field}0 is too wide (%2 bits)">; + def warn_bitfield_too_small_for_enum : Warning< + "bit-field %0 is not wide enough to store all enumerators of %1">, + InGroup, DefaultIgnore; + def note_widen_bitfield : Note< + "widen this field to %0 bits to store all values of %1">; + def warn_unsigned_bitfield_assigned_signed_enum : Warning< + "assigning value of signed enum type %1 to unsigned bit-field %0; " + "negative enumerators of enum %1 will be converted to positive values">, + InGroup, DefaultIgnore; + def warn_signed_bitfield_enum_conversion : Warning< + "signed bit-field %0 needs an extra bit to represent the largest positive " + "enumerators of %1">, + InGroup, DefaultIgnore; + def note_change_bitfield_sign : Note< + "consider making the bitfield type %select{unsigned|signed}0">; + + def warn_missing_braces : Warning< + "suggest braces around initialization of subobject">, + InGroup, DefaultIgnore; + + def err_redefinition_of_label : Error<"redefinition of label %0">; + def err_undeclared_label_use : Error<"use of undeclared label %0">; + def err_goto_ms_asm_label : Error< + "cannot jump from this goto statement to label %0 inside an inline assembly block">; + def note_goto_ms_asm_label : Note< + "inline assembly label %0 declared here">; + def warn_unused_label : Warning<"unused label %0">, + InGroup, DefaultIgnore; + + def err_continue_from_cond_var_init : Error< + "cannot jump from this continue statement to the loop increment; " + "jump bypasses initialization of loop condition variable">; + def err_goto_into_protected_scope : Error< + "cannot jump from this goto statement to its label">; + def ext_goto_into_protected_scope : ExtWarn< + "jump from this goto statement to its label is a Microsoft extension">, + InGroup; + def warn_cxx98_compat_goto_into_protected_scope : Warning< + "jump from this goto statement to its label is incompatible with C++98">, + InGroup, DefaultIgnore; + def err_switch_into_protected_scope : Error< + "cannot jump from switch statement to this case label">; + def warn_cxx98_compat_switch_into_protected_scope : Warning< + "jump from switch statement to this case label is incompatible with C++98">, + InGroup, DefaultIgnore; + def err_indirect_goto_without_addrlabel : Error< + "indirect goto in function with no address-of-label expressions">; + def err_indirect_goto_in_protected_scope : Error< + "cannot jump from this %select{indirect|asm}0 goto statement to one of its possible targets">; + def warn_cxx98_compat_indirect_goto_in_protected_scope : Warning< + "jump from this %select{indirect|asm}0 goto statement to one of its possible targets " + "is incompatible with C++98">, InGroup, DefaultIgnore; + def note_indirect_goto_target : Note< + "possible target of %select{indirect|asm}0 goto statement">; + def note_protected_by_variable_init : Note< + "jump bypasses variable initialization">; + def note_protected_by_variable_nontriv_destructor : Note< + "jump bypasses variable with a non-trivial destructor">; + def note_protected_by_variable_non_pod : Note< + "jump bypasses initialization of non-POD variable">; + def note_protected_by_cleanup : Note< + "jump bypasses initialization of variable with __attribute__((cleanup))">; + def note_protected_by_vla_typedef : Note< + "jump bypasses initialization of VLA typedef">; + def note_protected_by_vla_type_alias : Note< + "jump bypasses initialization of VLA type alias">; + def note_protected_by_constexpr_if : Note< + "jump enters controlled statement of constexpr if">; + def note_protected_by_if_available : Note< + "jump enters controlled statement of if available">; + def note_protected_by_vla : Note< + "jump bypasses initialization of variable length array">; + def note_protected_by_objc_fast_enumeration : Note< + "jump enters Objective-C fast enumeration loop">; + def note_protected_by_objc_try : Note< + "jump bypasses initialization of @try block">; + def note_protected_by_objc_catch : Note< + "jump bypasses initialization of @catch block">; + def note_protected_by_objc_finally : Note< + "jump bypasses initialization of @finally block">; + def note_protected_by_objc_synchronized : Note< + "jump bypasses initialization of @synchronized block">; + def note_protected_by_objc_autoreleasepool : Note< + "jump bypasses auto release push of @autoreleasepool block">; + def note_protected_by_cxx_try : Note< + "jump bypasses initialization of try block">; + def note_protected_by_cxx_catch : Note< + "jump bypasses initialization of catch block">; + def note_protected_by_seh_try : Note< + "jump bypasses initialization of __try block">; + def note_protected_by_seh_except : Note< + "jump bypasses initialization of __except block">; + def note_protected_by_seh_finally : Note< + "jump bypasses initialization of __finally block">; + def note_protected_by___block : Note< + "jump bypasses setup of __block variable">; + def note_protected_by_objc_strong_init : Note< + "jump bypasses initialization of __strong variable">; + def note_protected_by_objc_weak_init : Note< + "jump bypasses initialization of __weak variable">; + def note_protected_by_non_trivial_c_struct_init : Note< + "jump bypasses initialization of variable of non-trivial C struct type">; + def note_enters_block_captures_cxx_obj : Note< + "jump enters lifetime of block which captures a destructible C++ object">; + def note_enters_block_captures_strong : Note< + "jump enters lifetime of block which strongly captures a variable">; + def note_enters_block_captures_weak : Note< + "jump enters lifetime of block which weakly captures a variable">; + def note_enters_block_captures_non_trivial_c_struct : Note< + "jump enters lifetime of block which captures a C struct that is non-trivial " + "to destroy">; + def note_enters_compound_literal_scope : Note< + "jump enters lifetime of a compound literal that is non-trivial to destruct">; + + def note_exits_cleanup : Note< + "jump exits scope of variable with __attribute__((cleanup))">; + def note_exits_dtor : Note< + "jump exits scope of variable with non-trivial destructor">; + def note_exits_temporary_dtor : Note< + "jump exits scope of lifetime-extended temporary with non-trivial " + "destructor">; + def note_exits___block : Note< + "jump exits scope of __block variable">; + def note_exits_objc_try : Note< + "jump exits @try block">; + def note_exits_objc_catch : Note< + "jump exits @catch block">; + def note_exits_objc_finally : Note< + "jump exits @finally block">; + def note_exits_objc_synchronized : Note< + "jump exits @synchronized block">; + def note_exits_cxx_try : Note< + "jump exits try block">; + def note_exits_cxx_catch : Note< + "jump exits catch block">; + def note_exits_seh_try : Note< + "jump exits __try block">; + def note_exits_seh_except : Note< + "jump exits __except block">; + def note_exits_seh_finally : Note< + "jump exits __finally block">; + def note_exits_objc_autoreleasepool : Note< + "jump exits autoreleasepool block">; + def note_exits_objc_strong : Note< + "jump exits scope of __strong variable">; + def note_exits_objc_weak : Note< + "jump exits scope of __weak variable">; + def note_exits_block_captures_cxx_obj : Note< + "jump exits lifetime of block which captures a destructible C++ object">; + def note_exits_block_captures_strong : Note< + "jump exits lifetime of block which strongly captures a variable">; + def note_exits_block_captures_weak : Note< + "jump exits lifetime of block which weakly captures a variable">; + def note_exits_block_captures_non_trivial_c_struct : Note< + "jump exits lifetime of block which captures a C struct that is non-trivial " + "to destroy">; + def note_exits_compound_literal_scope : Note< + "jump exits lifetime of a compound literal that is non-trivial to destruct">; + + def err_func_returning_qualified_void : ExtWarn< + "function cannot return qualified void type %0">, + InGroup>; + def err_func_returning_array_function : Error< + "function cannot return %select{array|function}0 type %1">; + def err_field_declared_as_function : Error<"field %0 declared as a function">; + def err_field_incomplete_or_sizeless : Error< + "field has %select{incomplete|sizeless}0 type %1">; + def ext_variable_sized_type_in_struct : ExtWarn< + "field %0 with variable sized type %1 not at the end of a struct or class is" + " a GNU extension">, InGroup; + + def ext_c99_flexible_array_member : Extension< + "flexible array members are a C99 feature">, InGroup; + def err_flexible_array_virtual_base : Error< + "flexible array member %0 not allowed in " + "%select{struct|interface|union|class|enum}1 which has a virtual base class">; + def err_flexible_array_empty_aggregate : Error< + "flexible array member %0 not allowed in otherwise empty " + "%select{struct|interface|union|class|enum}1">; + def err_flexible_array_has_nontrivial_dtor : Error< + "flexible array member %0 of type %1 with non-trivial destruction">; + def ext_flexible_array_in_struct : Extension< + "%0 may not be nested in a struct due to flexible array member">, + InGroup; + def ext_flexible_array_in_array : Extension< + "%0 may not be used as an array element due to flexible array member">, + InGroup; + def err_flexible_array_init : Error< + "initialization of flexible array member is not allowed">; + def ext_flexible_array_empty_aggregate_ms : Extension< + "flexible array member %0 in otherwise empty " + "%select{struct|interface|union|class|enum}1 is a Microsoft extension">, + InGroup; + def err_flexible_array_union : Error< + "flexible array member %0 in a union is not allowed">; + def ext_flexible_array_union_ms : Extension< + "flexible array member %0 in a union is a Microsoft extension">, + InGroup; + def ext_flexible_array_empty_aggregate_gnu : Extension< + "flexible array member %0 in otherwise empty " + "%select{struct|interface|union|class|enum}1 is a GNU extension">, + InGroup; + def ext_flexible_array_union_gnu : Extension< + "flexible array member %0 in a union is a GNU extension">, InGroup; + + def err_flexible_array_not_at_end : Error< + "flexible array member %0 with type %1 is not at the end of" + " %select{struct|interface|union|class|enum}2">; + def err_objc_variable_sized_type_not_at_end : Error< + "field %0 with variable sized type %1 is not at the end of class">; + def note_next_field_declaration : Note< + "next field declaration is here">; + def note_next_ivar_declaration : Note< + "next %select{instance variable declaration|synthesized instance variable}0" + " is here">; + def err_synthesize_variable_sized_ivar : Error< + "synthesized property with variable size type %0" + " requires an existing instance variable">; + def err_flexible_array_arc_retainable : Error< + "ARC forbids flexible array members with retainable object type">; + def warn_variable_sized_ivar_visibility : Warning< + "field %0 with variable sized type %1 is not visible to subclasses and" + " can conflict with their instance variables">, InGroup; + def warn_superclass_variable_sized_type_not_at_end : Warning< + "field %0 can overwrite instance variable %1 with variable sized type %2" + " in superclass %3">, InGroup; + + let CategoryName = "ARC Semantic Issue" in { + + // ARC-mode diagnostics. + + let CategoryName = "ARC Weak References" in { + + def err_arc_weak_no_runtime : Error< + "cannot create __weak reference because the current deployment target " + "does not support weak references">; + def err_arc_weak_disabled : Error< + "cannot create __weak reference in file using manual reference counting">; + def err_synthesizing_arc_weak_property_disabled : Error< + "cannot synthesize weak property in file using manual reference counting">; + def err_synthesizing_arc_weak_property_no_runtime : Error< + "cannot synthesize weak property because the current deployment target " + "does not support weak references">; + def err_arc_unsupported_weak_class : Error< + "class is incompatible with __weak references">; + def err_arc_weak_unavailable_assign : Error< + "assignment of a weak-unavailable object to a __weak object">; + def err_arc_weak_unavailable_property : Error< + "synthesizing __weak instance variable of type %0, which does not " + "support weak references">; + def note_implemented_by_class : Note< + "when implemented by class %0">; + def err_arc_convesion_of_weak_unavailable : Error< + "%select{implicit conversion|cast}0 of weak-unavailable object of type %1 to" + " a __weak object of type %2">; + + } // end "ARC Weak References" category + + let CategoryName = "ARC Restrictions" in { + + def err_unavailable_in_arc : Error< + "%0 is unavailable in ARC">; + def note_arc_forbidden_type : Note< + "declaration uses type that is ill-formed in ARC">; + def note_performs_forbidden_arc_conversion : Note< + "inline function performs a conversion which is forbidden in ARC">; + def note_arc_init_returns_unrelated : Note< + "init method must return a type related to its receiver type">; + def note_arc_weak_disabled : Note< + "declaration uses __weak, but ARC is disabled">; + def note_arc_weak_no_runtime : Note<"declaration uses __weak, which " + "the current deployment target does not support">; + def note_arc_field_with_ownership : Note< + "field has non-trivial ownership qualification">; + + def err_arc_illegal_explicit_message : Error< + "ARC forbids explicit message send of %0">; + def err_arc_unused_init_message : Error< + "the result of a delegate init call must be immediately returned " + "or assigned to 'self'">; + def err_arc_mismatched_cast : Error< + "%select{implicit conversion|cast}0 of " + "%select{%2|a non-Objective-C pointer type %2|a block pointer|" + "an Objective-C pointer|an indirect pointer to an Objective-C pointer}1" + " to %3 is disallowed with ARC">; + def err_arc_nolifetime_behavior : Error< + "explicit ownership qualifier on cast result has no effect">; + def err_arc_objc_property_default_assign_on_object : Error< + "ARC forbids synthesizing a property of an Objective-C object " + "with unspecified ownership or storage attribute">; + def err_arc_illegal_selector : Error< + "ARC forbids use of %0 in a @selector">; + def err_arc_illegal_method_def : Error< + "ARC forbids %select{implementation|synthesis}0 of %1">; + def warn_arc_strong_pointer_objc_pointer : Warning< + "method parameter of type %0 with no explicit ownership">, + InGroup>, DefaultIgnore; + + } // end "ARC Restrictions" category + + def err_arc_lost_method_convention : Error< + "method was declared as %select{an 'alloc'|a 'copy'|an 'init'|a 'new'}0 " + "method, but its implementation doesn't match because %select{" + "its result type is not an object pointer|" + "its result type is unrelated to its receiver type}1">; + def note_arc_lost_method_convention : Note<"declaration in interface">; + def err_arc_gained_method_convention : Error< + "method implementation does not match its declaration">; + def note_arc_gained_method_convention : Note< + "declaration in interface is not in the '%select{alloc|copy|init|new}0' " + "family because %select{its result type is not an object pointer|" + "its result type is unrelated to its receiver type}1">; + def err_typecheck_arc_assign_self : Error< + "cannot assign to 'self' outside of a method in the init family">; + def err_typecheck_arc_assign_self_class_method : Error< + "cannot assign to 'self' in a class method">; + def err_typecheck_arr_assign_enumeration : Error< + "fast enumeration variables cannot be modified in ARC by default; " + "declare the variable __strong to allow this">; + def err_typecheck_arc_assign_externally_retained : Error< + "variable declared with 'objc_externally_retained' " + "cannot be modified in ARC">; + def warn_arc_retained_assign : Warning< + "assigning retained object to %select{weak|unsafe_unretained}0 " + "%select{property|variable}1" + "; object will be released after assignment">, + InGroup; + def warn_arc_retained_property_assign : Warning< + "assigning retained object to unsafe property" + "; object will be released after assignment">, + InGroup; + def warn_arc_literal_assign : Warning< + "assigning %select{array literal|dictionary literal|numeric literal|boxed expression||block literal}0" + " to a weak %select{property|variable}1" + "; object will be released after assignment">, + InGroup; + def err_arc_new_array_without_ownership : Error< + "'new' cannot allocate an array of %0 with no explicit ownership">; + def err_arc_autoreleasing_var : Error< + "%select{__block variables|global variables|fields|instance variables}0 cannot have " + "__autoreleasing ownership">; + def err_arc_autoreleasing_capture : Error< + "cannot capture __autoreleasing variable in a " + "%select{block|lambda by copy}0">; + def err_arc_thread_ownership : Error< + "thread-local variable has non-trivial ownership: type is %0">; + def err_arc_indirect_no_ownership : Error< + "%select{pointer|reference}1 to non-const type %0 with no explicit ownership">; + def err_arc_array_param_no_ownership : Error< + "must explicitly describe intended ownership of an object array parameter">; + def err_arc_pseudo_dtor_inconstant_quals : Error< + "pseudo-destructor destroys object of type %0 with inconsistently-qualified " + "type %1">; + def err_arc_init_method_unrelated_result_type : Error< + "init methods must return a type related to the receiver type">; + def err_arc_nonlocal_writeback : Error< + "passing address of %select{non-local|non-scalar}0 object to " + "__autoreleasing parameter for write-back">; + def err_arc_method_not_found : Error< + "no known %select{instance|class}1 method for selector %0">; + def err_arc_receiver_forward_class : Error< + "receiver %0 for class message is a forward declaration">; + def err_arc_may_not_respond : Error< + "no visible @interface for %0 declares the selector %1">; + def err_arc_receiver_forward_instance : Error< + "receiver type %0 for instance message is a forward declaration">; + def warn_receiver_forward_instance : Warning< + "receiver type %0 for instance message is a forward declaration">, + InGroup, DefaultIgnore; + def err_arc_collection_forward : Error< + "collection expression type %0 is a forward declaration">; + def err_arc_multiple_method_decl : Error< + "multiple methods named %0 found with mismatched result, " + "parameter type or attributes">; + def warn_arc_lifetime_result_type : Warning< + "ARC %select{unused|__unsafe_unretained|__strong|__weak|__autoreleasing}0 " + "lifetime qualifier on return type is ignored">, + InGroup; + + let CategoryName = "ARC Retain Cycle" in { + + def warn_arc_retain_cycle : Warning< + "capturing %0 strongly in this block is likely to lead to a retain cycle">, + InGroup; + def note_arc_retain_cycle_owner : Note< + "block will be retained by %select{the captured object|an object strongly " + "retained by the captured object}0">; + + } // end "ARC Retain Cycle" category + + def warn_arc_object_memaccess : Warning< + "%select{destination for|source of}0 this %1 call is a pointer to " + "ownership-qualified type %2">, InGroup; + + let CategoryName = "ARC and @properties" in { + + def err_arc_strong_property_ownership : Error< + "existing instance variable %1 for strong property %0 may not be " + "%select{|__unsafe_unretained||__weak}2">; + def err_arc_assign_property_ownership : Error< + "existing instance variable %1 for property %0 with %select{unsafe_unretained|assign}2 " + "attribute must be __unsafe_unretained">; + def err_arc_inconsistent_property_ownership : Error< + "%select{|unsafe_unretained|strong|weak}1 property %0 may not also be " + "declared %select{|__unsafe_unretained|__strong|__weak|__autoreleasing}2">; + + } // end "ARC and @properties" category + + def warn_block_capture_autoreleasing : Warning< + "block captures an autoreleasing out-parameter, which may result in " + "use-after-free bugs">, + InGroup; + def note_declare_parameter_strong : Note< + "declare the parameter __strong or capture a __block __strong variable to " + "keep values alive across autorelease pools">; + + def err_arc_atomic_ownership : Error< + "cannot perform atomic operation on a pointer to type %0: type has " + "non-trivial ownership">; + + let CategoryName = "ARC Casting Rules" in { + + def err_arc_bridge_cast_incompatible : Error< + "incompatible types casting %0 to %1 with a %select{__bridge|" + "__bridge_transfer|__bridge_retained}2 cast">; + def err_arc_bridge_cast_wrong_kind : Error< + "cast of %select{Objective-C|block|C}0 pointer type %1 to " + "%select{Objective-C|block|C}2 pointer type %3 cannot use %select{__bridge|" + "__bridge_transfer|__bridge_retained}4">; + def err_arc_cast_requires_bridge : Error< + "%select{cast|implicit conversion}0 of %select{Objective-C|block|C}1 " + "pointer type %2 to %select{Objective-C|block|C}3 pointer type %4 " + "requires a bridged cast">; + def note_arc_bridge : Note< + "use __bridge to convert directly (no change in ownership)">; + def note_arc_cstyle_bridge : Note< + "use __bridge with C-style cast to convert directly (no change in ownership)">; + def note_arc_bridge_transfer : Note< + "use %select{__bridge_transfer|CFBridgingRelease call}1 to transfer " + "ownership of a +1 %0 into ARC">; + def note_arc_cstyle_bridge_transfer : Note< + "use __bridge_transfer with C-style cast to transfer " + "ownership of a +1 %0 into ARC">; + def note_arc_bridge_retained : Note< + "use %select{__bridge_retained|CFBridgingRetain call}1 to make an " + "ARC object available as a +1 %0">; + def note_arc_cstyle_bridge_retained : Note< + "use __bridge_retained with C-style cast to make an " + "ARC object available as a +1 %0">; + + } // ARC Casting category + + } // ARC category name + + def err_flexible_array_init_needs_braces : Error< + "flexible array requires brace-enclosed initializer">; + def err_illegal_decl_array_of_functions : Error< + "'%0' declared as array of functions of type %1">; + def err_array_incomplete_or_sizeless_type : Error< + "array has %select{incomplete|sizeless}0 element type %1">; + def err_illegal_message_expr_incomplete_type : Error< + "Objective-C message has incomplete result type %0">; + def err_illegal_decl_array_of_references : Error< + "'%0' declared as array of references of type %1">; + def err_decl_negative_array_size : Error< + "'%0' declared as an array with a negative size">; + def err_array_static_outside_prototype : Error< + "%0 used in array declarator outside of function prototype">; + def err_array_static_not_outermost : Error< + "%0 used in non-outermost array type derivation">; + def err_array_star_outside_prototype : Error< + "star modifier used outside of function prototype">; + def err_illegal_decl_pointer_to_reference : Error< + "'%0' declared as a pointer to a reference of type %1">; + def err_illegal_decl_mempointer_to_reference : Error< + "'%0' declared as a member pointer to a reference of type %1">; + def err_illegal_decl_mempointer_to_void : Error< + "'%0' declared as a member pointer to void">; + def err_illegal_decl_mempointer_in_nonclass : Error< + "'%0' does not point into a class">; + def err_mempointer_in_nonclass_type : Error< + "member pointer refers into non-class type %0">; + def err_reference_to_void : Error<"cannot form a reference to 'void'">; + def err_nonfunction_block_type : Error< + "block pointer to non-function type is invalid">; + def err_return_block_has_expr : Error<"void block should not return a value">; + def err_block_return_missing_expr : Error< + "non-void block should return a value">; + def err_func_def_incomplete_result : Error< + "incomplete result type %0 in function definition">; + def err_atomic_specifier_bad_type + : Error<"_Atomic cannot be applied to " + "%select{incomplete |array |function |reference |atomic |qualified " + "|sizeless ||integer }0type " + "%1 %select{|||||||which is not trivially copyable|}0">; + + // Expressions. + def ext_sizeof_alignof_function_type : Extension< + "invalid application of '%0' to a function type">, InGroup; + def ext_sizeof_alignof_void_type : Extension< + "invalid application of '%0' to a void type">, InGroup; + def err_opencl_sizeof_alignof_type : Error< + "invalid application of '%0' to a void type">; + def err_sizeof_alignof_incomplete_or_sizeless_type : Error< + "invalid application of '%0' to %select{an incomplete|sizeless}1 type %2">; + def err_sizeof_alignof_function_type : Error< + "invalid application of '%0' to a function type">; + def err_openmp_default_simd_align_expr : Error< + "invalid application of '__builtin_omp_required_simd_align' to an expression, only type is allowed">; + def err_sizeof_alignof_typeof_bitfield : Error< + "invalid application of '%select{sizeof|alignof|typeof}0' to bit-field">; + def err_alignof_member_of_incomplete_type : Error< + "invalid application of 'alignof' to a field of a class still being defined">; + def err_vecstep_non_scalar_vector_type : Error< + "'vec_step' requires built-in scalar or vector type, %0 invalid">; + def err_offsetof_incomplete_type : Error< + "offsetof of incomplete type %0">; + def err_offsetof_record_type : Error< + "offsetof requires struct, union, or class type, %0 invalid">; + def err_offsetof_array_type : Error<"offsetof requires array type, %0 invalid">; + def ext_offsetof_non_pod_type : ExtWarn<"offset of on non-POD type %0">, + InGroup; + def ext_offsetof_non_standardlayout_type : ExtWarn< + "offset of on non-standard-layout type %0">, InGroup; + def err_offsetof_bitfield : Error<"cannot compute offset of bit-field %0">; + def err_offsetof_field_of_virtual_base : Error< + "invalid application of 'offsetof' to a field of a virtual base">; + def warn_sub_ptr_zero_size_types : Warning< + "subtraction of pointers to type %0 of zero size has undefined behavior">, + InGroup; + def warn_pointer_arith_null_ptr : Warning< + "performing pointer arithmetic on a null pointer has undefined behavior%select{| if the offset is nonzero}0">, + InGroup, DefaultIgnore; + def warn_gnu_null_ptr_arith : Warning< + "arithmetic on a null pointer treated as a cast from integer to pointer is a GNU extension">, + InGroup, DefaultIgnore; + def warn_pointer_sub_null_ptr : Warning< + "performing pointer subtraction with a null pointer %select{has|may have}0 undefined behavior">, + InGroup, DefaultIgnore; + def err_kernel_invalidates_sycl_unique_stable_name + : Error<"kernel instantiation changes the result of an evaluated " + "'__builtin_sycl_unique_stable_name'">; + def note_sycl_unique_stable_name_evaluated_here + : Note<"'__builtin_sycl_unique_stable_name' evaluated here">; + + def warn_floatingpoint_eq : Warning< + "comparing floating point with == or != is unsafe">, + InGroup>, DefaultIgnore; + + def warn_remainder_division_by_zero : Warning< + "%select{remainder|division}0 by zero is undefined">, + InGroup; + def warn_shift_lhs_negative : Warning<"shifting a negative signed value is undefined">, + InGroup>; + def warn_shift_negative : Warning<"shift count is negative">, + InGroup>; + def warn_shift_gt_typewidth : Warning<"shift count >= width of type">, + InGroup>; + def warn_shift_result_gt_typewidth : Warning< + "signed shift result (%0) requires %1 bits to represent, but %2 only has " + "%3 bits">, InGroup>; + def warn_shift_result_sets_sign_bit : Warning< + "signed shift result (%0) sets the sign bit of the shift expression's " + "type (%1) and becomes negative">, + InGroup>, DefaultIgnore; + + def warn_precedence_bitwise_rel : Warning< + "%0 has lower precedence than %1; %1 will be evaluated first">, + InGroup; + def note_precedence_bitwise_first : Note< + "place parentheses around the %0 expression to evaluate it first">; + def note_precedence_silence : Note< + "place parentheses around the '%0' expression to silence this warning">; + + def warn_precedence_conditional : Warning< + "operator '?:' has lower precedence than '%0'; '%0' will be evaluated first">, + InGroup; + def warn_precedence_bitwise_conditional : Warning< + "operator '?:' has lower precedence than '%0'; '%0' will be evaluated first">, + InGroup; + def note_precedence_conditional_first : Note< + "place parentheses around the '?:' expression to evaluate it first">; + + def warn_enum_constant_in_bool_context : Warning< + "converting the enum constant to a boolean">, + InGroup, DefaultIgnore; + def warn_left_shift_in_bool_context : Warning< + "converting the result of '<<' to a boolean; did you mean '(%0) != 0'?">, + InGroup, DefaultIgnore; + def warn_logical_instead_of_bitwise : Warning< + "use of logical '%0' with constant operand">, + InGroup>; + def note_logical_instead_of_bitwise_change_operator : Note< + "use '%0' for a bitwise operation">; + def note_logical_instead_of_bitwise_remove_constant : Note< + "remove constant to silence this warning">; + + def warn_bitwise_op_in_bitwise_op : Warning< + "'%0' within '%1'">, InGroup, DefaultIgnore; + + def warn_logical_and_in_logical_or : Warning< + "'&&' within '||'">, InGroup, DefaultIgnore; + + def warn_overloaded_shift_in_comparison :Warning< + "overloaded operator %select{>>|<<}0 has higher precedence than " + "comparison operator">, + InGroup; + def note_evaluate_comparison_first :Note< + "place parentheses around comparison expression to evaluate it first">; + + def note_concatenated_string_literal_silence :Note< + "place parentheses around the string literal to silence warning">; + + def warn_addition_in_bitshift : Warning< + "operator '%0' has lower precedence than '%1'; " + "'%1' will be evaluated first">, InGroup; + + def warn_self_assignment_builtin : Warning< + "explicitly assigning value of variable of type %0 to itself">, + InGroup, DefaultIgnore; + def warn_self_assignment_overloaded : Warning< + "explicitly assigning value of variable of type %0 to itself">, + InGroup, DefaultIgnore; + def warn_self_move : Warning< + "explicitly moving variable of type %0 to itself">, + InGroup, DefaultIgnore; + + def warn_redundant_move_on_return : Warning< + "redundant move in return statement">, + InGroup, DefaultIgnore; + def warn_pessimizing_move_on_return : Warning< + "moving a local object in a return statement prevents copy elision">, + InGroup, DefaultIgnore; + def warn_pessimizing_move_on_initialization : Warning< + "moving a temporary object prevents copy elision">, + InGroup, DefaultIgnore; + def note_remove_move : Note<"remove std::move call here">; + + def warn_string_plus_int : Warning< + "adding %0 to a string does not append to the string">, + InGroup; + def warn_string_plus_char : Warning< + "adding %0 to a string pointer does not append to the string">, + InGroup; + def note_string_plus_scalar_silence : Note< + "use array indexing to silence this warning">; + + def warn_sizeof_array_param : Warning< + "sizeof on array function parameter will return size of %0 instead of %1">, + InGroup; + + def warn_sizeof_array_decay : Warning< + "sizeof on pointer operation will return size of %0 instead of %1">, + InGroup; + + def err_sizeof_nonfragile_interface : Error< + "application of '%select{alignof|sizeof}1' to interface %0 is " + "not supported on this architecture and platform">; + def err_atdef_nonfragile_interface : Error< + "use of @defs is not supported on this architecture and platform">; + def err_subscript_nonfragile_interface : Error< + "subscript requires size of interface %0, which is not constant for " + "this architecture and platform">; + + def err_arithmetic_nonfragile_interface : Error< + "arithmetic on pointer to interface %0, which is not a constant size for " + "this architecture and platform">; + + def warn_deprecated_comma_subscript : Warning< + "top-level comma expression in array subscript is deprecated">, + InGroup; + + def ext_subscript_non_lvalue : Extension< + "ISO C90 does not allow subscripting non-lvalue array">; + def err_typecheck_subscript_value : Error< + "subscripted value is not an array, pointer, or vector">; + def err_typecheck_subscript_not_integer : Error< + "array subscript is not an integer">; + def err_subscript_function_type : Error< + "subscript of pointer to function type %0">; + def err_subscript_incomplete_or_sizeless_type : Error< + "subscript of pointer to %select{incomplete|sizeless}0 type %1">; + def err_dereference_incomplete_type : Error< + "dereference of pointer to incomplete type %0">; + def ext_gnu_subscript_void_type : Extension< + "subscript of a pointer to void is a GNU extension">, InGroup; + def err_typecheck_member_reference_struct_union : Error< + "member reference base type %0 is not a structure or union">; + def err_typecheck_member_reference_ivar : Error< + "%0 does not have a member named %1">; + def err_arc_weak_ivar_access : Error< + "dereferencing a __weak pointer is not allowed due to possible " + "null value caused by race condition, assign it to strong variable first">; + def err_typecheck_member_reference_arrow : Error< + "member reference type %0 is not a pointer">; + def err_typecheck_member_reference_suggestion : Error< + "member reference type %0 is %select{a|not a}1 pointer; did you mean to use '%select{->|.}1'?">; + def note_typecheck_member_reference_suggestion : Note< + "did you mean to use '.' instead?">; + def note_member_reference_arrow_from_operator_arrow : Note< + "'->' applied to return value of the operator->() declared here">; + def err_typecheck_member_reference_type : Error< + "cannot refer to type member %0 in %1 with '%select{.|->}2'">; + def err_typecheck_member_reference_unknown : Error< + "cannot refer to member %0 in %1 with '%select{.|->}2'">; + def err_member_reference_needs_call : Error< + "base of member reference is a function; perhaps you meant to call " + "it%select{| with no arguments}0?">; + def warn_subscript_is_char : Warning<"array subscript is of type 'char'">, + InGroup, DefaultIgnore; + + def err_typecheck_incomplete_tag : Error<"incomplete definition of type %0">; + def err_no_member : Error<"no member named %0 in %1">; + def err_no_member_overloaded_arrow : Error< + "no member named %0 in %1; did you mean to use '->' instead of '.'?">; + + def err_member_not_yet_instantiated : Error< + "no member %0 in %1; it has not yet been instantiated">; + def note_non_instantiated_member_here : Note< + "not-yet-instantiated member is declared here">; + + def err_enumerator_does_not_exist : Error< + "enumerator %0 does not exist in instantiation of %1">; + def note_enum_specialized_here : Note< + "enum %0 was explicitly specialized here">; + + def err_specialization_not_primary_template : Error< + "cannot reference member of primary template because deduced class " + "template specialization %0 is %select{instantiated from a partial|" + "an explicit}1 specialization">; + + def err_member_redeclared : Error<"class member cannot be redeclared">; + def ext_member_redeclared : ExtWarn<"class member cannot be redeclared">, + InGroup; + def err_member_redeclared_in_instantiation : Error< + "multiple overloads of %0 instantiate to the same signature %1">; + def err_member_name_of_class : Error<"member %0 has the same name as its class">; + def err_member_def_undefined_record : Error< + "out-of-line definition of %0 from class %1 without definition">; + def err_member_decl_does_not_match : Error< + "out-of-line %select{declaration|definition}2 of %0 " + "does not match any declaration in %1">; + def err_friend_decl_with_def_arg_must_be_def : Error< + "friend declaration specifying a default argument must be a definition">; + def err_friend_decl_with_def_arg_redeclared : Error< + "friend declaration specifying a default argument must be the only declaration">; + def err_friend_decl_does_not_match : Error< + "friend declaration of %0 does not match any declaration in %1">; + def err_member_decl_does_not_match_suggest : Error< + "out-of-line %select{declaration|definition}2 of %0 " + "does not match any declaration in %1; did you mean %3?">; + def err_member_def_does_not_match_ret_type : Error< + "return type of out-of-line definition of %q0 differs from " + "that in the declaration">; + def err_nonstatic_member_out_of_line : Error< + "non-static data member defined out-of-line">; + def err_qualified_typedef_declarator : Error< + "typedef declarator cannot be qualified">; + def err_qualified_param_declarator : Error< + "parameter declarator cannot be qualified">; + def ext_out_of_line_declaration : ExtWarn< + "out-of-line declaration of a member must be a definition">, + InGroup, DefaultError; + def err_member_extra_qualification : Error< + "extra qualification on member %0">; + def warn_member_extra_qualification : Warning< + err_member_extra_qualification.Text>, InGroup; + def warn_namespace_member_extra_qualification : Warning< + "extra qualification on member %0">, + InGroup>; + def err_member_qualification : Error< + "non-friend class member %0 cannot have a qualified name">; + def note_member_def_close_match : Note<"member declaration nearly matches">; + def note_member_def_close_const_match : Note< + "member declaration does not match because " + "it %select{is|is not}0 const qualified">; + def note_member_def_close_param_match : Note< + "type of %ordinal0 parameter of member declaration does not match definition" + "%diff{ ($ vs $)|}1,2">; + def note_local_decl_close_match : Note<"local declaration nearly matches">; + def note_local_decl_close_param_match : Note< + "type of %ordinal0 parameter of local declaration does not match definition" + "%diff{ ($ vs $)|}1,2">; + def err_typecheck_ivar_variable_size : Error< + "instance variables must have a constant size">; + def err_ivar_reference_type : Error< + "instance variables cannot be of reference type">; + def err_typecheck_illegal_increment_decrement : Error< + "cannot %select{decrement|increment}1 value of type %0">; + def err_typecheck_expect_int : Error< + "used type %0 where integer is required">; + def err_typecheck_arithmetic_incomplete_or_sizeless_type : Error< + "arithmetic on a pointer to %select{an incomplete|sizeless}0 type %1">; + def err_typecheck_pointer_arith_function_type : Error< + "arithmetic on%select{ a|}0 pointer%select{|s}0 to%select{ the|}2 " + "function type%select{|s}2 %1%select{| and %3}2">; + def err_typecheck_pointer_arith_void_type : Error< + "arithmetic on%select{ a|}0 pointer%select{|s}0 to void">; + def err_typecheck_decl_incomplete_type : Error< + "variable has incomplete type %0">; + def ext_typecheck_decl_incomplete_type : ExtWarn< + "tentative definition of variable with internal linkage has incomplete non-array type %0">, + InGroup>; + def err_tentative_def_incomplete_type : Error< + "tentative definition has type %0 that is never completed">; + def warn_tentative_incomplete_array : Warning< + "tentative array definition assumed to have one element">; + def err_typecheck_incomplete_array_needs_initializer : Error< + "definition of variable with array type needs an explicit size " + "or an initializer">; + def err_array_init_not_init_list : Error< + "array initializer must be an initializer " + "list%select{| or string literal| or wide string literal}0">; + def err_array_init_narrow_string_into_wchar : Error< + "initializing wide char array with non-wide string literal">; + def err_array_init_wide_string_into_char : Error< + "initializing char array with wide string literal">; + def err_array_init_incompat_wide_string_into_wchar : Error< + "initializing wide char array with incompatible wide string literal">; + def err_array_init_plain_string_into_char8_t : Error< + "initializing 'char8_t' array with plain string literal">; + def note_array_init_plain_string_into_char8_t : Note< + "add 'u8' prefix to form a 'char8_t' string literal">; + def err_array_init_utf8_string_into_char : Error< + "%select{|ISO C++20 does not permit }0initialization of char array with " + "UTF-8 string literal%select{ is not permitted by '-fchar8_t'|}0">; + def warn_cxx20_compat_utf8_string : Warning< + "type of UTF-8 string literal will change from array of const char to " + "array of const char8_t in C++20">, InGroup, DefaultIgnore; + def note_cxx20_compat_utf8_string_remove_u8 : Note< + "remove 'u8' prefix to avoid a change of behavior; " + "Clang encodes unprefixed narrow string literals as UTF-8">; + def err_array_init_different_type : Error< + "cannot initialize array %diff{of type $ with array of type $|" + "with different type of array}0,1">; + def err_array_init_non_constant_array : Error< + "cannot initialize array %diff{of type $ with non-constant array of type $|" + "with different type of array}0,1">; + def ext_array_init_copy : Extension< + "initialization of an array " + "%diff{of type $ from a compound literal of type $|" + "from a compound literal}0,1 is a GNU extension">, InGroup; + // This is intentionally not disabled by -Wno-gnu. + def ext_array_init_parens : ExtWarn< + "parenthesized initialization of a member array is a GNU extension">, + InGroup>, DefaultError; + def warn_deprecated_string_literal_conversion : Warning< + "conversion from string literal to %0 is deprecated">, + InGroup; + def ext_deprecated_string_literal_conversion : ExtWarn< + "ISO C++11 does not allow conversion from string literal to %0">, + InGroup, SFINAEFailure; + def err_realimag_invalid_type : Error<"invalid type %0 to %1 operator">; + def err_typecheck_sclass_fscope : Error< + "illegal storage class on file-scoped variable">; + def warn_standalone_specifier : Warning<"'%0' ignored on this declaration">, + InGroup; + def ext_standalone_specifier : ExtWarn<"'%0' is not permitted on a declaration " + "of a type">, InGroup; + def err_standalone_class_nested_name_specifier : Error< + "forward declaration of %select{class|struct|interface|union|enum}0 cannot " + "have a nested name specifier">; + def err_typecheck_sclass_func : Error<"illegal storage class on function">; + def err_static_block_func : Error< + "function declared in block scope cannot have 'static' storage class">; + def err_typecheck_address_of : Error<"address of %select{bit-field" + "|vector element|property expression|register variable|matrix element}0 requested">; + def ext_typecheck_addrof_void : Extension< + "ISO C forbids taking the address of an expression of type 'void'">; + def err_unqualified_pointer_member_function : Error< + "must explicitly qualify name of member function when taking its address">; + def err_invalid_form_pointer_member_function : Error< + "cannot create a non-constant pointer to member function">; + def err_address_of_function_with_pass_object_size_params: Error< + "cannot take address of function %0 because parameter %1 has " + "pass_object_size attribute">; + def err_parens_pointer_member_function : Error< + "cannot parenthesize the name of a method when forming a member pointer">; + def err_typecheck_invalid_lvalue_addrof_addrof_function : Error< + "extra '&' taking address of overloaded function">; + def err_typecheck_invalid_lvalue_addrof : Error< + "cannot take the address of an rvalue of type %0">; + def ext_typecheck_addrof_temporary : ExtWarn< + "taking the address of a temporary object of type %0">, + InGroup, DefaultError; + def err_typecheck_addrof_temporary : Error< + "taking the address of a temporary object of type %0">; + def err_typecheck_addrof_dtor : Error< + "taking the address of a destructor">; + def err_typecheck_unary_expr : Error< + "invalid argument type %0 to unary expression">; + def err_typecheck_indirection_requires_pointer : Error< + "indirection requires pointer operand (%0 invalid)">; + def ext_typecheck_indirection_through_void_pointer : ExtWarn< + "ISO C++ does not allow indirection on operand of type %0">, + InGroup>; + def warn_indirection_through_null : Warning< + "indirection of non-volatile null pointer will be deleted, not trap">, + InGroup; + def warn_binding_null_to_reference : Warning< + "binding dereferenced null pointer to reference has undefined behavior">, + InGroup; + def note_indirection_through_null : Note< + "consider using __builtin_trap() or qualifying pointer with 'volatile'">; + def warn_pointer_indirection_from_incompatible_type : Warning< + "dereference of type %1 that was reinterpret_cast from type %0 has undefined " + "behavior">, + InGroup, DefaultIgnore; + def warn_taking_address_of_packed_member : Warning< + "taking address of packed member %0 of class or structure %q1 may result in an unaligned pointer value">, + InGroup>; + def warn_param_mismatched_alignment : Warning< + "passing %0-byte aligned argument to %1-byte aligned parameter %2 of %3 may result in an unaligned pointer access">, + InGroup>; + + def err_objc_object_assignment : Error< + "cannot assign to class object (%0 invalid)">; + def err_typecheck_invalid_operands : Error< + "invalid operands to binary expression (%0 and %1)">, Deferrable; + def note_typecheck_invalid_operands_converted : Note< + "%select{first|second}0 operand was implicitly converted to type %1">; + def err_typecheck_logical_vector_expr_gnu_cpp_restrict : Error< + "logical expression with vector %select{type %1 and non-vector type %2|types" + " %1 and %2}0 is only supported in C++">; + def err_typecheck_sub_ptr_compatible : Error< + "%diff{$ and $ are not pointers to compatible types|" + "pointers to incompatible types}0,1">; + def ext_typecheck_ordered_comparison_of_pointer_integer : ExtWarn< + "ordered comparison between pointer and integer (%0 and %1)">; + def ext_typecheck_ordered_comparison_of_pointer_and_zero : Extension< + "ordered comparison between pointer and zero (%0 and %1) is an extension">; + def err_typecheck_ordered_comparison_of_pointer_and_zero : Error< + "ordered comparison between pointer and zero (%0 and %1)">; + def err_typecheck_three_way_comparison_of_pointer_and_zero : Error< + "three-way comparison between pointer and zero">; + def ext_typecheck_compare_complete_incomplete_pointers : Extension< + "pointer comparisons before C11 " + "need to be between two complete or two incomplete types; " + "%0 is %select{|in}2complete and " + "%1 is %select{|in}3complete">, + InGroup; + def warn_typecheck_ordered_comparison_of_function_pointers : Warning< + "ordered comparison of function pointers (%0 and %1)">, + InGroup; + def ext_typecheck_ordered_comparison_of_function_pointers : ExtWarn< + "ordered comparison of function pointers (%0 and %1)">, + InGroup; + def err_typecheck_ordered_comparison_of_function_pointers : Error< + "ordered comparison of function pointers (%0 and %1)">; + def ext_typecheck_comparison_of_fptr_to_void : Extension< + "equality comparison between function pointer and void pointer (%0 and %1)">; + def err_typecheck_comparison_of_fptr_to_void : Error< + "equality comparison between function pointer and void pointer (%0 and %1)">; + def ext_typecheck_comparison_of_pointer_integer : ExtWarn< + "comparison between pointer and integer (%0 and %1)">, + InGroup>; + def err_typecheck_comparison_of_pointer_integer : Error< + "comparison between pointer and integer (%0 and %1)">; + def ext_typecheck_comparison_of_distinct_pointers : ExtWarn< + "comparison of distinct pointer types%diff{ ($ and $)|}0,1">, + InGroup; + def ext_typecheck_cond_incompatible_operands : ExtWarn< + "incompatible operand types (%0 and %1)">; + def err_cond_voidptr_arc : Error < + "operands to conditional of types%diff{ $ and $|}0,1 are incompatible " + "in ARC mode">; + def err_typecheck_comparison_of_distinct_pointers : Error< + "comparison of distinct pointer types%diff{ ($ and $)|}0,1">; + def err_typecheck_op_on_nonoverlapping_address_space_pointers : Error< + "%select{comparison between %diff{ ($ and $)|}0,1" + "|arithmetic operation with operands of type %diff{ ($ and $)|}0,1" + "|conditional operator with the second and third operands of type " + "%diff{ ($ and $)|}0,1}2" + " which are pointers to non-overlapping address spaces">; + + def select_arith_conv_kind : TextSubstitution< + "%select{arithmetic between|bitwise operation between|comparison of|" + "conditional expression between|compound assignment of}0">; + def warn_arith_conv_enum_float : Warning< + "%sub{select_arith_conv_kind}0 " + "%select{floating-point|enumeration}1 type %2 " + "%plural{2:with|4:from|:and}0 " + "%select{enumeration|floating-point}1 type %3">, + InGroup, DefaultIgnore; + def warn_arith_conv_enum_float_cxx20 : Warning< + "%sub{select_arith_conv_kind}0 " + "%select{floating-point|enumeration}1 type %2 " + "%plural{2:with|4:from|:and}0 " + "%select{enumeration|floating-point}1 type %3 is deprecated">, + InGroup; + def warn_arith_conv_mixed_enum_types : Warning< + "%sub{select_arith_conv_kind}0 " + "different enumeration types%diff{ ($ and $)|}1,2">, + InGroup, DefaultIgnore; + def warn_arith_conv_mixed_enum_types_cxx20 : Warning< + "%sub{select_arith_conv_kind}0 " + "different enumeration types%diff{ ($ and $)|}1,2 is deprecated">, + InGroup; + def warn_arith_conv_mixed_anon_enum_types : Warning< + warn_arith_conv_mixed_enum_types.Text>, + InGroup, DefaultIgnore; + def warn_arith_conv_mixed_anon_enum_types_cxx20 : Warning< + warn_arith_conv_mixed_enum_types_cxx20.Text>, + InGroup; + def warn_conditional_mixed_enum_types : Warning< + warn_arith_conv_mixed_enum_types.Text>, + InGroup, DefaultIgnore; + def warn_conditional_mixed_enum_types_cxx20 : Warning< + warn_arith_conv_mixed_enum_types_cxx20.Text>, + InGroup; + def warn_comparison_mixed_enum_types : Warning< + warn_arith_conv_mixed_enum_types.Text>, + InGroup; + def warn_comparison_mixed_enum_types_cxx20 : Warning< + warn_arith_conv_mixed_enum_types_cxx20.Text>, + InGroup; + def warn_comparison_of_mixed_enum_types_switch : Warning< + "comparison of different enumeration types in switch statement" + "%diff{ ($ and $)|}0,1">, + InGroup; + + def err_typecheck_assign_const : Error< + "%select{" + "cannot assign to return value because function %1 returns a const value|" + "cannot assign to variable %1 with const-qualified type %2|" + "cannot assign to %select{non-|}1static data member %2 " + "with const-qualified type %3|" + "cannot assign to non-static data member within const member function %1|" + "cannot assign to %select{variable %2|non-static data member %2|lvalue}1 " + "with %select{|nested }3const-qualified data member %4|" + "read-only variable is not assignable}0">; + + def note_typecheck_assign_const : Note< + "%select{" + "function %1 which returns const-qualified type %2 declared here|" + "variable %1 declared const here|" + "%select{non-|}1static data member %2 declared const here|" + "member function %q1 is declared const here|" + "%select{|nested }1data member %2 declared const here}0">; + + def warn_unsigned_always_true_comparison : Warning< + "result of comparison of %select{%3|unsigned expression}0 %2 " + "%select{unsigned expression|%3}0 is always %4">, + InGroup, DefaultIgnore; + def warn_unsigned_char_always_true_comparison : Warning< + "result of comparison of %select{%3|char expression}0 %2 " + "%select{char expression|%3}0 is always %4, since char is interpreted as " + "unsigned">, InGroup, DefaultIgnore; + def warn_unsigned_enum_always_true_comparison : Warning< + "result of comparison of %select{%3|unsigned enum expression}0 %2 " + "%select{unsigned enum expression|%3}0 is always %4">, + InGroup, DefaultIgnore; + def warn_tautological_constant_compare : Warning< + "result of comparison %select{%3|%1}0 %2 " + "%select{%1|%3}0 is always %4">, + InGroup, DefaultIgnore; + def warn_tautological_compare_objc_bool : Warning< + "result of comparison of constant %0 with expression of type 'BOOL'" + " is always %1, as the only well defined values for 'BOOL' are YES and NO">, + InGroup; + def subst_int_range : TextSubstitution<"%0-bit %select{signed|unsigned}1 value">; + def warn_tautological_compare_value_range : Warning< + "result of comparison of " + "%select{%4|%sub{subst_int_range}1,2}0 %3 " + "%select{%sub{subst_int_range}1,2|%4}0 is always %5">, + InGroup, DefaultIgnore; + + def warn_mixed_sign_comparison : Warning< + "comparison of integers of different signs: %0 and %1">, + InGroup, DefaultIgnore; + def warn_out_of_range_compare : Warning< + "result of comparison of %select{constant %0|true|false}1 with " + "%select{expression of type %2|boolean expression}3 is always %4">, + InGroup; + def warn_tautological_bool_compare : Warning, + InGroup; + def warn_integer_constants_in_conditional_always_true : Warning< + "converting the result of '?:' with integer constants to a boolean always " + "evaluates to 'true'">, + InGroup; + def warn_left_shift_always : Warning< + "converting the result of '<<' to a boolean always evaluates " + "to %select{false|true}0">, + InGroup; + def warn_null_in_arithmetic_operation : Warning< + "use of NULL in arithmetic operation">, + InGroup; + def warn_null_in_comparison_operation : Warning< + "comparison between NULL and non-pointer " + "%select{(%1 and NULL)|(NULL and %1)}0">, + InGroup; + def err_shift_rhs_only_vector : Error< + "requested shift is a vector of type %0 but the first operand is not a " + "vector (%1)">; + + def warn_logical_not_on_lhs_of_check : Warning< + "logical not is only applied to the left hand side of this " + "%select{comparison|bitwise operator}0">, + InGroup; + def note_logical_not_fix : Note< + "add parentheses after the '!' to evaluate the " + "%select{comparison|bitwise operator}0 first">; + def note_logical_not_silence_with_parens : Note< + "add parentheses around left hand side expression to silence this warning">; + + def err_invalid_this_use : Error< + "invalid use of 'this' outside of a non-static member function">; + def err_this_static_member_func : Error< + "'this' cannot be%select{| implicitly}0 used in a static member function " + "declaration">; + def err_invalid_member_use_in_static_method : Error< + "invalid use of member %0 in static member function">; + def err_invalid_qualified_function_type : Error< + "%select{non-member function|static member function|deduction guide}0 " + "%select{of type %2 |}1cannot have '%3' qualifier">; + def err_compound_qualified_function_type : Error< + "%select{block pointer|pointer|reference}0 to function type %select{%2 |}1" + "cannot have '%3' qualifier">; + def err_qualified_function_typeid : Error< + "type operand %0 of 'typeid' cannot have '%1' qualifier">; + + def err_ref_qualifier_overload : Error< + "cannot overload a member function %select{without a ref-qualifier|with " + "ref-qualifier '&'|with ref-qualifier '&&'}0 with a member function %select{" + "without a ref-qualifier|with ref-qualifier '&'|with ref-qualifier '&&'}1">; + + def err_invalid_non_static_member_use : Error< + "invalid use of non-static data member %0">; + def err_nested_non_static_member_use : Error< + "%select{call to non-static member function|use of non-static data member}0 " + "%2 of %1 from nested type %3">; + def warn_cxx98_compat_non_static_member_use : Warning< + "use of non-static data member %0 in an unevaluated context is " + "incompatible with C++98">, InGroup, DefaultIgnore; + def err_invalid_incomplete_type_use : Error< + "invalid use of incomplete type %0">; + def err_builtin_func_cast_more_than_one_arg : Error< + "function-style cast to a builtin type can only take one argument">; + def err_value_init_for_array_type : Error< + "array types cannot be value-initialized">; + def err_init_for_function_type : Error< + "cannot create object of function type %0">; + def warn_format_nonliteral_noargs : Warning< + "format string is not a string literal (potentially insecure)">, + InGroup; + def warn_format_nonliteral : Warning< + "format string is not a string literal">, + InGroup, DefaultIgnore; + + def err_unexpected_interface : Error< + "unexpected interface name %0: expected expression">; + def err_ref_non_value : Error<"%0 does not refer to a value">; + def err_ref_vm_type : Error< + "cannot refer to declaration with a variably modified type inside block">; + def err_ref_flexarray_type : Error< + "cannot refer to declaration of structure variable with flexible array member " + "inside block">; + def err_ref_array_type : Error< + "cannot refer to declaration with an array type inside block">; + def err_property_not_found : Error< + "property %0 not found on object of type %1">; + def err_invalid_property_name : Error< + "%0 is not a valid property name (accessing an object of type %1)">; + def err_getter_not_found : Error< + "no getter method for read from property">; + def err_objc_subscript_method_not_found : Error< + "expected method to %select{read|write}1 %select{dictionary|array}2 element not " + "found on object of type %0">; + def err_objc_subscript_index_type : Error< + "method index parameter type %0 is not integral type">; + def err_objc_subscript_key_type : Error< + "method key parameter type %0 is not object type">; + def err_objc_subscript_dic_object_type : Error< + "method object parameter type %0 is not object type">; + def err_objc_subscript_object_type : Error< + "cannot assign to this %select{dictionary|array}1 because assigning method's " + "2nd parameter of type %0 is not an Objective-C pointer type">; + def err_objc_subscript_base_type : Error< + "%select{dictionary|array}1 subscript base type %0 is not an Objective-C object">; + def err_objc_multiple_subscript_type_conversion : Error< + "indexing expression is invalid because subscript type %0 has " + "multiple type conversion functions">; + def err_objc_subscript_type_conversion : Error< + "indexing expression is invalid because subscript type %0 is not an integral" + " or Objective-C pointer type">; + def err_objc_subscript_pointer : Error< + "indexing expression is invalid because subscript type %0 is not an" + " Objective-C pointer">; + def err_objc_indexing_method_result_type : Error< + "method for accessing %select{dictionary|array}1 element must have Objective-C" + " object return type instead of %0">; + def err_objc_index_incomplete_class_type : Error< + "Objective-C index expression has incomplete class type %0">; + def err_illegal_container_subscripting_op : Error< + "illegal operation on Objective-C container subscripting">; + def err_property_not_found_forward_class : Error< + "property %0 cannot be found in forward class object %1">; + def err_property_not_as_forward_class : Error< + "property %0 refers to an incomplete Objective-C class %1 " + "(with no @interface available)">; + def note_forward_class : Note< + "forward declaration of class here">; + def err_duplicate_property : Error< + "property has a previous declaration">; + def ext_gnu_void_ptr : Extension< + "arithmetic on%select{ a|}0 pointer%select{|s}0 to void is a GNU extension">, + InGroup; + def ext_gnu_ptr_func_arith : Extension< + "arithmetic on%select{ a|}0 pointer%select{|s}0 to%select{ the|}2 function " + "type%select{|s}2 %1%select{| and %3}2 is a GNU extension">, + InGroup; + def err_readonly_message_assignment : Error< + "assigning to 'readonly' return result of an Objective-C message not allowed">; + def ext_integer_increment_complex : Extension< + "ISO C does not support '++'/'--' on complex integer type %0">; + def ext_integer_complement_complex : Extension< + "ISO C does not support '~' for complex conjugation of %0">; + def err_nosetter_property_assignment : Error< + "%select{assignment to readonly property|" + "no setter method %1 for assignment to property}0">; + def err_nosetter_property_incdec : Error< + "%select{%select{increment|decrement}1 of readonly property|" + "no setter method %2 for %select{increment|decrement}1 of property}0">; + def err_nogetter_property_compound_assignment : Error< + "a getter method is needed to perform a compound assignment on a property">; + def err_nogetter_property_incdec : Error< + "no getter method %1 for %select{increment|decrement}0 of property">; + def err_no_subobject_property_setting : Error< + "expression is not assignable">; + def err_qualified_objc_access : Error< + "%select{property|instance variable}0 access cannot be qualified with '%1'">; + + def ext_freestanding_complex : Extension< + "complex numbers are an extension in a freestanding C99 implementation">; + + // FIXME: Remove when we support imaginary. + def err_imaginary_not_supported : Error<"imaginary types are not supported">; + + // Obj-c expressions + def warn_root_inst_method_not_found : Warning< + "instance method %0 is being used on 'Class' which is not in the root class">, + InGroup; + def warn_class_method_not_found : Warning< + "class method %objcclass0 not found (return type defaults to 'id')">, + InGroup; + def warn_instance_method_on_class_found : Warning< + "instance method %0 found instead of class method %1">, + InGroup; + def warn_inst_method_not_found : Warning< + "instance method %objcinstance0 not found (return type defaults to 'id')">, + InGroup; + def warn_instance_method_not_found_with_typo : Warning< + "instance method %objcinstance0 not found (return type defaults to 'id')" + "; did you mean %objcinstance2?">, InGroup; + def warn_class_method_not_found_with_typo : Warning< + "class method %objcclass0 not found (return type defaults to 'id')" + "; did you mean %objcclass2?">, InGroup; + def err_method_not_found_with_typo : Error< + "%select{instance|class}1 method %0 not found " + "; did you mean %2?">; + def err_no_super_class_message : Error< + "no @interface declaration found in class messaging of %0">; + def err_root_class_cannot_use_super : Error< + "%0 cannot use 'super' because it is a root class">; + def err_invalid_receiver_to_message_super : Error< + "'super' is only valid in a method body">; + def err_invalid_receiver_class_message : Error< + "receiver type %0 is not an Objective-C class">; + def err_missing_open_square_message_send : Error< + "missing '[' at start of message send expression">; + def warn_bad_receiver_type : Warning< + "receiver type %0 is not 'id' or interface pointer, consider " + "casting it to 'id'">,InGroup; + def err_bad_receiver_type : Error<"bad receiver type %0">; + def err_incomplete_receiver_type : Error<"incomplete receiver type %0">; + def err_unknown_receiver_suggest : Error< + "unknown receiver %0; did you mean %1?">; + def err_objc_throw_expects_object : Error< + "@throw requires an Objective-C object type (%0 invalid)">; + def err_objc_synchronized_expects_object : Error< + "@synchronized requires an Objective-C object type (%0 invalid)">; + def err_rethrow_used_outside_catch : Error< + "@throw (rethrow) used outside of a @catch block">; + def err_attribute_multiple_objc_gc : Error< + "multiple garbage collection attributes specified for type">; + def err_catch_param_not_objc_type : Error< + "@catch parameter is not a pointer to an interface type">; + def err_illegal_qualifiers_on_catch_parm : Error< + "illegal qualifiers on @catch parameter">; + def err_storage_spec_on_catch_parm : Error< + "@catch parameter cannot have storage specifier '%0'">; + def warn_register_objc_catch_parm : Warning< + "'register' storage specifier on @catch parameter will be ignored">; + def err_qualified_objc_catch_parm : Error< + "@catch parameter declarator cannot be qualified">; + def warn_objc_pointer_cxx_catch_fragile : Warning< + "cannot catch an exception thrown with @throw in C++ in the non-unified " + "exception model">, InGroup; + def err_objc_object_catch : Error< + "cannot catch an Objective-C object by value">; + def err_incomplete_type_objc_at_encode : Error< + "'@encode' of incomplete type %0">; + def warn_objc_circular_container : Warning< + "adding %0 to %1 might cause circular dependency in container">, + InGroup>; + def note_objc_circular_container_declared_here : Note<"%0 declared here">; + def warn_objc_unsafe_perform_selector : Warning< + "%0 is incompatible with selectors that return a " + "%select{struct|union|vector}1 type">, + InGroup>; + def note_objc_unsafe_perform_selector_method_declared_here : Note< + "method %0 that returns %1 declared here">; + def err_attribute_arm_builtin_alias : Error< + "'__clang_arm_builtin_alias' attribute can only be applied to an ARM builtin">; + def err_attribute_arm_mve_polymorphism : Error< + "'__clang_arm_mve_strict_polymorphism' attribute can only be applied to an MVE/NEON vector type">; + + def warn_setter_getter_impl_required : Warning< + "property %0 requires method %1 to be defined - " + "use @synthesize, @dynamic or provide a method implementation " + "in this class implementation">, + InGroup; + def warn_setter_getter_impl_required_in_category : Warning< + "property %0 requires method %1 to be defined - " + "use @dynamic or provide a method implementation in this category">, + InGroup; + def note_parameter_named_here : Note< + "passing argument to parameter %0 here">; + def note_parameter_here : Note< + "passing argument to parameter here">; + def note_method_return_type_change : Note< + "compiler has implicitly changed method %0 return type">; + + def warn_impl_required_for_class_property : Warning< + "class property %0 requires method %1 to be defined - " + "use @dynamic or provide a method implementation " + "in this class implementation">, + InGroup; + def warn_impl_required_in_category_for_class_property : Warning< + "class property %0 requires method %1 to be defined - " + "use @dynamic or provide a method implementation in this category">, + InGroup; + + // C++ casts + // These messages adhere to the TryCast pattern: %0 is an int specifying the + // cast type, %1 is the source type, %2 is the destination type. + def err_bad_reinterpret_cast_overload : Error< + "reinterpret_cast cannot resolve overloaded function %0 to type %1">; + + def warn_reinterpret_different_from_static : Warning< + "'reinterpret_cast' %select{from|to}3 class %0 %select{to|from}3 its " + "%select{virtual base|base at non-zero offset}2 %1 behaves differently from " + "'static_cast'">, InGroup; + def note_reinterpret_updowncast_use_static: Note< + "use 'static_cast' to adjust the pointer correctly while " + "%select{upcasting|downcasting}0">; + + def err_bad_static_cast_overload : Error< + "address of overloaded function %0 cannot be static_cast to type %1">; + + def err_bad_cstyle_cast_overload : Error< + "address of overloaded function %0 cannot be cast to type %1">; + + + def err_bad_cxx_cast_generic : Error< + "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|" + "C-style cast|functional-style cast|addrspace_cast}0 from %1 to %2 is not allowed">; + def err_bad_cxx_cast_unrelated_class : Error< + "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|" + "functional-style cast|}0 from %1 to %2, which are not related by " + "inheritance, is not allowed">; + def note_type_incomplete : Note<"%0 is incomplete">; + def err_bad_cxx_cast_rvalue : Error< + "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|" + "functional-style cast|addrspace_cast}0 from rvalue to reference type %2">; + def err_bad_cxx_cast_bitfield : Error< + "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|" + "functional-style cast|}0 from bit-field lvalue to reference type %2">; + def err_bad_cxx_cast_qualifiers_away : Error< + "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|" + "functional-style cast|}0 from %1 to %2 casts away qualifiers">; + def err_bad_cxx_cast_addr_space_mismatch : Error< + "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|" + "C-style cast|functional-style cast|addrspace_cast}0 from %1 to %2 converts between mismatching address" + " spaces">; + def ext_bad_cxx_cast_qualifiers_away_incoherent : ExtWarn< + "ISO C++ does not allow " + "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|" + "functional-style cast|}0 from %1 to %2 because it casts away qualifiers, " + "even though the source and destination types are unrelated">, + SFINAEFailure, InGroup>; + def err_bad_const_cast_dest : Error< + "%select{const_cast||||C-style cast|functional-style cast|}0 to %2, " + "which is not a reference, pointer-to-object, or pointer-to-data-member">; + def ext_cast_fn_obj : Extension< + "cast between pointer-to-function and pointer-to-object is an extension">; + def ext_ms_cast_fn_obj : ExtWarn< + "static_cast between pointer-to-function and pointer-to-object is a " + "Microsoft extension">, InGroup; + def warn_cxx98_compat_cast_fn_obj : Warning< + "cast between pointer-to-function and pointer-to-object is incompatible with C++98">, + InGroup, DefaultIgnore; + def err_bad_reinterpret_cast_small_int : Error< + "cast from pointer to smaller type %2 loses information">; + def err_bad_cxx_cast_vector_to_scalar_different_size : Error< + "%select{||reinterpret_cast||C-style cast||}0 from vector %1 " + "to scalar %2 of different size">; + def err_bad_cxx_cast_scalar_to_vector_different_size : Error< + "%select{||reinterpret_cast||C-style cast||}0 from scalar %1 " + "to vector %2 of different size">; + def err_bad_cxx_cast_vector_to_vector_different_size : Error< + "%select{||reinterpret_cast||C-style cast||}0 from vector %1 " + "to vector %2 of different size">; + def warn_bad_cxx_cast_nested_pointer_addr_space : Warning< + "%select{reinterpret_cast|C-style cast}0 from %1 to %2 " + "changes address space of nested pointers">, + InGroup; + def err_bad_lvalue_to_rvalue_cast : Error< + "cannot cast from lvalue of type %1 to rvalue reference type %2; types are " + "not compatible">; + def err_bad_rvalue_to_rvalue_cast : Error< + "cannot cast from rvalue of type %1 to rvalue reference type %2; types are " + "not compatible">; + def err_bad_static_cast_pointer_nonpointer : Error< + "cannot cast from type %1 to pointer type %2">; + def err_bad_static_cast_member_pointer_nonmp : Error< + "cannot cast from type %1 to member pointer type %2">; + def err_bad_cxx_cast_member_pointer_size : Error< + "cannot %select{||reinterpret_cast||C-style cast||}0 from member pointer " + "type %1 to member pointer type %2 of different size">; + def err_bad_reinterpret_cast_reference : Error< + "reinterpret_cast of a %0 to %1 needs its address, which is not allowed">; + def warn_undefined_reinterpret_cast : Warning< + "reinterpret_cast from %0 to %1 has undefined behavior">, + InGroup, DefaultIgnore; + + // These messages don't adhere to the pattern. + // FIXME: Display the path somehow better. + def err_ambiguous_base_to_derived_cast : Error< + "ambiguous cast from base %0 to derived %1:%2">; + def err_static_downcast_via_virtual : Error< + "cannot cast %0 to %1 via virtual base %2">; + def err_downcast_from_inaccessible_base : Error< + "cannot cast %select{private|protected}2 base class %1 to %0">; + def err_upcast_to_inaccessible_base : Error< + "cannot cast %0 to its %select{private|protected}2 base class %1">; + def err_bad_dynamic_cast_not_ref_or_ptr : Error< + "invalid target type %0 for dynamic_cast; target type must be a reference or pointer type to a defined class">; + def err_bad_dynamic_cast_not_class : Error<"%0 is not a class type">; + def err_bad_cast_incomplete : Error<"%0 is an incomplete type">; + def err_bad_dynamic_cast_not_ptr : Error<"cannot use dynamic_cast to convert from %0 to %1">; + def err_bad_dynamic_cast_not_polymorphic : Error<"%0 is not polymorphic">; + + // Other C++ expressions + def err_need_header_before_typeid : Error< + "you need to include before using the 'typeid' operator">; + def err_need_header_before_ms_uuidof : Error< + "you need to include before using the '__uuidof' operator">; + def err_need_header_before_placement_new : Error< + "no matching %0 function for non-allocating placement new expression; " + "include ">; + def err_ms___leave_not_in___try : Error< + "'__leave' statement not in __try block">; + def err_uuidof_without_guid : Error< + "cannot call operator __uuidof on a type with no GUID">; + def err_uuidof_with_multiple_guids : Error< + "cannot call operator __uuidof on a type with multiple GUIDs">; + def err_incomplete_typeid : Error<"'typeid' of incomplete type %0">; + def err_variably_modified_typeid : Error<"'typeid' of variably modified type %0">; + def err_static_illegal_in_new : Error< + "the 'static' modifier for the array size is not legal in new expressions">; + def err_array_new_needs_size : Error< + "array size must be specified in new expression with no initializer">; + def err_bad_new_type : Error< + "cannot allocate %select{function|reference}1 type %0 with new">; + def err_new_incomplete_or_sizeless_type : Error< + "allocation of %select{incomplete|sizeless}0 type %1">; + def err_new_array_nonconst : Error< + "only the first dimension of an allocated array may have dynamic size">; + def err_new_array_size_unknown_from_init : Error< + "cannot determine allocated array size from initializer">; + def err_new_array_init_args : Error< + "array 'new' cannot have initialization arguments">; + def ext_new_paren_array_nonconst : ExtWarn< + "when type is in parentheses, array cannot have dynamic size">; + def err_placement_new_non_placement_delete : Error< + "'new' expression with placement arguments refers to non-placement " + "'operator delete'">; + def err_array_size_not_integral : Error< + "array size expression must have integral or %select{|unscoped }0" + "enumeration type, not %1">; + def err_array_size_incomplete_type : Error< + "array size expression has incomplete class type %0">; + def err_array_size_explicit_conversion : Error< + "array size expression of type %0 requires explicit conversion to type %1">; + def note_array_size_conversion : Note< + "conversion to %select{integral|enumeration}0 type %1 declared here">; + def err_array_size_ambiguous_conversion : Error< + "ambiguous conversion of array size expression of type %0 to an integral or " + "enumeration type">; + def ext_array_size_conversion : Extension< + "implicit conversion from array size expression of type %0 to " + "%select{integral|enumeration}1 type %2 is a C++11 extension">, + InGroup; + def warn_cxx98_compat_array_size_conversion : Warning< + "implicit conversion from array size expression of type %0 to " + "%select{integral|enumeration}1 type %2 is incompatible with C++98">, + InGroup, DefaultIgnore; + def err_address_space_qualified_new : Error< + "'new' cannot allocate objects of type %0 in address space '%1'">; + def err_address_space_qualified_delete : Error< + "'delete' cannot delete objects of type %0 in address space '%1'">; + + def err_default_init_const : Error< + "default initialization of an object of const type %0" + "%select{| without a user-provided default constructor}1">; + def ext_default_init_const : ExtWarn< + "default initialization of an object of const type %0" + "%select{| without a user-provided default constructor}1 " + "is a Microsoft extension">, + InGroup; + def err_delete_operand : Error<"cannot delete expression of type %0">; + def ext_delete_void_ptr_operand : ExtWarn< + "cannot delete expression with pointer-to-'void' type %0">, + InGroup; + def err_ambiguous_delete_operand : Error< + "ambiguous conversion of delete expression of type %0 to a pointer">; + def warn_delete_incomplete : Warning< + "deleting pointer to incomplete type %0 may cause undefined behavior">, + InGroup; + def err_delete_incomplete_class_type : Error< + "deleting incomplete class type %0; no conversions to pointer type">; + def err_delete_explicit_conversion : Error< + "converting delete expression from type %0 to type %1 invokes an explicit " + "conversion function">; + def note_delete_conversion : Note<"conversion to pointer type %0">; + def warn_delete_array_type : Warning< + "'delete' applied to a pointer-to-array type %0 treated as 'delete[]'">; + def warn_mismatched_delete_new : Warning< + "'delete%select{|[]}0' applied to a pointer that was allocated with " + "'new%select{[]|}0'; did you mean 'delete%select{[]|}0'?">, + InGroup>; + def note_allocated_here : Note<"allocated with 'new%select{[]|}0' here">; + def err_no_suitable_delete_member_function_found : Error< + "no suitable member %0 in %1">; + def err_ambiguous_suitable_delete_member_function_found : Error< + "multiple suitable %0 functions in %1">; + def warn_ambiguous_suitable_delete_function_found : Warning< + "multiple suitable %0 functions for %1; no 'operator delete' function " + "will be invoked if initialization throws an exception">, + InGroup>; + def note_member_declared_here : Note< + "member %0 declared here">; + def note_member_first_declared_here : Note< + "member %0 first declared here">; ++def warn_bitwise_instead_of_logical : Warning< ++ "use of bitwise '%0' with boolean operands">, ++ InGroup, DefaultIgnore; + def warn_bitwise_negation_bool : Warning< + "bitwise negation of a boolean expression%select{;| always evaluates to 'true';}0 " + "did you mean logical negation?">, + InGroup, DefaultIgnore; + def err_decrement_bool : Error<"cannot decrement expression of type bool">; + def warn_increment_bool : Warning< + "incrementing expression of type bool is deprecated and " + "incompatible with C++17">, InGroup; + def ext_increment_bool : ExtWarn< + "ISO C++17 does not allow incrementing expression of type bool">, + DefaultError, InGroup; + def err_increment_decrement_enum : Error< + "cannot %select{decrement|increment}0 expression of enum type %1">; + + def warn_deprecated_increment_decrement_volatile : Warning< + "%select{decrement|increment}0 of object of volatile-qualified type %1 " + "is deprecated">, InGroup; + def warn_deprecated_simple_assign_volatile : Warning< + "use of result of assignment to object of volatile-qualified type %0 " + "is deprecated">, InGroup; + def warn_deprecated_compound_assign_volatile : Warning< + "compound assignment to object of volatile-qualified type %0 is deprecated">, + InGroup; + def warn_deprecated_volatile_return : Warning< + "volatile-qualified return type %0 is deprecated">, + InGroup; + def warn_deprecated_volatile_param : Warning< + "volatile-qualified parameter type %0 is deprecated">, + InGroup; + def warn_deprecated_volatile_structured_binding : Warning< + "volatile qualifier in structured binding declaration is deprecated">, + InGroup; + + def warn_deprecated_altivec_src_compat : Warning< + "Current handling of vector bool and vector pixel types in this context are " + "deprecated. The default behaviour will soon change to that implied by the " + "'-altivec-compat=xl' option">, + InGroup>; + + def err_catch_incomplete_ptr : Error< + "cannot catch pointer to incomplete type %0">; + def err_catch_incomplete_ref : Error< + "cannot catch reference to incomplete type %0">; + def err_catch_incomplete : Error<"cannot catch incomplete type %0">; + def err_catch_sizeless : Error< + "cannot catch %select{|reference to }0sizeless type %1">; + def err_catch_rvalue_ref : Error<"cannot catch exceptions by rvalue reference">; + def err_catch_variably_modified : Error< + "cannot catch variably modified type %0">; + def err_qualified_catch_declarator : Error< + "exception declarator cannot be qualified">; + def err_early_catch_all : Error<"catch-all handler must come last">; + def err_bad_memptr_rhs : Error< + "right hand operand to %0 has non-pointer-to-member type %1">; + def err_bad_memptr_lhs : Error< + "left hand operand to %0 must be a %select{|pointer to }1class " + "compatible with the right hand operand, but is %2">; + def err_memptr_incomplete : Error< + "member pointer has incomplete base type %0">; + def warn_exception_caught_by_earlier_handler : Warning< + "exception of type %0 will be caught by earlier handler">, + InGroup; + def note_previous_exception_handler : Note<"for type %0">; + def err_exceptions_disabled : Error< + "cannot use '%0' with exceptions disabled">; + def err_objc_exceptions_disabled : Error< + "cannot use '%0' with Objective-C exceptions disabled">; + def warn_throw_in_noexcept_func : Warning< + "%0 has a non-throwing exception specification but can still throw">, + InGroup; + def note_throw_in_dtor : Note< + "%select{destructor|deallocator}0 has a %select{non-throwing|implicit " + "non-throwing}1 exception specification">; + def note_throw_in_function : Note<"function declared non-throwing here">; + def err_seh_try_outside_functions : Error< + "cannot use SEH '__try' in blocks, captured regions, or Obj-C method decls">; + def err_mixing_cxx_try_seh_try : Error< + "cannot use C++ 'try' in the same function as SEH '__try'">; + def err_seh_try_unsupported : Error< + "SEH '__try' is not supported on this target">; + def note_conflicting_try_here : Note< + "conflicting %0 here">; + def warn_jump_out_of_seh_finally : Warning< + "jump out of __finally block has undefined behavior">, + InGroup>; + def warn_non_virtual_dtor : Warning< + "%0 has virtual functions but non-virtual destructor">, + InGroup, DefaultIgnore; + def warn_delete_non_virtual_dtor : Warning< + "%select{delete|destructor}0 called on non-final %1 that has " + "virtual functions but non-virtual destructor">, + InGroup, DefaultIgnore, ShowInSystemHeader; + def note_delete_non_virtual : Note< + "qualify call to silence this warning">; + def warn_delete_abstract_non_virtual_dtor : Warning< + "%select{delete|destructor}0 called on %1 that is abstract but has " + "non-virtual destructor">, InGroup, ShowInSystemHeader; + def warn_overloaded_virtual : Warning< + "%q0 hides overloaded virtual %select{function|functions}1">, + InGroup, DefaultIgnore; + def note_hidden_overloaded_virtual_declared_here : Note< + "hidden overloaded virtual function %q0 declared here" + "%select{|: different classes%diff{ ($ vs $)|}2,3" + "|: different number of parameters (%2 vs %3)" + "|: type mismatch at %ordinal2 parameter%diff{ ($ vs $)|}3,4" + "|: different return type%diff{ ($ vs $)|}2,3" + "|: different qualifiers (%2 vs %3)" + "|: different exception specifications}1">; + def warn_using_directive_in_header : Warning< + "using namespace directive in global context in header">, + InGroup, DefaultIgnore; + def warn_overaligned_type : Warning< + "type %0 requires %1 bytes of alignment and the default allocator only " + "guarantees %2 bytes">, + InGroup, DefaultIgnore; + def err_aligned_allocation_unavailable : Error< + "aligned %select{allocation|deallocation}0 function of type '%1' is " + "%select{only|not}4 available on %2%select{ %3 or newer|}4">; + def note_silence_aligned_allocation_unavailable : Note< + "if you supply your own aligned allocation functions, use " + "-faligned-allocation to silence this diagnostic">; + + def err_conditional_void_nonvoid : Error< + "%select{left|right}1 operand to ? is void, but %select{right|left}1 operand " + "is of type %0">; + def err_conditional_ambiguous : Error< + "conditional expression is ambiguous; " + "%diff{$ can be converted to $ and vice versa|" + "types can be convert to each other}0,1">; + def err_conditional_ambiguous_ovl : Error< + "conditional expression is ambiguous; %diff{$ and $|types}0,1 " + "can be converted to several common types">; + def err_conditional_vector_size : Error< + "vector condition type %0 and result type %1 do not have the same number " + "of elements">; + def err_conditional_vector_element_size : Error< + "vector condition type %0 and result type %1 do not have elements of the " + "same size">; + def err_conditional_vector_has_void : Error< + "GNU vector conditional operand cannot be %select{void|a throw expression}0">; + def err_conditional_vector_operand_type + : Error<"enumeration type %0 is not allowed in a vector conditional">; + def err_conditional_vector_cond_result_mismatch + : Error<"cannot mix vectors and extended vectors in a vector conditional">; + def err_conditional_vector_mismatched + : Error<"vector operands to the vector conditional must be the same type " + "%diff{($ and $)|}0,1}">; + + def err_throw_incomplete : Error< + "cannot throw object of incomplete type %0">; + def err_throw_incomplete_ptr : Error< + "cannot throw pointer to object of incomplete type %0">; + def err_throw_sizeless : Error< + "cannot throw object of sizeless type %0">; + def warn_throw_underaligned_obj : Warning< + "underaligned exception object thrown">, + InGroup; + def note_throw_underaligned_obj : Note< + "required alignment of type %0 (%1 bytes) is larger than the supported " + "alignment of C++ exception objects on this target (%2 bytes)">; + def err_return_in_constructor_handler : Error< + "return in the catch of a function try block of a constructor is illegal">; + def warn_cdtor_function_try_handler_mem_expr : Warning< + "cannot refer to a non-static member from the handler of a " + "%select{constructor|destructor}0 function try block">, InGroup; + + let CategoryName = "Lambda Issue" in { + def err_capture_more_than_once : Error< + "%0 can appear only once in a capture list">; + def err_reference_capture_with_reference_default : Error< + "'&' cannot precede a capture when the capture default is '&'">; + def err_copy_capture_with_copy_default : Error< + "'&' must precede a capture when the capture default is '='">; + def err_capture_does_not_name_variable : Error< + "%0 in capture list does not name a variable">; + def err_capture_non_automatic_variable : Error< + "%0 cannot be captured because it does not have automatic storage " + "duration">; + def err_this_capture : Error< + "'this' cannot be %select{implicitly |}0captured in this context">; + def note_lambda_this_capture_fixit : Note< + "explicitly capture 'this'">; + def err_lambda_capture_anonymous_var : Error< + "unnamed variable cannot be implicitly captured in a lambda expression">; + def err_lambda_capture_flexarray_type : Error< + "variable %0 with flexible array member cannot be captured in " + "a lambda expression">; + def err_lambda_impcap : Error< + "variable %0 cannot be implicitly captured in a lambda with no " + "capture-default specified">; + def note_lambda_variable_capture_fixit : Note< + "capture %0 by %select{value|reference}1">; + def note_lambda_default_capture_fixit : Note< + "default capture by %select{value|reference}0">; + def note_lambda_decl : Note<"lambda expression begins here">; + def err_lambda_unevaluated_operand : Error< + "lambda expression in an unevaluated operand">; + def err_lambda_in_constant_expression : Error< + "a lambda expression may not appear inside of a constant expression">; + def err_lambda_in_invalid_context : Error< + "a lambda expression cannot appear in this context">; + def err_lambda_return_init_list : Error< + "cannot deduce lambda return type from initializer list">; + def err_lambda_capture_default_arg : Error< + "lambda expression in default argument cannot capture any entity">; + def err_lambda_incomplete_result : Error< + "incomplete result type %0 in lambda expression">; + def err_noreturn_lambda_has_return_expr : Error< + "lambda declared 'noreturn' should not return">; + def warn_maybe_falloff_nonvoid_lambda : Warning< + "non-void lambda does not return a value in all control paths">, + InGroup; + def warn_falloff_nonvoid_lambda : Warning< + "non-void lambda does not return a value">, + InGroup; + def err_access_lambda_capture : Error< + // The ERRORs represent other special members that aren't constructors, in + // hopes that someone will bother noticing and reporting if they appear + "capture of variable '%0' as type %1 calls %select{private|protected}3 " + "%select{default |copy |move |*ERROR* |*ERROR* |*ERROR* |}2constructor">, + AccessControl; + def note_lambda_to_block_conv : Note< + "implicit capture of lambda object due to conversion to block pointer " + "here">; + def note_var_explicitly_captured_here : Note<"variable %0 is" + "%select{| explicitly}1 captured here">; + + // C++14 lambda init-captures. + def warn_cxx11_compat_init_capture : Warning< + "initialized lambda captures are incompatible with C++ standards " + "before C++14">, InGroup, DefaultIgnore; + def ext_init_capture : ExtWarn< + "initialized lambda captures are a C++14 extension">, InGroup; + def err_init_capture_no_expression : Error< + "initializer missing for lambda capture %0">; + def err_init_capture_multiple_expressions : Error< + "initializer for lambda capture %0 contains multiple expressions">; + def err_init_capture_paren_braces : Error< + "cannot deduce type for lambda capture %1 from " + "%select{parenthesized|nested}0 initializer list">; + def err_init_capture_deduction_failure : Error< + "cannot deduce type for lambda capture %0 from initializer of type %2">; + def err_init_capture_deduction_failure_from_init_list : Error< + "cannot deduce type for lambda capture %0 from initializer list">; + def warn_cxx17_compat_init_capture_pack : Warning< + "initialized lambda capture packs are incompatible with C++ standards " + "before C++20">, InGroup, DefaultIgnore; + def ext_init_capture_pack : ExtWarn< + "initialized lambda pack captures are a C++20 extension">, InGroup; + + // C++14 generic lambdas. + def warn_cxx11_compat_generic_lambda : Warning< + "generic lambdas are incompatible with C++11">, + InGroup, DefaultIgnore; + + // C++17 '*this' captures. + def warn_cxx14_compat_star_this_lambda_capture : Warning< + "by value capture of '*this' is incompatible with C++ standards before C++17">, + InGroup, DefaultIgnore; + def ext_star_this_lambda_capture_cxx17 : ExtWarn< + "capture of '*this' by copy is a C++17 extension">, InGroup; + + // C++17 parameter shadows capture + def err_parameter_shadow_capture : Error< + "a lambda parameter cannot shadow an explicitly captured entity">; + + // C++20 [=, this] captures. + def warn_cxx17_compat_equals_this_lambda_capture : Warning< + "explicit capture of 'this' with a capture default of '=' is incompatible " + "with C++ standards before C++20">, InGroup, DefaultIgnore; + def ext_equals_this_lambda_capture_cxx20 : ExtWarn< + "explicit capture of 'this' with a capture default of '=' " + "is a C++20 extension">, InGroup; + def warn_deprecated_this_capture : Warning< + "implicit capture of 'this' with a capture default of '=' is deprecated">, + InGroup, DefaultIgnore; + def note_deprecated_this_capture : Note< + "add an explicit capture of 'this' to capture '*this' by reference">; + + // C++20 default constructible / assignable lambdas. + def warn_cxx17_compat_lambda_def_ctor_assign : Warning< + "%select{default construction|assignment}0 of lambda is incompatible with " + "C++ standards before C++20">, InGroup, DefaultIgnore; + } + + def err_return_in_captured_stmt : Error< + "cannot return from %0">; + def err_capture_block_variable : Error< + "__block variable %0 cannot be captured in a " + "%select{lambda expression|captured statement}1">; + + def err_operator_arrow_circular : Error< + "circular pointer delegation detected">; + def err_operator_arrow_depth_exceeded : Error< + "use of 'operator->' on type %0 would invoke a sequence of more than %1 " + "'operator->' calls">; + def note_operator_arrow_here : Note< + "'operator->' declared here produces an object of type %0">; + def note_operator_arrows_suppressed : Note< + "(skipping %0 'operator->'%s0 in backtrace)">; + def note_operator_arrow_depth : Note< + "use -foperator-arrow-depth=N to increase 'operator->' limit">; + + def err_pseudo_dtor_base_not_scalar : Error< + "object expression of non-scalar type %0 cannot be used in a " + "pseudo-destructor expression">; + def ext_pseudo_dtor_on_void : ExtWarn< + "pseudo-destructors on type void are a Microsoft extension">, + InGroup; + def err_pseudo_dtor_type_mismatch : Error< + "the type of object expression " + "%diff{($) does not match the type being destroyed ($)|" + "does not match the type being destroyed}0,1 " + "in pseudo-destructor expression">; + def err_pseudo_dtor_call_with_args : Error< + "call to pseudo-destructor cannot have any arguments">; + def err_dtor_expr_without_call : Error< + "reference to %select{destructor|pseudo-destructor}0 must be called" + "%select{|; did you mean to call it with no arguments?}1">; + def err_pseudo_dtor_destructor_non_type : Error< + "%0 does not refer to a type name in pseudo-destructor expression; expected " + "the name of type %1">; + def err_invalid_use_of_function_type : Error< + "a function type is not allowed here">; + def err_invalid_use_of_array_type : Error<"an array type is not allowed here">; + def err_typecheck_bool_condition : Error< + "value of type %0 is not contextually convertible to 'bool'">; + def err_typecheck_ambiguous_condition : Error< + "conversion %diff{from $ to $|between types}0,1 is ambiguous">; + def err_typecheck_nonviable_condition : Error< + "no viable conversion%select{%diff{ from $ to $|}1,2|" + "%diff{ from returned value of type $ to function return type $|}1,2}0">; + def err_typecheck_nonviable_condition_incomplete : Error< + "no viable conversion%diff{ from $ to incomplete type $|}0,1">; + def err_typecheck_deleted_function : Error< + "conversion function %diff{from $ to $|between types}0,1 " + "invokes a deleted function">; + + def err_expected_class_or_namespace : Error<"%0 is not a class" + "%select{ or namespace|, namespace, or enumeration}1">; + def err_invalid_declarator_scope : Error<"cannot define or redeclare %0 here " + "because namespace %1 does not enclose namespace %2">; + def err_invalid_declarator_global_scope : Error< + "definition or redeclaration of %0 cannot name the global scope">; + def err_invalid_declarator_in_function : Error< + "definition or redeclaration of %0 not allowed inside a function">; + def err_invalid_declarator_in_block : Error< + "definition or redeclaration of %0 not allowed inside a block">; + def err_not_tag_in_scope : Error< + "no %select{struct|interface|union|class|enum}0 named %1 in %2">; + + def err_no_typeid_with_fno_rtti : Error< + "use of typeid requires -frtti">; + def err_no_dynamic_cast_with_fno_rtti : Error< + "use of dynamic_cast requires -frtti">; + def warn_no_dynamic_cast_with_rtti_disabled: Warning< + "dynamic_cast will not work since RTTI data is disabled by " + "%select{-fno-rtti-data|/GR-}0">, InGroup; + def warn_no_typeid_with_rtti_disabled: Warning< + "typeid will not work since RTTI data is disabled by " + "%select{-fno-rtti-data|/GR-}0">, InGroup; + + def err_cannot_form_pointer_to_member_of_reference_type : Error< + "cannot form a pointer-to-member to member %0 of reference type %1">; + def err_incomplete_object_call : Error< + "incomplete type in call to object of type %0">; + + def warn_condition_is_assignment : Warning<"using the result of an " + "assignment as a condition without parentheses">, + InGroup; + def warn_free_nonheap_object + : Warning<"attempt to call %0 on non-heap %select{object %2|object: block expression|object: lambda-to-function-pointer conversion}1">, + InGroup; + + // Completely identical except off by default. + def warn_condition_is_idiomatic_assignment : Warning<"using the result " + "of an assignment as a condition without parentheses">, + InGroup>, DefaultIgnore; + def note_condition_assign_to_comparison : Note< + "use '==' to turn this assignment into an equality comparison">; + def note_condition_or_assign_to_comparison : Note< + "use '!=' to turn this compound assignment into an inequality comparison">; + def note_condition_assign_silence : Note< + "place parentheses around the assignment to silence this warning">; + + def warn_equality_with_extra_parens : Warning<"equality comparison with " + "extraneous parentheses">, InGroup; + def note_equality_comparison_to_assign : Note< + "use '=' to turn this equality comparison into an assignment">; + def note_equality_comparison_silence : Note< + "remove extraneous parentheses around the comparison to silence this warning">; + + // assignment related diagnostics (also for argument passing, returning, etc). + // In most of these diagnostics the %2 is a value from the + // Sema::AssignmentAction enumeration + def err_typecheck_convert_incompatible : Error< + "%select{%diff{assigning to $ from incompatible type $|" + "assigning to type from incompatible type}0,1" + "|%diff{passing $ to parameter of incompatible type $|" + "passing type to parameter of incompatible type}0,1" + "|%diff{returning $ from a function with incompatible result type $|" + "returning type from a function with incompatible result type}0,1" + "|%diff{converting $ to incompatible type $|" + "converting type to incompatible type}0,1" + "|%diff{initializing $ with an expression of incompatible type $|" + "initializing type with an expression of incompatible type}0,1" + "|%diff{sending $ to parameter of incompatible type $|" + "sending type to parameter of incompatible type}0,1" + "|%diff{casting $ to incompatible type $|" + "casting type to incompatible type}0,1}2" + "%select{|; dereference with *|" + "; take the address with &|" + "; remove *|" + "; remove &}3" + "%select{|: different classes%diff{ ($ vs $)|}5,6" + "|: different number of parameters (%5 vs %6)" + "|: type mismatch at %ordinal5 parameter%diff{ ($ vs $)|}6,7" + "|: different return type%diff{ ($ vs $)|}5,6" + "|: different qualifiers (%5 vs %6)" + "|: different exception specifications}4">; + def err_typecheck_missing_return_type_incompatible : Error< + "%diff{return type $ must match previous return type $|" + "return type must match previous return type}0,1 when %select{block " + "literal|lambda expression}2 has unspecified explicit return type">; + + def note_incomplete_class_and_qualified_id : Note< + "conformance of forward class %0 to protocol %1 can not be confirmed">; + def warn_incompatible_qualified_id : Warning< + "%select{%diff{assigning to $ from incompatible type $|" + "assigning to type from incompatible type}0,1" + "|%diff{passing $ to parameter of incompatible type $|" + "passing type to parameter of incompatible type}0,1" + "|%diff{returning $ from a function with incompatible result type $|" + "returning type from a function with incompatible result type}0,1" + "|%diff{converting $ to incompatible type $|" + "converting type to incompatible type}0,1" + "|%diff{initializing $ with an expression of incompatible type $|" + "initializing type with an expression of incompatible type}0,1" + "|%diff{sending $ to parameter of incompatible type $|" + "sending type to parameter of incompatible type}0,1" + "|%diff{casting $ to incompatible type $|" + "casting type to incompatible type}0,1}2">; + def err_incompatible_qualified_id : Error< + "%select{%diff{assigning to $ from incompatible type $|" + "assigning to type from incompatible type}0,1" + "|%diff{passing $ to parameter of incompatible type $|" + "passing type to parameter of incompatible type}0,1" + "|%diff{returning $ from a function with incompatible result type $|" + "returning type from a function with incompatible result type}0,1" + "|%diff{converting $ to incompatible type $|" + "converting type to incompatible type}0,1" + "|%diff{initializing $ with an expression of incompatible type $|" + "initializing type with an expression of incompatible type}0,1" + "|%diff{sending $ to parameter of incompatible type $|" + "sending type to parameter of incompatible type}0,1" + "|%diff{casting $ to incompatible type $|" + "casting type to incompatible type}0,1}2">; + def ext_typecheck_convert_pointer_int : ExtWarn< + "incompatible pointer to integer conversion " + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + "%select{|; dereference with *|" + "; take the address with &|" + "; remove *|" + "; remove &}3">, + InGroup; + def err_typecheck_convert_pointer_int : Error< + "incompatible pointer to integer conversion " + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + "%select{|; dereference with *|" + "; take the address with &|" + "; remove *|" + "; remove &}3">; + def ext_typecheck_convert_int_pointer : ExtWarn< + "incompatible integer to pointer conversion " + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + "%select{|; dereference with *|" + "; take the address with &|" + "; remove *|" + "; remove &}3">, + InGroup, SFINAEFailure; + def err_typecheck_convert_int_pointer : Error< + "incompatible integer to pointer conversion " + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + "%select{|; dereference with *|" + "; take the address with &|" + "; remove *|" + "; remove &}3">; + def ext_typecheck_convert_pointer_void_func : Extension< + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + " converts between void pointer and function pointer">; + def err_typecheck_convert_pointer_void_func : Error< + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + " converts between void pointer and function pointer">; + def ext_typecheck_convert_incompatible_pointer_sign : ExtWarn< + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + " converts between pointers to integer types %select{with different sign|" + "where one is of the unique plain 'char' type and the other is not}3">, + InGroup>; + def err_typecheck_convert_incompatible_pointer_sign : + Error; + def ext_typecheck_convert_incompatible_pointer : ExtWarn< + "incompatible pointer types " + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + "%select{|; dereference with *|" + "; take the address with &|" + "; remove *|" + "; remove &}3">, + InGroup; + def err_typecheck_convert_incompatible_pointer : Error< + "incompatible pointer types " + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + "%select{|; dereference with *|" + "; take the address with &|" + "; remove *|" + "; remove &}3">; + def ext_typecheck_convert_incompatible_function_pointer : ExtWarn< + "incompatible function pointer types " + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + "%select{|; dereference with *|" + "; take the address with &|" + "; remove *|" + "; remove &}3">, + InGroup; + def err_typecheck_convert_incompatible_function_pointer : Error< + "incompatible function pointer types " + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + "%select{|; dereference with *|" + "; take the address with &|" + "; remove *|" + "; remove &}3">; + def ext_typecheck_convert_discards_qualifiers : ExtWarn< + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + " discards qualifiers">, + InGroup; + def err_typecheck_convert_discards_qualifiers : Error< + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + " discards qualifiers">; + def ext_nested_pointer_qualifier_mismatch : ExtWarn< + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + " discards qualifiers in nested pointer types">, + InGroup; + def err_nested_pointer_qualifier_mismatch : Error< + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + " discards qualifiers in nested pointer types">; + def warn_incompatible_vectors : Warning< + "incompatible vector types " + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2">, + InGroup, DefaultIgnore; + def err_incompatible_vectors : Error< + "incompatible vector types " + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2">; + def err_int_to_block_pointer : Error< + "invalid block pointer conversion " + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2">; + def err_typecheck_convert_incompatible_block_pointer : Error< + "incompatible block pointer types " + "%select{%diff{assigning to $ from $|assigning to different types}0,1" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2">; + def err_typecheck_incompatible_address_space : Error< + "%select{%diff{assigning $ to $|assigning to different types}1,0" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + " changes address space of pointer">; + def err_typecheck_incompatible_nested_address_space : Error< + "%select{%diff{assigning $ to $|assigning to different types}1,0" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + " changes address space of nested pointer">; + def err_typecheck_incompatible_ownership : Error< + "%select{%diff{assigning $ to $|assigning to different types}1,0" + "|%diff{passing $ to parameter of type $|" + "passing to parameter of different type}0,1" + "|%diff{returning $ from a function with result type $|" + "returning from function with different return type}0,1" + "|%diff{converting $ to type $|converting between types}0,1" + "|%diff{initializing $ with an expression of type $|" + "initializing with expression of different type}0,1" + "|%diff{sending $ to parameter of type $|" + "sending to parameter of different type}0,1" + "|%diff{casting $ to type $|casting between types}0,1}2" + " changes retain/release properties of pointer">; + def err_typecheck_comparison_of_distinct_blocks : Error< + "comparison of distinct block types%diff{ ($ and $)|}0,1">; + + def err_typecheck_array_not_modifiable_lvalue : Error< + "array type %0 is not assignable">; + def err_typecheck_non_object_not_modifiable_lvalue : Error< + "non-object type %0 is not assignable">; + def err_typecheck_expression_not_modifiable_lvalue : Error< + "expression is not assignable">; + def err_typecheck_incomplete_type_not_modifiable_lvalue : Error< + "incomplete type %0 is not assignable">; + def err_typecheck_lvalue_casts_not_supported : Error< + "assignment to cast is illegal, lvalue casts are not supported">; + + def err_typecheck_duplicate_vector_components_not_mlvalue : Error< + "vector is not assignable (contains duplicate components)">; + def err_block_decl_ref_not_modifiable_lvalue : Error< + "variable is not assignable (missing __block type specifier)">; + def err_lambda_decl_ref_not_modifiable_lvalue : Error< + "cannot assign to a variable captured by copy in a non-mutable lambda">; + def err_typecheck_call_not_function : Error< + "called object type %0 is not a function or function pointer">; + def err_call_incomplete_return : Error< + "calling function with incomplete return type %0">; + def err_call_function_incomplete_return : Error< + "calling %0 with incomplete return type %1">; + def err_call_incomplete_argument : Error< + "argument type %0 is incomplete">; + def err_typecheck_call_too_few_args : Error< + "too few %select{|||execution configuration }0arguments to " + "%select{function|block|method|kernel function}0 call, " + "expected %1, have %2">; + def err_typecheck_call_too_few_args_one : Error< + "too few %select{|||execution configuration }0arguments to " + "%select{function|block|method|kernel function}0 call, " + "single argument %1 was not specified">; + def err_typecheck_call_too_few_args_at_least : Error< + "too few %select{|||execution configuration }0arguments to " + "%select{function|block|method|kernel function}0 call, " + "expected at least %1, have %2">; + def err_typecheck_call_too_few_args_at_least_one : Error< + "too few %select{|||execution configuration }0arguments to " + "%select{function|block|method|kernel function}0 call, " + "at least argument %1 must be specified">; + def err_typecheck_call_too_few_args_suggest : Error< + "too few %select{|||execution configuration }0arguments to " + "%select{function|block|method|kernel function}0 call, " + "expected %1, have %2; did you mean %3?">; + def err_typecheck_call_too_few_args_at_least_suggest : Error< + "too few %select{|||execution configuration }0arguments to " + "%select{function|block|method|kernel function}0 call, " + "expected at least %1, have %2; did you mean %3?">; + def err_typecheck_call_too_many_args : Error< + "too many %select{|||execution configuration }0arguments to " + "%select{function|block|method|kernel function}0 call, " + "expected %1, have %2">; + def err_typecheck_call_too_many_args_one : Error< + "too many %select{|||execution configuration }0arguments to " + "%select{function|block|method|kernel function}0 call, " + "expected single argument %1, have %2 arguments">; + def err_typecheck_call_too_many_args_at_most : Error< + "too many %select{|||execution configuration }0arguments to " + "%select{function|block|method|kernel function}0 call, " + "expected at most %1, have %2">; + def err_typecheck_call_too_many_args_at_most_one : Error< + "too many %select{|||execution configuration }0arguments to " + "%select{function|block|method|kernel function}0 call, " + "expected at most single argument %1, have %2 arguments">; + def err_typecheck_call_too_many_args_suggest : Error< + "too many %select{|||execution configuration }0arguments to " + "%select{function|block|method|kernel function}0 call, " + "expected %1, have %2; did you mean %3?">; + def err_typecheck_call_too_many_args_at_most_suggest : Error< + "too many %select{|||execution configuration }0arguments to " + "%select{function|block|method|kernel function}0 call, " + "expected at most %1, have %2; did you mean %3?">; + + def err_arc_typecheck_convert_incompatible_pointer : Error< + "incompatible pointer types passing retainable parameter of type %0" + "to a CF function expecting %1 type">; + + def err_builtin_fn_use : Error<"builtin functions must be directly called">; + + def warn_call_wrong_number_of_arguments : Warning< + "too %select{few|many}0 arguments in call to %1">; + def err_atomic_builtin_must_be_pointer : Error< + "address argument to atomic builtin must be a pointer (%0 invalid)">; + def err_atomic_builtin_must_be_pointer_intptr : Error< + "address argument to atomic builtin must be a pointer to integer or pointer" + " (%0 invalid)">; + def err_atomic_builtin_cannot_be_const : Error< + "address argument to atomic builtin cannot be const-qualified (%0 invalid)">; + def err_atomic_builtin_must_be_pointer_intfltptr : Error< + "address argument to atomic builtin must be a pointer to integer," + " floating-point or pointer (%0 invalid)">; + def err_atomic_builtin_pointer_size : Error< + "address argument to atomic builtin must be a pointer to 1,2,4,8 or 16 byte " + "type (%0 invalid)">; + def err_atomic_exclusive_builtin_pointer_size : Error< + "address argument to load or store exclusive builtin must be a pointer to" + " 1,2,4 or 8 byte type (%0 invalid)">; + def err_atomic_builtin_ext_int_size : Error< + "Atomic memory operand must have a power-of-two size">; + def err_atomic_builtin_ext_int_prohibit : Error< + "argument to atomic builtin of type '_ExtInt' is not supported">; + def err_atomic_op_needs_atomic : Error< + "address argument to atomic operation must be a pointer to _Atomic " + "type (%0 invalid)">; + def err_atomic_op_needs_non_const_atomic : Error< + "address argument to atomic operation must be a pointer to non-%select{const|constant}0 _Atomic " + "type (%1 invalid)">; + def err_atomic_op_needs_non_const_pointer : Error< + "address argument to atomic operation must be a pointer to non-const " + "type (%0 invalid)">; + def err_atomic_op_needs_trivial_copy : Error< + "address argument to atomic operation must be a pointer to a " + "trivially-copyable type (%0 invalid)">; + def err_atomic_op_needs_atomic_int_ptr_or_fp : Error< + "address argument to atomic operation must be a pointer to %select{|atomic }0" + "integer, pointer or supported floating point type (%1 invalid)">; + def err_atomic_op_needs_atomic_int_or_ptr : Error< + "address argument to atomic operation must be a pointer to %select{|atomic }0" + "integer or pointer (%1 invalid)">; + def err_atomic_op_needs_atomic_int : Error< + "address argument to atomic operation must be a pointer to " + "%select{|atomic }0integer (%1 invalid)">; + def warn_atomic_op_has_invalid_memory_order : Warning< + "memory order argument to atomic operation is invalid">, + InGroup>; + def err_atomic_op_has_invalid_synch_scope : Error< + "synchronization scope argument to atomic operation is invalid">; + def warn_atomic_implicit_seq_cst : Warning< + "implicit use of sequentially-consistent atomic may incur stronger memory barriers than necessary">, + InGroup>, DefaultIgnore; + + def err_overflow_builtin_must_be_int : Error< + "operand argument to overflow builtin must be an integer (%0 invalid)">; + def err_overflow_builtin_must_be_ptr_int : Error< + "result argument to overflow builtin must be a pointer " + "to a non-const integer (%0 invalid)">; + def err_overflow_builtin_ext_int_max_size : Error< + "__builtin_mul_overflow does not support signed _ExtInt operands of more " + "than %0 bits">; + + def err_atomic_load_store_uses_lib : Error< + "atomic %select{load|store}0 requires runtime support that is not " + "available for this target">; + + def err_nontemporal_builtin_must_be_pointer : Error< + "address argument to nontemporal builtin must be a pointer (%0 invalid)">; + def err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector : Error< + "address argument to nontemporal builtin must be a pointer to integer, float, " + "pointer, or a vector of such types (%0 invalid)">; + + def err_deleted_function_use : Error<"attempt to use a deleted function">; + def err_deleted_inherited_ctor_use : Error< + "constructor inherited by %0 from base class %1 is implicitly deleted">; + + def note_called_by : Note<"called by %0">; + def err_kern_type_not_void_return : Error< + "kernel function type %0 must have void return type">; + def err_kern_is_nonstatic_method : Error< + "kernel function %0 must be a free function or static member function">; + def err_config_scalar_return : Error< + "CUDA special function '%0' must have scalar return type">; + def err_kern_call_not_global_function : Error< + "kernel call to non-global function %0">; + def err_global_call_not_config : Error< + "call to global function %0 not configured">; + def err_ref_bad_target : Error< + "reference to %select{__device__|__global__|__host__|__host__ __device__}0 " + "%select{function|variable}1 %2 in %select{__device__|__global__|__host__|__host__ __device__}3 function">; + def note_cuda_const_var_unpromoted : Note< + "const variable cannot be emitted on device side due to dynamic initialization">; + def note_cuda_host_var : Note< + "host variable declared here">; + def err_ref_bad_target_global_initializer : Error< + "reference to %select{__device__|__global__|__host__|__host__ __device__}0 " + "function %1 in global initializer">; + def err_capture_bad_target : Error< + "capture host variable %0 by reference in device or host device lambda function">; + def warn_maybe_capture_bad_target_this_ptr : Warning< + "capture host side class data member by this pointer in device or host device lambda function " + "may result in invalid memory access if this pointer is not accessible on device side">, + InGroup>; + def warn_kern_is_method : Extension< + "kernel function %0 is a member function; this may not be accepted by nvcc">, + InGroup; + def warn_kern_is_inline : Warning< + "ignored 'inline' attribute on kernel function %0">, + InGroup; + def err_variadic_device_fn : Error< + "CUDA device code does not support variadic functions">; + def err_va_arg_in_device : Error< + "CUDA device code does not support va_arg">; + def err_alias_not_supported_on_nvptx : Error<"CUDA does not support aliases">; + def err_cuda_unattributed_constexpr_cannot_overload_device : Error< + "constexpr function %0 without __host__ or __device__ attributes cannot " + "overload __device__ function with same signature. Add a __host__ " + "attribute, or build with -fno-cuda-host-device-constexpr.">; + def note_cuda_conflicting_device_function_declared_here : Note< + "conflicting __device__ function declared here">; + def err_cuda_device_exceptions : Error< + "cannot use '%0' in " + "%select{__device__|__global__|__host__|__host__ __device__}1 function">; + def err_dynamic_var_init : Error< + "dynamic initialization is not supported for " + "__device__, __constant__, __shared__, and __managed__ variables.">; + def err_shared_var_init : Error< + "initialization is not supported for __shared__ variables.">; + def err_cuda_vla : Error< + "cannot use variable-length arrays in " + "%select{__device__|__global__|__host__|__host__ __device__}0 functions">; + def err_cuda_extern_shared : Error<"__shared__ variable %0 cannot be 'extern'">; + def err_cuda_host_shared : Error< + "__shared__ local variables not allowed in " + "%select{__device__|__global__|__host__|__host__ __device__}0 functions">; + def err_cuda_nonstatic_constdev: Error<"__constant__, __device__, and " + "__managed__ are not allowed on non-static local variables">; + def err_cuda_ovl_target : Error< + "%select{__device__|__global__|__host__|__host__ __device__}0 function %1 " + "cannot overload %select{__device__|__global__|__host__|__host__ __device__}2 function %3">; + def note_cuda_ovl_candidate_target_mismatch : Note< + "candidate template ignored: target attributes do not match">; + + def err_cuda_device_builtin_surftex_cls_template : Error< + "illegal device builtin %select{surface|texture}0 reference " + "class template %1 declared here">; + def note_cuda_device_builtin_surftex_cls_should_have_n_args : Note< + "%0 needs to have exactly %1 template parameters">; + def note_cuda_device_builtin_surftex_cls_should_have_match_arg : Note< + "the %select{1st|2nd|3rd}1 template parameter of %0 needs to be " + "%select{a type|an integer or enum value}2">; + + def err_cuda_device_builtin_surftex_ref_decl : Error< + "illegal device builtin %select{surface|texture}0 reference " + "type %1 declared here">; + def note_cuda_device_builtin_surftex_should_be_template_class : Note< + "%0 needs to be instantiated from a class template with proper " + "template arguments">; + + def err_hip_invalid_args_builtin_mangled_name : Error< + "invalid argument: symbol must be a device-side function or global variable">; + + def warn_non_pod_vararg_with_format_string : Warning< + "cannot pass %select{non-POD|non-trivial}0 object of type %1 to variadic " + "%select{function|block|method|constructor}2; expected type from format " + "string was %3">, InGroup, DefaultError; + // The arguments to this diagnostic should match the warning above. + def err_cannot_pass_objc_interface_to_vararg_format : Error< + "cannot pass object with interface type %1 by value to variadic " + "%select{function|block|method|constructor}2; expected type from format " + "string was %3">; + def err_cannot_pass_non_trivial_c_struct_to_vararg : Error< + "cannot pass non-trivial C object of type %0 by value to variadic " + "%select{function|block|method|constructor}1">; + + + def err_cannot_pass_objc_interface_to_vararg : Error< + "cannot pass object with interface type %0 by value through variadic " + "%select{function|block|method|constructor}1">; + def warn_cannot_pass_non_pod_arg_to_vararg : Warning< + "cannot pass object of %select{non-POD|non-trivial}0 type %1 through variadic" + " %select{function|block|method|constructor}2; call will abort at runtime">, + InGroup, DefaultError; + def warn_cxx98_compat_pass_non_pod_arg_to_vararg : Warning< + "passing object of trivial but non-POD type %0 through variadic" + " %select{function|block|method|constructor}1 is incompatible with C++98">, + InGroup, DefaultIgnore; + def warn_pass_class_arg_to_vararg : Warning< + "passing object of class type %0 through variadic " + "%select{function|block|method|constructor}1" + "%select{|; did you mean to call '%3'?}2">, + InGroup, DefaultIgnore; + def err_cannot_pass_to_vararg : Error< + "cannot pass %select{expression of type %1|initializer list}0 to variadic " + "%select{function|block|method|constructor}2">; + def err_cannot_pass_to_vararg_format : Error< + "cannot pass %select{expression of type %1|initializer list}0 to variadic " + "%select{function|block|method|constructor}2; expected type from format " + "string was %3">; + + def err_typecheck_call_invalid_ordered_compare : Error< + "ordered compare requires two args of floating point type" + "%diff{ ($ and $)|}0,1">; + def err_typecheck_call_invalid_unary_fp : Error< + "floating point classification requires argument of floating point type " + "(passed in %0)">; + def err_typecheck_cond_expect_int_float : Error< + "used type %0 where integer or floating point type is required">; + def err_typecheck_cond_expect_scalar : Error< + "used type %0 where arithmetic or pointer type is required">; + def err_typecheck_cond_expect_nonfloat : Error< + "used type %0 where floating point type is not allowed">; + def ext_typecheck_cond_one_void : Extension< + "C99 forbids conditional expressions with only one void side">; + def err_typecheck_cast_to_incomplete : Error< + "cast to incomplete type %0">; + def ext_typecheck_cast_nonscalar : Extension< + "C99 forbids casting nonscalar type %0 to the same type">; + def ext_typecheck_cast_to_union : Extension< + "cast to union type is a GNU extension">, + InGroup; + def err_typecheck_cast_to_union_no_type : Error< + "cast to union type from type %0 not present in union">; + def err_cast_pointer_from_non_pointer_int : Error< + "operand of type %0 cannot be cast to a pointer type">; + def warn_cast_pointer_from_sel : Warning< + "cast of type %0 to %1 is deprecated; use sel_getName instead">, + InGroup; + def warn_function_def_in_objc_container : Warning< + "function definition inside an Objective-C container is deprecated">, + InGroup; + def err_typecheck_call_requires_real_fp : Error< + "argument type %0 is not a real floating point type">; + def err_typecheck_call_different_arg_types : Error< + "arguments are of different types%diff{ ($ vs $)|}0,1">; + + def warn_cast_calling_conv : Warning< + "cast between incompatible calling conventions '%0' and '%1'; " + "calls through this pointer may abort at runtime">, + InGroup>; + def note_change_calling_conv_fixit : Note< + "consider defining %0 with the '%1' calling convention">; + def warn_bad_function_cast : Warning< + "cast from function call of type %0 to non-matching type %1">, + InGroup, DefaultIgnore; + def warn_cast_function_type : Warning< + "cast %diff{from $ to $ |}0,1converts to incompatible function type">, + InGroup, DefaultIgnore; + def err_cast_pointer_to_non_pointer_int : Error< + "pointer cannot be cast to type %0">; + def err_cast_to_bfloat16 : Error<"cannot type-cast to __bf16">; + def err_cast_from_bfloat16 : Error<"cannot type-cast from __bf16">; + def err_typecheck_expect_scalar_operand : Error< + "operand of type %0 where arithmetic or pointer type is required">; + def err_typecheck_cond_incompatible_operands : Error< + "incompatible operand types%diff{ ($ and $)|}0,1">; + def err_typecheck_expect_flt_or_vector : Error< + "invalid operand of type %0 where floating, complex or " + "a vector of such types is required">; + def err_cast_selector_expr : Error< + "cannot type cast @selector expression">; + def ext_typecheck_cond_incompatible_pointers : ExtWarn< + "pointer type mismatch%diff{ ($ and $)|}0,1">, + InGroup>; + def ext_typecheck_cond_pointer_integer_mismatch : ExtWarn< + "pointer/integer type mismatch in conditional expression" + "%diff{ ($ and $)|}0,1">, + InGroup>; + def err_typecheck_choose_expr_requires_constant : Error< + "'__builtin_choose_expr' requires a constant expression">; + def warn_unused_expr : Warning<"expression result unused">, + InGroup; + def warn_unused_voidptr : Warning< + "expression result unused; should this cast be to 'void'?">, + InGroup; + def warn_unused_property_expr : Warning< + "property access result unused - getters should not be used for side effects">, + InGroup; + def warn_unused_container_subscript_expr : Warning< + "container access result unused - container access should not be used for side effects">, + InGroup; + def warn_unused_call : Warning< + "ignoring return value of function declared with %0 attribute">, + InGroup; + def warn_unused_constructor : Warning< + "ignoring temporary created by a constructor declared with %0 attribute">, + InGroup; + def warn_unused_constructor_msg : Warning< + "ignoring temporary created by a constructor declared with %0 attribute: %1">, + InGroup; + def warn_side_effects_unevaluated_context : Warning< + "expression with side effects has no effect in an unevaluated context">, + InGroup; + def warn_side_effects_typeid : Warning< + "expression with side effects will be evaluated despite being used as an " + "operand to 'typeid'">, InGroup; + def warn_unused_result : Warning< + "ignoring return value of function declared with %0 attribute">, + InGroup; + def warn_unused_result_msg : Warning< + "ignoring return value of function declared with %0 attribute: %1">, + InGroup; + def warn_unused_volatile : Warning< + "expression result unused; assign into a variable to force a volatile load">, + InGroup>; + + def ext_cxx14_attr : Extension< + "use of the %0 attribute is a C++14 extension">, InGroup; + def ext_cxx17_attr : Extension< + "use of the %0 attribute is a C++17 extension">, InGroup; + def ext_cxx20_attr : Extension< + "use of the %0 attribute is a C++20 extension">, InGroup; + + def warn_unused_comparison : Warning< + "%select{equality|inequality|relational|three-way}0 comparison result unused">, + InGroup; + def note_inequality_comparison_to_or_assign : Note< + "use '|=' to turn this inequality comparison into an or-assignment">; + + def err_incomplete_type_used_in_type_trait_expr : Error< + "incomplete type %0 used in type trait expression">; + + // C++20 constinit and require_constant_initialization attribute + def warn_cxx20_compat_constinit : Warning< + "'constinit' specifier is incompatible with C++ standards before C++20">, + InGroup, DefaultIgnore; + def err_constinit_local_variable : Error< + "local variable cannot be declared 'constinit'">; + def err_require_constant_init_failed : Error< + "variable does not have a constant initializer">; + def note_declared_required_constant_init_here : Note< + "required by %select{'require_constant_initialization' attribute|" + "'constinit' specifier}0 here">; + def ext_constinit_missing : ExtWarn< + "'constinit' specifier missing on initializing declaration of %0">, + InGroup>; + def note_constinit_specified_here : Note<"variable declared constinit here">; + def err_constinit_added_too_late : Error< + "'constinit' specifier added after initialization of variable">; + def warn_require_const_init_added_too_late : Warning< + "'require_constant_initialization' attribute added after initialization " + "of variable">, InGroup; + def note_constinit_missing_here : Note< + "add the " + "%select{'require_constant_initialization' attribute|'constinit' specifier}0 " + "to the initializing declaration here">; + + def err_dimension_expr_not_constant_integer : Error< + "dimension expression does not evaluate to a constant unsigned int">; + + def err_typecheck_cond_incompatible_operands_null : Error< + "non-pointer operand type %0 incompatible with %select{NULL|nullptr}1">; + def ext_empty_struct_union : Extension< + "empty %select{struct|union}0 is a GNU extension">, InGroup; + def ext_no_named_members_in_struct_union : Extension< + "%select{struct|union}0 without named members is a GNU extension">, InGroup; + def warn_zero_size_struct_union_compat : Warning<"%select{|empty }0" + "%select{struct|union}1 has size 0 in C, %select{size 1|non-zero size}2 in C++">, + InGroup, DefaultIgnore; + def warn_zero_size_struct_union_in_extern_c : Warning<"%select{|empty }0" + "%select{struct|union}1 has size 0 in C, %select{size 1|non-zero size}2 in C++">, + InGroup; + def warn_cast_qual : Warning<"cast from %0 to %1 drops %select{const and " + "volatile qualifiers|const qualifier|volatile qualifier}2">, + InGroup, DefaultIgnore; + def warn_cast_qual2 : Warning<"cast from %0 to %1 must have all intermediate " + "pointers const qualified to be safe">, InGroup, DefaultIgnore; + def warn_redefine_extname_not_applied : Warning< + "#pragma redefine_extname is applicable to external C declarations only; " + "not applied to %select{function|variable}0 %1">, + InGroup; + } // End of general sema category. + + // inline asm. + let CategoryName = "Inline Assembly Issue" in { + def err_asm_invalid_lvalue_in_output : Error<"invalid lvalue in asm output">; + def err_asm_invalid_output_constraint : Error< + "invalid output constraint '%0' in asm">; + def err_asm_invalid_lvalue_in_input : Error< + "invalid lvalue in asm input for constraint '%0'">; + def err_asm_invalid_input_constraint : Error< + "invalid input constraint '%0' in asm">; + def err_asm_tying_incompatible_types : Error< + "unsupported inline asm: input with type " + "%diff{$ matching output with type $|}0,1">; + def err_asm_unexpected_constraint_alternatives : Error< + "asm constraint has an unexpected number of alternatives: %0 vs %1">; + def err_asm_incomplete_type : Error<"asm operand has incomplete type %0">; + def err_asm_unknown_register_name : Error<"unknown register name '%0' in asm">; + def err_asm_unwind_and_goto : Error<"unwind clobber can't be used with asm goto">; + def err_asm_invalid_global_var_reg : Error<"register '%0' unsuitable for " + "global register variables on this target">; + def err_asm_register_size_mismatch : Error<"size of register '%0' does not " + "match variable size">; + def err_asm_bad_register_type : Error<"bad type for named register variable">; + def err_asm_invalid_input_size : Error< + "invalid input size for constraint '%0'">; + def err_asm_invalid_output_size : Error< + "invalid output size for constraint '%0'">; + def err_invalid_asm_cast_lvalue : Error< + "invalid use of a cast in a inline asm context requiring an lvalue: " + "remove the cast or build with -fheinous-gnu-extensions">; + def err_invalid_asm_value_for_constraint + : Error <"value '%0' out of range for constraint '%1'">; + def err_asm_non_addr_value_in_memory_constraint : Error < + "reference to a %select{bit-field|vector element|global register variable}0" + " in asm %select{input|output}1 with a memory constraint '%2'">; + def err_asm_input_duplicate_match : Error< + "more than one input constraint matches the same output '%0'">; + + def warn_asm_label_on_auto_decl : Warning< + "ignored asm label '%0' on automatic variable">; + def warn_invalid_asm_cast_lvalue : Warning< + "invalid use of a cast in an inline asm context requiring an lvalue: " + "accepted due to -fheinous-gnu-extensions, but clang may remove support " + "for this in the future">; + def warn_asm_mismatched_size_modifier : Warning< + "value size does not match register size specified by the constraint " + "and modifier">, + InGroup; + + def note_asm_missing_constraint_modifier : Note< + "use constraint modifier \"%0\"">; + def note_asm_input_duplicate_first : Note< + "constraint '%0' is already present here">; + def error_duplicate_asm_operand_name : Error< + "duplicate use of asm operand name \"%0\"">; + def note_duplicate_asm_operand_name : Note< + "asm operand name \"%0\" first referenced here">; + } + + def error_inoutput_conflict_with_clobber : Error< + "asm-specifier for input or output variable conflicts with asm" + " clobber list">; + + let CategoryName = "Semantic Issue" in { + + def err_invalid_conversion_between_matrixes : Error< + "conversion between matrix types%diff{ $ and $|}0,1 of different size is not allowed">; + + def err_invalid_conversion_between_matrix_and_type : Error< + "conversion between matrix type %0 and incompatible type %1 is not allowed">; + + def err_invalid_conversion_between_vectors : Error< + "invalid conversion between vector type%diff{ $ and $|}0,1 of different " + "size">; + def err_invalid_conversion_between_vector_and_integer : Error< + "invalid conversion between vector type %0 and integer type %1 " + "of different size">; + + def err_opencl_function_pointer : Error< + "%select{pointers|references}0 to functions are not allowed">; + + def err_opencl_taking_address_capture : Error< + "taking address of a capture is not allowed">; + + def err_invalid_conversion_between_vector_and_scalar : Error< + "invalid conversion between vector type %0 and scalar type %1">; + + // C++ member initializers. + def err_only_constructors_take_base_inits : Error< + "only constructors take base initializers">; + + def err_multiple_mem_initialization : Error < + "multiple initializations given for non-static member %0">; + def err_multiple_mem_union_initialization : Error < + "initializing multiple members of union">; + def err_multiple_base_initialization : Error < + "multiple initializations given for base %0">; + + def err_mem_init_not_member_or_class : Error< + "member initializer %0 does not name a non-static data member or base " + "class">; + + def warn_initializer_out_of_order : Warning< + "%select{field|base class}0 %1 will be initialized after " + "%select{field|base}2 %3">, + InGroup, DefaultIgnore; + + def warn_some_initializers_out_of_order : Warning< + "initializer order does not match the declaration order">, + InGroup, DefaultIgnore; + + def note_initializer_out_of_order : Note< + "%select{field|base class}0 %1 will be initialized after " + "%select{field|base}2 %3">; + + def warn_abstract_vbase_init_ignored : Warning< + "initializer for virtual base class %0 of abstract class %1 " + "will never be used">, + InGroup>, DefaultIgnore; + + def err_base_init_does_not_name_class : Error< + "constructor initializer %0 does not name a class">; + def err_base_init_direct_and_virtual : Error< + "base class initializer %0 names both a direct base class and an " + "inherited virtual base class">; + def err_not_direct_base_or_virtual : Error< + "type %0 is not a direct or virtual base of %1">; + + def err_in_class_initializer_non_const : Error< + "non-const static data member must be initialized out of line">; + def err_in_class_initializer_volatile : Error< + "static const volatile data member must be initialized out of line">; + def err_in_class_initializer_bad_type : Error< + "static data member of type %0 must be initialized out of line">; + def ext_in_class_initializer_float_type : ExtWarn< + "in-class initializer for static data member of type %0 is a GNU extension">, + InGroup; + def ext_in_class_initializer_float_type_cxx11 : ExtWarn< + "in-class initializer for static data member of type %0 requires " + "'constexpr' specifier">, InGroup, DefaultError; + def note_in_class_initializer_float_type_cxx11 : Note<"add 'constexpr'">; + def err_in_class_initializer_literal_type : Error< + "in-class initializer for static data member of type %0 requires " + "'constexpr' specifier">; + def err_in_class_initializer_non_constant : Error< + "in-class initializer for static data member is not a constant expression">; + def err_default_member_initializer_not_yet_parsed : Error< + "default member initializer for %1 needed within definition of enclosing " + "class %0 outside of member functions">; + def note_default_member_initializer_not_yet_parsed : Note< + "default member initializer declared here">; + def err_default_member_initializer_cycle + : Error<"default member initializer for %0 uses itself">; + + def ext_in_class_initializer_non_constant : Extension< + "in-class initializer for static data member is not a constant expression; " + "folding it to a constant is a GNU extension">, InGroup; + + def err_thread_dynamic_init : Error< + "initializer for thread-local variable must be a constant expression">; + def err_thread_nontrivial_dtor : Error< + "type of thread-local variable has non-trivial destruction">; + def note_use_thread_local : Note< + "use 'thread_local' to allow this">; + + // C++ anonymous unions and GNU anonymous structs/unions + def ext_anonymous_union : Extension< + "anonymous unions are a C11 extension">, InGroup; + def ext_gnu_anonymous_struct : Extension< + "anonymous structs are a GNU extension">, InGroup; + def ext_c11_anonymous_struct : Extension< + "anonymous structs are a C11 extension">, InGroup; + def err_anonymous_union_not_static : Error< + "anonymous unions at namespace or global scope must be declared 'static'">; + def err_anonymous_union_with_storage_spec : Error< + "anonymous union at class scope must not have a storage specifier">; + def err_anonymous_struct_not_member : Error< + "anonymous %select{structs|structs and classes}0 must be " + "%select{struct or union|class}0 members">; + def err_anonymous_record_member_redecl : Error< + "member of anonymous %select{struct|union}0 redeclares %1">; + def err_anonymous_record_with_type : Error< + "types cannot be declared in an anonymous %select{struct|union}0">; + def ext_anonymous_record_with_type : Extension< + "types declared in an anonymous %select{struct|union}0 are a Microsoft " + "extension">, InGroup; + def ext_anonymous_record_with_anonymous_type : Extension< + "anonymous types declared in an anonymous %select{struct|union}0 " + "are an extension">, InGroup>; + def err_anonymous_record_with_function : Error< + "functions cannot be declared in an anonymous %select{struct|union}0">; + def err_anonymous_record_with_static : Error< + "static members cannot be declared in an anonymous %select{struct|union}0">; + def err_anonymous_record_bad_member : Error< + "anonymous %select{struct|union}0 can only contain non-static data members">; + def err_anonymous_record_nonpublic_member : Error< + "anonymous %select{struct|union}0 cannot contain a " + "%select{private|protected}1 data member">; + def ext_ms_anonymous_record : ExtWarn< + "anonymous %select{structs|unions}0 are a Microsoft extension">, + InGroup; + + // C++ local classes + def err_reference_to_local_in_enclosing_context : Error< + "reference to local %select{variable|binding}1 %0 declared in enclosing " + "%select{%3|block literal|lambda expression|context}2">; + + def err_static_data_member_not_allowed_in_local_class : Error< + "static data member %0 not allowed in local %sub{select_tag_type_kind}2 %1">; + + // C++ derived classes + def err_base_clause_on_union : Error<"unions cannot have base classes">; + def err_base_must_be_class : Error<"base specifier must name a class">; + def err_union_as_base_class : Error<"unions cannot be base classes">; + def err_circular_inheritance : Error< + "circular inheritance between %0 and %1">; + def err_base_class_has_flexible_array_member : Error< + "base class %0 has a flexible array member">; + def err_incomplete_base_class : Error<"base class has incomplete type">; + def err_duplicate_base_class : Error< + "base class %0 specified more than once as a direct base class">; + def warn_inaccessible_base_class : Warning< + "direct base %0 is inaccessible due to ambiguity:%1">, + InGroup>; + // FIXME: better way to display derivation? Pass entire thing into diagclient? + def err_ambiguous_derived_to_base_conv : Error< + "ambiguous conversion from derived class %0 to base class %1:%2">; + def err_ambiguous_memptr_conv : Error< + "ambiguous conversion from pointer to member of %select{base|derived}0 " + "class %1 to pointer to member of %select{derived|base}0 class %2:%3">; + def ext_ms_ambiguous_direct_base : ExtWarn< + "accessing inaccessible direct base %0 of %1 is a Microsoft extension">, + InGroup; + + def err_memptr_conv_via_virtual : Error< + "conversion from pointer to member of class %0 to pointer to member " + "of class %1 via virtual base %2 is not allowed">; + + // C++ member name lookup + def err_ambiguous_member_multiple_subobjects : Error< + "non-static member %0 found in multiple base-class subobjects of type %1:%2">; + def err_ambiguous_member_multiple_subobject_types : Error< + "member %0 found in multiple base classes of different types">; + def note_ambiguous_member_found : Note<"member found by ambiguous name lookup">; + def note_ambiguous_member_type_found : Note< + "member type %0 found by ambiguous name lookup">; + def err_ambiguous_reference : Error<"reference to %0 is ambiguous">; + def note_ambiguous_candidate : Note<"candidate found by name lookup is %q0">; + def err_ambiguous_tag_hiding : Error<"a type named %0 is hidden by a " + "declaration in a different namespace">; + def note_hidden_tag : Note<"type declaration hidden">; + def note_hiding_object : Note<"declaration hides type">; + + // C++ operator overloading + def err_operator_overload_needs_class_or_enum : Error< + "overloaded %0 must have at least one parameter of class " + "or enumeration type">; + + def err_operator_overload_variadic : Error<"overloaded %0 cannot be variadic">; + def err_operator_overload_static : Error< + "overloaded %0 cannot be a static member function">; + def err_operator_overload_default_arg : Error< + "parameter of overloaded %0 cannot have a default argument">; + def err_operator_overload_must_be : Error< + "overloaded %0 must be a %select{unary|binary|unary or binary}2 operator " + "(has %1 parameter%s1)">; + + def err_operator_overload_must_be_member : Error< + "overloaded %0 must be a non-static member function">; + def err_operator_overload_post_incdec_must_be_int : Error< + "parameter of overloaded post-%select{increment|decrement}1 operator must " + "have type 'int' (not %0)">; + + // C++ allocation and deallocation functions. + def err_operator_new_delete_declared_in_namespace : Error< + "%0 cannot be declared inside a namespace">; + def err_operator_new_delete_declared_static : Error< + "%0 cannot be declared static in global scope">; + def ext_operator_new_delete_declared_inline : ExtWarn< + "replacement function %0 cannot be declared 'inline'">, + InGroup>; + def err_operator_new_delete_invalid_result_type : Error< + "%0 must return type %1">; + def err_operator_new_delete_dependent_result_type : Error< + "%0 cannot have a dependent return type; use %1 instead">; + def err_operator_new_delete_too_few_parameters : Error< + "%0 must have at least one parameter">; + def err_operator_new_delete_template_too_few_parameters : Error< + "%0 template must have at least two parameters">; + def warn_operator_new_returns_null : Warning< + "%0 should not return a null pointer unless it is declared 'throw()'" + "%select{| or 'noexcept'}1">, InGroup; + + def err_operator_new_dependent_param_type : Error< + "%0 cannot take a dependent type as first parameter; " + "use size_t (%1) instead">; + def err_operator_new_param_type : Error< + "%0 takes type size_t (%1) as first parameter">; + def err_operator_new_default_arg: Error< + "parameter of %0 cannot have a default argument">; + def err_operator_delete_dependent_param_type : Error< + "%0 cannot take a dependent type as first parameter; use %1 instead">; + def err_operator_delete_param_type : Error< + "first parameter of %0 must have type %1">; + def err_destroying_operator_delete_not_usual : Error< + "destroying operator delete can have only an optional size and optional " + "alignment parameter">; + def note_implicit_delete_this_in_destructor_here : Note< + "while checking implicit 'delete this' for virtual destructor">; + def err_builtin_operator_new_delete_not_usual : Error< + "call to '%select{__builtin_operator_new|__builtin_operator_delete}0' " + "selects non-usual %select{allocation|deallocation}0 function">; + def note_non_usual_function_declared_here : Note< + "non-usual %0 declared here">; + + // C++ literal operators + def err_literal_operator_outside_namespace : Error< + "literal operator %0 must be in a namespace or global scope">; + def err_literal_operator_id_outside_namespace : Error< + "non-namespace scope '%0' cannot have a literal operator member">; + def err_literal_operator_default_argument : Error< + "literal operator cannot have a default argument">; + def err_literal_operator_bad_param_count : Error< + "non-template literal operator must have one or two parameters">; + def err_literal_operator_invalid_param : Error< + "parameter of literal operator must have type 'unsigned long long', 'long double', 'char', 'wchar_t', 'char16_t', 'char32_t', or 'const char *'">; + def err_literal_operator_param : Error< + "invalid literal operator parameter type %0, did you mean %1?">; + def err_literal_operator_template_with_params : Error< + "literal operator template cannot have any parameters">; + def err_literal_operator_template : Error< + "template parameter list for literal operator must be either 'char...' or 'typename T, T...'">; + def err_literal_operator_extern_c : Error< + "literal operator must have C++ linkage">; + def ext_string_literal_operator_template : ExtWarn< + "string literal operator templates are a GNU extension">, + InGroup; + def warn_user_literal_reserved : Warning< + "user-defined literal suffixes not starting with '_' are reserved" + "%select{; no literal will invoke this operator|}0">, + InGroup; + + // C++ conversion functions + def err_conv_function_not_member : Error< + "conversion function must be a non-static member function">; + def err_conv_function_return_type : Error< + "conversion function cannot have a return type">; + def err_conv_function_with_params : Error< + "conversion function cannot have any parameters">; + def err_conv_function_variadic : Error< + "conversion function cannot be variadic">; + def err_conv_function_to_array : Error< + "conversion function cannot convert to an array type">; + def err_conv_function_to_function : Error< + "conversion function cannot convert to a function type">; + def err_conv_function_with_complex_decl : Error< + "cannot specify any part of a return type in the " + "declaration of a conversion function" + "%select{" + "; put the complete type after 'operator'|" + "; use a typedef to declare a conversion to %1|" + "; use an alias template to declare a conversion to %1|" + "}0">; + def err_conv_function_redeclared : Error< + "conversion function cannot be redeclared">; + def warn_conv_to_self_not_used : Warning< + "conversion function converting %0 to itself will never be used">, + InGroup; + def warn_conv_to_base_not_used : Warning< + "conversion function converting %0 to its base class %1 will never be used">, + InGroup; + def warn_conv_to_void_not_used : Warning< + "conversion function converting %0 to %1 will never be used">, + InGroup; + + def warn_not_compound_assign : Warning< + "use of unary operator that may be intended as compound assignment (%0=)">; + + // C++11 explicit conversion operators + def ext_explicit_conversion_functions : ExtWarn< + "explicit conversion functions are a C++11 extension">, InGroup; + def warn_cxx98_compat_explicit_conversion_functions : Warning< + "explicit conversion functions are incompatible with C++98">, + InGroup, DefaultIgnore; + + // C++11 defaulted functions + def err_defaulted_special_member_params : Error< + "an explicitly-defaulted %select{|copy |move }0constructor cannot " + "have default arguments">; + def err_defaulted_special_member_variadic : Error< + "an explicitly-defaulted %select{|copy |move }0constructor cannot " + "be variadic">; + def err_defaulted_special_member_return_type : Error< + "explicitly-defaulted %select{copy|move}0 assignment operator must " + "return %1">; + def err_defaulted_special_member_quals : Error< + "an explicitly-defaulted %select{copy|move}0 assignment operator may not " + "have 'const'%select{, 'constexpr'|}1 or 'volatile' qualifiers">; + def err_defaulted_special_member_volatile_param : Error< + "the parameter for an explicitly-defaulted %sub{select_special_member_kind}0 " + "may not be volatile">; + def err_defaulted_special_member_move_const_param : Error< + "the parameter for an explicitly-defaulted move " + "%select{constructor|assignment operator}0 may not be const">; + def err_defaulted_special_member_copy_const_param : Error< + "the parameter for this explicitly-defaulted copy " + "%select{constructor|assignment operator}0 is const, but a member or base " + "requires it to be non-const">; + def err_defaulted_copy_assign_not_ref : Error< + "the parameter for an explicitly-defaulted copy assignment operator must be an " + "lvalue reference type">; + def err_incorrect_defaulted_constexpr : Error< + "defaulted definition of %sub{select_special_member_kind}0 " + "is not constexpr">; + def err_incorrect_defaulted_consteval : Error< + "defaulted declaration of %sub{select_special_member_kind}0 " + "cannot be consteval because implicit definition is not constexpr">; + def warn_defaulted_method_deleted : Warning< + "explicitly defaulted %sub{select_special_member_kind}0 is implicitly " + "deleted">, InGroup; + def err_out_of_line_default_deletes : Error< + "defaulting this %sub{select_special_member_kind}0 " + "would delete it after its first declaration">; + def note_deleted_type_mismatch : Note< + "function is implicitly deleted because its declared type does not match " + "the type of an implicit %sub{select_special_member_kind}0">; + def warn_cxx17_compat_defaulted_method_type_mismatch : Warning< + "explicitly defaulting this %sub{select_special_member_kind}0 with a type " + "different from the implicit type is incompatible with C++ standards before " + "C++20">, InGroup, DefaultIgnore; + def warn_vbase_moved_multiple_times : Warning< + "defaulted move assignment operator of %0 will move assign virtual base " + "class %1 multiple times">, InGroup>; + def note_vbase_moved_here : Note< + "%select{%1 is a virtual base class of base class %2 declared here|" + "virtual base class %1 declared here}0">; + + // C++20 defaulted comparisons + // This corresponds to values of Sema::DefaultedComparisonKind. + def select_defaulted_comparison_kind : TextSubstitution< + "%select{|equality|three-way|equality|relational}0 comparison " + "operator">; + def ext_defaulted_comparison : ExtWarn< + "defaulted comparison operators are a C++20 extension">, InGroup; + def warn_cxx17_compat_defaulted_comparison : Warning< + "defaulted comparison operators are incompatible with C++ standards " + "before C++20">, InGroup, DefaultIgnore; + def err_defaulted_comparison_template : Error< + "comparison operator template cannot be defaulted">; + def err_defaulted_comparison_out_of_class : Error< + "%sub{select_defaulted_comparison_kind}0 can only be defaulted in a class " + "definition">; + def err_defaulted_comparison_param : Error< + "invalid parameter type for defaulted %sub{select_defaulted_comparison_kind}0" + "; found %1, expected %2%select{| or %4}3">; + def err_defaulted_comparison_param_mismatch : Error< + "parameters for defaulted %sub{select_defaulted_comparison_kind}0 " + "must have the same type%diff{ (found $ vs $)|}1,2">; + def err_defaulted_comparison_non_const : Error< + "defaulted member %sub{select_defaulted_comparison_kind}0 must be " + "const-qualified">; + def err_defaulted_comparison_return_type_not_bool : Error< + "return type for defaulted %sub{select_defaulted_comparison_kind}0 " + "must be 'bool', not %1">; + def err_defaulted_comparison_deduced_return_type_not_auto : Error< + "deduced return type for defaulted %sub{select_defaulted_comparison_kind}0 " + "must be 'auto', not %1">; + def warn_defaulted_comparison_deleted : Warning< + "explicitly defaulted %sub{select_defaulted_comparison_kind}0 is implicitly " + "deleted">, InGroup; + def err_non_first_default_compare_deletes : Error< + "defaulting %select{this %sub{select_defaulted_comparison_kind}1|" + "the corresponding implicit 'operator==' for this defaulted 'operator<=>'}0 " + "would delete it after its first declaration">; + def note_defaulted_comparison_union : Note< + "defaulted %0 is implicitly deleted because " + "%2 is a %select{union-like class|union}1 with variant members">; + def note_defaulted_comparison_reference_member : Note< + "defaulted %0 is implicitly deleted because " + "class %1 has a reference member">; + def note_defaulted_comparison_ambiguous : Note< + "defaulted %0 is implicitly deleted because implied %select{|'==' |'<' }1" + "comparison %select{|for member %3 |for base class %3 }2is ambiguous">; + def note_defaulted_comparison_inaccessible : Note< + "defaulted %0 is implicitly deleted because it would invoke a " + "%select{private|protected}3 %4%select{ member of %6|" + " member of %6 to compare member %2| to compare base class %2}1">; + def note_defaulted_comparison_calls_deleted : Note< + "defaulted %0 is implicitly deleted because it would invoke a deleted " + "comparison function%select{| for member %2| for base class %2}1">; + def note_defaulted_comparison_no_viable_function : Note< + "defaulted %0 is implicitly deleted because there is no viable " + "%select{three-way comparison function|'operator=='}1 for " + "%select{|member |base class }2%3">; + def note_defaulted_comparison_no_viable_function_synthesized : Note< + "three-way comparison cannot be synthesized because there is no viable " + "function for %select{'=='|'<'}0 comparison">; + def note_defaulted_comparison_not_rewritten_callee : Note< + "defaulted %0 is implicitly deleted because this non-rewritten comparison " + "function would be the best match for the comparison">; + def note_defaulted_comparison_not_rewritten_conversion : Note< + "defaulted %0 is implicitly deleted because a builtin comparison function " + "using this conversion would be the best match for the comparison">; + def note_defaulted_comparison_cannot_deduce : Note< + "return type of defaulted 'operator<=>' cannot be deduced because " + "return type %2 of three-way comparison for %select{|member|base class}0 %1 " + "is not a standard comparison category type">; + def err_defaulted_comparison_cannot_deduce_undeduced_auto : Error< + "return type of defaulted 'operator<=>' cannot be deduced because " + "three-way comparison for %select{|member|base class}0 %1 " + "has a deduced return type and is not yet defined">; + def note_defaulted_comparison_cannot_deduce_undeduced_auto : Note< + "%select{|member|base class}0 %1 declared here">; + def note_defaulted_comparison_cannot_deduce_callee : Note< + "selected 'operator<=>' for %select{|member|base class}0 %1 declared here">; + def err_incorrect_defaulted_comparison_constexpr : Error< + "defaulted definition of %select{%sub{select_defaulted_comparison_kind}1|" + "three-way comparison operator}0 " + "cannot be declared %select{constexpr|consteval}2 because " + "%select{it|the corresponding implicit 'operator=='}0 " + "invokes a non-constexpr comparison function">; + def note_defaulted_comparison_not_constexpr : Note< + "non-constexpr comparison function would be used to compare " + "%select{|member %1|base class %1}0">; + def note_defaulted_comparison_not_constexpr_here : Note< + "non-constexpr comparison function declared here">; + def note_in_declaration_of_implicit_equality_comparison : Note< + "while declaring the corresponding implicit 'operator==' " + "for this defaulted 'operator<=>'">; + + def ext_implicit_exception_spec_mismatch : ExtWarn< + "function previously declared with an %select{explicit|implicit}0 exception " + "specification redeclared with an %select{implicit|explicit}0 exception " + "specification">, InGroup>; + + def warn_ptr_arith_precedes_bounds : Warning< + "the pointer decremented by %0 refers before the beginning of the array">, + InGroup, DefaultIgnore; + def warn_ptr_arith_exceeds_bounds : Warning< + "the pointer incremented by %0 refers past the end of the array (that " + "contains %1 element%s2)">, + InGroup, DefaultIgnore; + def warn_array_index_precedes_bounds : Warning< + "array index %0 is before the beginning of the array">, + InGroup; + def warn_array_index_exceeds_bounds : Warning< + "array index %0 is past the end of the array (which contains %1 " + "element%s2)">, InGroup; + def warn_ptr_arith_exceeds_max_addressable_bounds : Warning< + "the pointer incremented by %0 refers past the last possible element for an array in %1-bit " + "address space containing %2-bit (%3-byte) elements (max possible %4 element%s5)">, + InGroup; + def warn_array_index_exceeds_max_addressable_bounds : Warning< + "array index %0 refers past the last possible element for an array in %1-bit " + "address space containing %2-bit (%3-byte) elements (max possible %4 element%s5)">, + InGroup; + def note_array_declared_here : Note< + "array %0 declared here">; + + def warn_printf_insufficient_data_args : Warning< + "more '%%' conversions than data arguments">, InGroup; + def warn_printf_data_arg_not_used : Warning< + "data argument not used by format string">, InGroup; + def warn_format_invalid_conversion : Warning< + "invalid conversion specifier '%0'">, InGroup; + def warn_printf_incomplete_specifier : Warning< + "incomplete format specifier">, InGroup; + def warn_missing_format_string : Warning< + "format string missing">, InGroup; + def warn_scanf_nonzero_width : Warning< + "zero field width in scanf format string is unused">, + InGroup; + def warn_format_conversion_argument_type_mismatch : Warning< + "format specifies type %0 but the argument has " + "%select{type|underlying type}2 %1">, + InGroup; + def warn_format_conversion_argument_type_mismatch_pedantic : Extension< + warn_format_conversion_argument_type_mismatch.Text>, + InGroup; + def warn_format_conversion_argument_type_mismatch_confusion : Warning< + warn_format_conversion_argument_type_mismatch.Text>, + InGroup, DefaultIgnore; + def warn_format_argument_needs_cast : Warning< + "%select{values of type|enum values with underlying type}2 '%0' should not " + "be used as format arguments; add an explicit cast to %1 instead">, + InGroup; + def warn_format_argument_needs_cast_pedantic : Warning< + warn_format_argument_needs_cast.Text>, + InGroup, DefaultIgnore; + def warn_printf_positional_arg_exceeds_data_args : Warning < + "data argument position '%0' exceeds the number of data arguments (%1)">, + InGroup; + def warn_format_zero_positional_specifier : Warning< + "position arguments in format strings start counting at 1 (not 0)">, + InGroup; + def warn_format_invalid_positional_specifier : Warning< + "invalid position specified for %select{field width|field precision}0">, + InGroup; + def warn_format_mix_positional_nonpositional_args : Warning< + "cannot mix positional and non-positional arguments in format string">, + InGroup; + def warn_static_array_too_small : Warning< + "array argument is too small; %select{contains %0 elements|is of size %0}2," + " callee requires at least %1">, + InGroup; + def note_callee_static_array : Note< + "callee declares array parameter as static here">; + def warn_empty_format_string : Warning< + "format string is empty">, InGroup; + def warn_format_string_is_wide_literal : Warning< + "format string should not be a wide string">, InGroup; + def warn_printf_format_string_contains_null_char : Warning< + "format string contains '\\0' within the string body">, InGroup; + def warn_printf_format_string_not_null_terminated : Warning< + "format string is not null-terminated">, InGroup; + def warn_printf_asterisk_missing_arg : Warning< + "'%select{*|.*}0' specified field %select{width|precision}0 is missing a matching 'int' argument">, + InGroup; + def warn_printf_asterisk_wrong_type : Warning< + "field %select{width|precision}0 should have type %1, but argument has type %2">, + InGroup; + def warn_printf_nonsensical_optional_amount: Warning< + "%select{field width|precision}0 used with '%1' conversion specifier, resulting in undefined behavior">, + InGroup; + def warn_printf_nonsensical_flag: Warning< + "flag '%0' results in undefined behavior with '%1' conversion specifier">, + InGroup; + def warn_format_nonsensical_length: Warning< + "length modifier '%0' results in undefined behavior or no effect with '%1' conversion specifier">, + InGroup; + def warn_format_non_standard_positional_arg: Warning< + "positional arguments are not supported by ISO C">, InGroup, DefaultIgnore; + def warn_format_non_standard: Warning< + "'%0' %select{length modifier|conversion specifier}1 is not supported by ISO C">, + InGroup, DefaultIgnore; + def warn_format_non_standard_conversion_spec: Warning< + "using length modifier '%0' with conversion specifier '%1' is not supported by ISO C">, + InGroup, DefaultIgnore; + def err_invalid_mask_type_size : Error< + "mask type size must be between 1-byte and 8-bytes">; + def warn_format_invalid_annotation : Warning< + "using '%0' format specifier annotation outside of os_log()/os_trace()">, + InGroup; + def warn_format_P_no_precision : Warning< + "using '%%P' format specifier without precision">, + InGroup; + def warn_printf_ignored_flag: Warning< + "flag '%0' is ignored when flag '%1' is present">, + InGroup; + def warn_printf_empty_objc_flag: Warning< + "missing object format flag">, + InGroup; + def warn_printf_ObjCflags_without_ObjCConversion: Warning< + "object format flags cannot be used with '%0' conversion specifier">, + InGroup; + def warn_printf_invalid_objc_flag: Warning< + "'%0' is not a valid object format flag">, + InGroup; + def warn_scanf_scanlist_incomplete : Warning< + "no closing ']' for '%%[' in scanf format string">, + InGroup; + def warn_format_bool_as_character : Warning< + "using '%0' format specifier, but argument has boolean value">, + InGroup; + def note_format_string_defined : Note<"format string is defined here">; + def note_format_fix_specifier : Note<"did you mean to use '%0'?">; + def note_printf_c_str: Note<"did you mean to call the %0 method?">; + def note_format_security_fixit: Note< + "treat the string as an argument to avoid this">; + + def warn_null_arg : Warning< + "null passed to a callee that requires a non-null argument">, + InGroup; + def warn_null_ret : Warning< + "null returned from %select{function|method}0 that requires a non-null return value">, + InGroup; + + def err_lifetimebound_no_object_param : Error< + "'lifetimebound' attribute cannot be applied; %select{static |non-}0member " + "function has no implicit object parameter">; + def err_lifetimebound_ctor_dtor : Error< + "'lifetimebound' attribute cannot be applied to a " + "%select{constructor|destructor}0">; + + // CHECK: returning address/reference of stack memory + def warn_ret_stack_addr_ref : Warning< + "%select{address of|reference to}0 stack memory associated with " + "%select{local variable|parameter}2 %1 returned">, + InGroup; + def warn_ret_local_temp_addr_ref : Warning< + "returning %select{address of|reference to}0 local temporary object">, + InGroup; + def warn_ret_addr_label : Warning< + "returning address of label, which is local">, + InGroup; + def err_ret_local_block : Error< + "returning block that lives on the local stack">; + def note_local_var_initializer : Note< + "%select{via initialization of|binding reference}0 variable " + "%select{%2 |}1here">; + def note_lambda_capture_initializer : Note< + "%select{implicitly |}2captured%select{| by reference}3" + "%select{%select{ due to use|}2 here|" + " via initialization of lambda capture %0}1">; + def note_init_with_default_member_initalizer : Note< + "initializing field %0 with default member initializer">; + + // Check for initializing a member variable with the address or a reference to + // a constructor parameter. + def warn_bind_ref_member_to_parameter : Warning< + "binding reference member %0 to stack allocated " + "%select{variable|parameter}2 %1">, InGroup; + def warn_init_ptr_member_to_parameter_addr : Warning< + "initializing pointer member %0 with the stack address of " + "%select{variable|parameter}2 %1">, InGroup; + def note_ref_or_ptr_member_declared_here : Note< + "%select{reference|pointer}0 member declared here">; + + def err_dangling_member : Error< + "%select{reference|backing array for 'std::initializer_list'}2 " + "%select{|subobject of }1member %0 " + "%select{binds to|is}2 a temporary object " + "whose lifetime would be shorter than the lifetime of " + "the constructed object">; + def warn_dangling_member : Warning< + "%select{reference|backing array for 'std::initializer_list'}2 " + "%select{|subobject of }1member %0 " + "%select{binds to|is}2 a temporary object " + "whose lifetime is shorter than the lifetime of the constructed object">, + InGroup; + def warn_dangling_lifetime_pointer_member : Warning< + "initializing pointer member %0 to point to a temporary object " + "whose lifetime is shorter than the lifetime of the constructed object">, + InGroup; + def note_lifetime_extending_member_declared_here : Note< + "%select{%select{reference|'std::initializer_list'}0 member|" + "member with %select{reference|'std::initializer_list'}0 subobject}1 " + "declared here">; + def warn_dangling_variable : Warning< + "%select{temporary %select{whose address is used as value of|" + "%select{|implicitly }2bound to}4 " + "%select{%select{|reference }4member of local variable|" + "local %select{variable|reference}4}1|" + "array backing " + "%select{initializer list subobject of local variable|" + "local initializer list}1}0 " + "%select{%3 |}2will be destroyed at the end of the full-expression">, + InGroup; + def warn_new_dangling_reference : Warning< + "temporary bound to reference member of allocated object " + "will be destroyed at the end of the full-expression">, + InGroup; + def warn_dangling_lifetime_pointer : Warning< + "object backing the pointer " + "will be destroyed at the end of the full-expression">, + InGroup; + def warn_new_dangling_initializer_list : Warning< + "array backing " + "%select{initializer list subobject of the allocated object|" + "the allocated initializer list}0 " + "will be destroyed at the end of the full-expression">, + InGroup; + def warn_unsupported_lifetime_extension : Warning< + "sorry, lifetime extension of " + "%select{temporary|backing array of initializer list}0 created " + "by aggregate initialization using default member initializer " + "is not supported; lifetime of %select{temporary|backing array}0 " + "will end at the end of the full-expression">, InGroup; + + // For non-floating point, expressions of the form x == x or x != x + // should result in a warning, since these always evaluate to a constant. + // Array comparisons have similar warnings + def warn_comparison_always : Warning< + "%select{self-|array }0comparison always evaluates to " + "%select{a constant|true|false|'std::strong_ordering::equal'}1">, + InGroup; + def warn_comparison_bitwise_always : Warning< + "bitwise comparison always evaluates to %select{false|true}0">, + InGroup, DefaultIgnore; + def warn_comparison_bitwise_or : Warning< + "bitwise or with non-zero value always evaluates to true">, + InGroup, DefaultIgnore; + def warn_tautological_overlap_comparison : Warning< + "overlapping comparisons always evaluate to %select{false|true}0">, + InGroup, DefaultIgnore; + def warn_depr_array_comparison : Warning< + "comparison between two arrays is deprecated; " + "to compare array addresses, use unary '+' to decay operands to pointers">, + InGroup; + + def warn_stringcompare : Warning< + "result of comparison against %select{a string literal|@encode}0 is " + "unspecified (use an explicit string comparison function instead)">, + InGroup; + + def warn_identity_field_assign : Warning< + "assigning %select{field|instance variable}0 to itself">, + InGroup; + + // Type safety attributes + def err_type_tag_for_datatype_not_ice : Error< + "'type_tag_for_datatype' attribute requires the initializer to be " + "an %select{integer|integral}0 constant expression">; + def err_type_tag_for_datatype_too_large : Error< + "'type_tag_for_datatype' attribute requires the initializer to be " + "an %select{integer|integral}0 constant expression " + "that can be represented by a 64 bit integer">; + def err_tag_index_out_of_range : Error< + "%select{type tag|argument}0 index %1 is greater than the number of arguments specified">; + def warn_type_tag_for_datatype_wrong_kind : Warning< + "this type tag was not designed to be used with this function">, + InGroup; + def warn_type_safety_type_mismatch : Warning< + "argument type %0 doesn't match specified %1 type tag " + "%select{that requires %3|}2">, InGroup; + def warn_type_safety_null_pointer_required : Warning< + "specified %0 type tag requires a null pointer">, InGroup; + + // Generic selections. + def err_assoc_type_incomplete : Error< + "type %0 in generic association incomplete">; + def err_assoc_type_nonobject : Error< + "type %0 in generic association not an object type">; + def err_assoc_type_variably_modified : Error< + "type %0 in generic association is a variably modified type">; + def err_assoc_compatible_types : Error< + "type %0 in generic association compatible with previously specified type %1">; + def note_compat_assoc : Note< + "compatible type %0 specified here">; + def err_generic_sel_no_match : Error< + "controlling expression type %0 not compatible with any generic association type">; + def err_generic_sel_multi_match : Error< + "controlling expression type %0 compatible with %1 generic association types">; + + + // Blocks + def err_blocks_disable : Error<"blocks support disabled - compile with -fblocks" + " or %select{pick a deployment target that supports them|for OpenCL 2.0}0">; + def err_block_returning_array_function : Error< + "block cannot return %select{array|function}0 type %1">; + + // Builtin annotation + def err_builtin_annotation_first_arg : Error< + "first argument to __builtin_annotation must be an integer">; + def err_builtin_annotation_second_arg : Error< + "second argument to __builtin_annotation must be a non-wide string constant">; + def err_msvc_annotation_wide_str : Error< + "arguments to __annotation must be wide string constants">; + + // CFString checking + def err_cfstring_literal_not_string_constant : Error< + "CFString literal is not a string constant">; + def warn_cfstring_truncated : Warning< + "input conversion stopped due to an input byte that does not " + "belong to the input codeset UTF-8">, + InGroup>; + + // os_log checking + // TODO: separate diagnostic for os_trace() + def err_os_log_format_not_string_constant : Error< + "os_log() format argument is not a string constant">; + def err_os_log_argument_too_big : Error< + "os_log() argument %0 is too big (%1 bytes, max %2)">; + def warn_os_log_format_narg : Error< + "os_log() '%%n' format specifier is not allowed">, DefaultError; + + // Statements. + def err_continue_not_in_loop : Error< + "'continue' statement not in loop statement">; + def err_break_not_in_loop_or_switch : Error< + "'break' statement not in loop or switch statement">; + def warn_loop_ctrl_binds_to_inner : Warning< + "'%0' is bound to current loop, GCC binds it to the enclosing loop">, + InGroup; + def warn_break_binds_to_switch : Warning< + "'break' is bound to loop, GCC binds it to switch">, + InGroup; + def err_default_not_in_switch : Error< + "'default' statement not in switch statement">; + def err_case_not_in_switch : Error<"'case' statement not in switch statement">; + def warn_bool_switch_condition : Warning< + "switch condition has boolean value">, InGroup; + def warn_case_value_overflow : Warning< + "overflow converting case value to switch condition type (%0 to %1)">, + InGroup; + def err_duplicate_case : Error<"duplicate case value '%0'">; + def err_duplicate_case_differing_expr : Error< + "duplicate case value: '%0' and '%1' both equal '%2'">; + def warn_case_empty_range : Warning<"empty case range specified">; + def warn_missing_case_for_condition : + Warning<"no case matching constant switch condition '%0'">; + + def warn_def_missing_case : Warning<"%plural{" + "1:enumeration value %1 not explicitly handled in switch|" + "2:enumeration values %1 and %2 not explicitly handled in switch|" + "3:enumeration values %1, %2, and %3 not explicitly handled in switch|" + ":%0 enumeration values not explicitly handled in switch: %1, %2, %3...}0">, + InGroup, DefaultIgnore; + + def warn_missing_case : Warning<"%plural{" + "1:enumeration value %1 not handled in switch|" + "2:enumeration values %1 and %2 not handled in switch|" + "3:enumeration values %1, %2, and %3 not handled in switch|" + ":%0 enumeration values not handled in switch: %1, %2, %3...}0">, + InGroup; + + def warn_unannotated_fallthrough : Warning< + "unannotated fall-through between switch labels">, + InGroup, DefaultIgnore; + def warn_unannotated_fallthrough_per_function : Warning< + "unannotated fall-through between switch labels in partly-annotated " + "function">, InGroup, DefaultIgnore; + def note_insert_fallthrough_fixit : Note< + "insert '%0;' to silence this warning">; + def note_insert_break_fixit : Note< + "insert 'break;' to avoid fall-through">; + def err_fallthrough_attr_wrong_target : Error< + "%0 attribute is only allowed on empty statements">; + def note_fallthrough_insert_semi_fixit : Note<"did you forget ';'?">; + def err_fallthrough_attr_outside_switch : Error< + "fallthrough annotation is outside switch statement">; + def err_fallthrough_attr_invalid_placement : Error< + "fallthrough annotation does not directly precede switch label">; + + def warn_unreachable_default : Warning< + "default label in switch which covers all enumeration values">, + InGroup, DefaultIgnore; + def warn_not_in_enum : Warning<"case value not in enumerated type %0">, + InGroup; + def warn_not_in_enum_assignment : Warning<"integer constant not in range " + "of enumerated type %0">, InGroup>, DefaultIgnore; + def err_typecheck_statement_requires_scalar : Error< + "statement requires expression of scalar type (%0 invalid)">; + def err_typecheck_statement_requires_integer : Error< + "statement requires expression of integer type (%0 invalid)">; + def err_multiple_default_labels_defined : Error< + "multiple default labels in one switch">; + def err_switch_multiple_conversions : Error< + "multiple conversions from switch condition type %0 to an integral or " + "enumeration type">; + def note_switch_conversion : Note< + "conversion to %select{integral|enumeration}0 type %1">; + def err_switch_explicit_conversion : Error< + "switch condition type %0 requires explicit conversion to %1">; + def err_switch_incomplete_class_type : Error< + "switch condition has incomplete class type %0">; + + def warn_empty_if_body : Warning< + "if statement has empty body">, InGroup; + def warn_empty_for_body : Warning< + "for loop has empty body">, InGroup; + def warn_empty_range_based_for_body : Warning< + "range-based for loop has empty body">, InGroup; + def warn_empty_while_body : Warning< + "while loop has empty body">, InGroup; + def warn_empty_switch_body : Warning< + "switch statement has empty body">, InGroup; + def note_empty_body_on_separate_line : Note< + "put the semicolon on a separate line to silence this warning">; + + def err_va_start_captured_stmt : Error< + "'va_start' cannot be used in a captured statement">; + def err_va_start_outside_function : Error< + "'va_start' cannot be used outside a function">; + def err_va_start_fixed_function : Error< + "'va_start' used in function with fixed args">; + def err_va_start_used_in_wrong_abi_function : Error< + "'va_start' used in %select{System V|Win64}0 ABI function">; + def err_ms_va_start_used_in_sysv_function : Error< + "'__builtin_ms_va_start' used in System V ABI function">; + def warn_second_arg_of_va_start_not_last_named_param : Warning< + "second argument to 'va_start' is not the last named parameter">, + InGroup; + def warn_va_start_type_is_undefined : Warning< + "passing %select{an object that undergoes default argument promotion|" + "an object of reference type|a parameter declared with the 'register' " + "keyword}0 to 'va_start' has undefined behavior">, InGroup; + def err_first_argument_to_va_arg_not_of_type_va_list : Error< + "first argument to 'va_arg' is of type %0 and not 'va_list'">; + def err_second_parameter_to_va_arg_incomplete: Error< + "second argument to 'va_arg' is of incomplete type %0">; + def err_second_parameter_to_va_arg_abstract: Error< + "second argument to 'va_arg' is of abstract type %0">; + def warn_second_parameter_to_va_arg_not_pod : Warning< + "second argument to 'va_arg' is of non-POD type %0">, + InGroup, DefaultError; + def warn_second_parameter_to_va_arg_ownership_qualified : Warning< + "second argument to 'va_arg' is of ARC ownership-qualified type %0">, + InGroup, DefaultError; + def warn_second_parameter_to_va_arg_never_compatible : Warning< + "second argument to 'va_arg' is of promotable type %0; this va_arg has " + "undefined behavior because arguments will be promoted to %1">, InGroup; + + def warn_return_missing_expr : Warning< + "non-void %select{function|method}1 %0 should return a value">, DefaultError, + InGroup; + def ext_return_missing_expr : ExtWarn< + "non-void %select{function|method}1 %0 should return a value">, DefaultError, + InGroup; + def ext_return_has_expr : ExtWarn< + "%select{void function|void method|constructor|destructor}1 %0 " + "should not return a value">, + DefaultError, InGroup; + def ext_return_has_void_expr : Extension< + "void %select{function|method|block}1 %0 should not return void expression">; + def err_return_init_list : Error< + "%select{void function|void method|constructor|destructor}1 %0 " + "must not return a value">; + def err_ctor_dtor_returns_void : Error< + "%select{constructor|destructor}1 %0 must not return void expression">; + def warn_noreturn_function_has_return_expr : Warning< + "function %0 declared 'noreturn' should not return">, + InGroup; + def warn_falloff_noreturn_function : Warning< + "function declared 'noreturn' should not return">, + InGroup; + def err_noreturn_block_has_return_expr : Error< + "block declared 'noreturn' should not return">; + def err_carries_dependency_missing_on_first_decl : Error< + "%select{function|parameter}0 declared '[[carries_dependency]]' " + "after its first declaration">; + def note_carries_dependency_missing_first_decl : Note< + "declaration missing '[[carries_dependency]]' attribute is here">; + def err_carries_dependency_param_not_function_decl : Error< + "'[[carries_dependency]]' attribute only allowed on parameter in a function " + "declaration or lambda">; + def err_block_on_nonlocal : Error< + "__block attribute not allowed, only allowed on local variables">; + def err_block_on_vm : Error< + "__block attribute not allowed on declaration with a variably modified type">; + def err_sizeless_nonlocal : Error< + "non-local variable with sizeless type %0">; + + def err_vec_builtin_non_vector : Error< + "first two arguments to %0 must be vectors">; + def err_vec_builtin_incompatible_vector : Error< + "first two arguments to %0 must have the same type">; + def err_vsx_builtin_nonconstant_argument : Error< + "argument %0 to %1 must be a 2-bit unsigned literal (i.e. 0, 1, 2 or 3)">; + + def err_shufflevector_nonconstant_argument : Error< + "index for __builtin_shufflevector must be a constant integer">; + def err_shufflevector_argument_too_large : Error< + "index for __builtin_shufflevector must be less than the total number " + "of vector elements">; + + def err_convertvector_non_vector : Error< + "first argument to __builtin_convertvector must be a vector">; + def err_convertvector_non_vector_type : Error< + "second argument to __builtin_convertvector must be a vector type">; + def err_convertvector_incompatible_vector : Error< + "first two arguments to __builtin_convertvector must have the same number of elements">; + + def err_first_argument_to_cwsc_not_call : Error< + "first argument to __builtin_call_with_static_chain must be a non-member call expression">; + def err_first_argument_to_cwsc_block_call : Error< + "first argument to __builtin_call_with_static_chain must not be a block call">; + def err_first_argument_to_cwsc_builtin_call : Error< + "first argument to __builtin_call_with_static_chain must not be a builtin call">; + def err_first_argument_to_cwsc_pdtor_call : Error< + "first argument to __builtin_call_with_static_chain must not be a pseudo-destructor call">; + def err_second_argument_to_cwsc_not_pointer : Error< + "second argument to __builtin_call_with_static_chain must be of pointer type">; + + def err_vector_incorrect_num_initializers : Error< + "%select{too many|too few}0 elements in vector initialization (expected %1 elements, have %2)">; + def err_altivec_empty_initializer : Error<"expected initializer">; + + def err_invalid_neon_type_code : Error< + "incompatible constant for this __builtin_neon function">; + def err_argument_invalid_range : Error< + "argument value %0 is outside the valid range [%1, %2]">; + def warn_argument_invalid_range : Warning< + "argument value %0 is outside the valid range [%1, %2]">, DefaultError, + InGroup>; + def warn_argument_undefined_behaviour : Warning< + "argument value %0 will result in undefined behaviour">, + InGroup>; + def err_argument_not_multiple : Error< + "argument should be a multiple of %0">; + def err_argument_not_power_of_2 : Error< + "argument should be a power of 2">; + def err_argument_not_shifted_byte : Error< + "argument should be an 8-bit value shifted by a multiple of 8 bits">; + def err_argument_not_shifted_byte_or_xxff : Error< + "argument should be an 8-bit value shifted by a multiple of 8 bits, or in the form 0x??FF">; + def err_argument_not_contiguous_bit_field : Error< + "argument %0 value should represent a contiguous bit field">; + def err_rotation_argument_to_cadd + : Error<"argument should be the value 90 or 270">; + def err_rotation_argument_to_cmla + : Error<"argument should be the value 0, 90, 180 or 270">; + def warn_neon_vector_initializer_non_portable : Warning< + "vector initializers are not compatible with NEON intrinsics in big endian " + "mode">, InGroup>; + def note_neon_vector_initializer_non_portable : Note< + "consider using vld1_%0%1() to initialize a vector from memory, or " + "vcreate_%0%1() to initialize from an integer constant">; + def note_neon_vector_initializer_non_portable_q : Note< + "consider using vld1q_%0%1() to initialize a vector from memory, or " + "vcombine_%0%1(vcreate_%0%1(), vcreate_%0%1()) to initialize from integer " + "constants">; + def err_systemz_invalid_tabort_code : Error< + "invalid transaction abort code">; + def err_64_bit_builtin_32_bit_tgt : Error< + "this builtin is only available on 64-bit targets">; + def err_32_bit_builtin_64_bit_tgt : Error< + "this builtin is only available on 32-bit targets">; + def err_builtin_x64_aarch64_only : Error< + "this builtin is only available on x86-64 and aarch64 targets">; + def err_mips_builtin_requires_dsp : Error< + "this builtin requires 'dsp' ASE, please use -mdsp">; + def err_mips_builtin_requires_dspr2 : Error< + "this builtin requires 'dsp r2' ASE, please use -mdspr2">; + def err_mips_builtin_requires_msa : Error< + "this builtin requires 'msa' ASE, please use -mmsa">; + def err_ppc_builtin_only_on_arch : Error< + "this builtin is only valid on POWER%0 or later CPUs">; + def err_ppc_invalid_use_mma_type : Error< + "invalid use of PPC MMA type">; + def err_x86_builtin_invalid_rounding : Error< + "invalid rounding argument">; + def err_x86_builtin_invalid_scale : Error< + "scale argument must be 1, 2, 4, or 8">; + def err_x86_builtin_tile_arg_duplicate : Error< + "tile arguments must refer to different tiles">; + + def err_builtin_target_unsupported : Error< + "builtin is not supported on this target">; + def err_builtin_longjmp_unsupported : Error< + "__builtin_longjmp is not supported for the current target">; + def err_builtin_setjmp_unsupported : Error< + "__builtin_setjmp is not supported for the current target">; + + def err_builtin_longjmp_invalid_val : Error< + "argument to __builtin_longjmp must be a constant 1">; + def err_builtin_requires_language : Error<"'%0' is only available in %1">; + + def err_constant_integer_arg_type : Error< + "argument to %0 must be a constant integer">; + + def ext_mixed_decls_code : Extension< + "ISO C90 forbids mixing declarations and code">, + InGroup>; + + def err_non_local_variable_decl_in_for : Error< + "declaration of non-local variable in 'for' loop">; + def err_non_variable_decl_in_for : Error< + "non-variable declaration in 'for' loop">; + def err_toomany_element_decls : Error< + "only one element declaration is allowed">; + def err_selector_element_not_lvalue : Error< + "selector element is not a valid lvalue">; + def err_selector_element_type : Error< + "selector element type %0 is not a valid object">; + def err_selector_element_const_type : Error< + "selector element of type %0 cannot be a constant lvalue expression">; + def err_collection_expr_type : Error< + "the type %0 is not a pointer to a fast-enumerable object">; + def warn_collection_expr_type : Warning< + "collection expression type %0 may not respond to %1">; + + def err_invalid_conversion_between_ext_vectors : Error< + "invalid conversion between ext-vector type %0 and %1">; + + def warn_duplicate_attribute_exact : Warning< + "attribute %0 is already applied">, InGroup; + + def warn_duplicate_attribute : Warning< + "attribute %0 is already applied with different arguments">, + InGroup; + + def warn_sync_fetch_and_nand_semantics_change : Warning< + "the semantics of this intrinsic changed with GCC " + "version 4.4 - the newer semantics are provided here">, + InGroup>; + + // Type + def ext_wchar_t_sign_spec : ExtWarn<"'%0' cannot be signed or unsigned">, + InGroup>, DefaultError; + def warn_receiver_forward_class : Warning< + "receiver %0 is a forward class and corresponding @interface may not exist">, + InGroup; + def note_method_sent_forward_class : Note<"method %0 is used for the forward class">; + def ext_missing_declspec : ExtWarn< + "declaration specifier missing, defaulting to 'int'">; + def ext_missing_type_specifier : ExtWarn< + "type specifier missing, defaults to 'int'">, + InGroup; + def err_decimal_unsupported : Error< + "GNU decimal type extension not supported">; + def err_missing_type_specifier : Error< + "C++ requires a type specifier for all declarations">; + def err_objc_array_of_interfaces : Error< + "array of interface %0 is invalid (probably should be an array of pointers)">; + def ext_c99_array_usage : Extension< + "%select{qualifier in |static |}0array size %select{||'[*] '}0is a C99 " + "feature">, InGroup; + def err_c99_array_usage_cxx : Error< + "%select{qualifier in |static |}0array size %select{||'[*] '}0is a C99 " + "feature, not permitted in C++">; + def err_type_unsupported : Error< + "%0 is not supported on this target">; + def err_nsconsumed_attribute_mismatch : Error< + "overriding method has mismatched ns_consumed attribute on its" + " parameter">; + def err_nsreturns_retained_attribute_mismatch : Error< + "overriding method has mismatched ns_returns_%select{not_retained|retained}0" + " attributes">; + def err_nserrordomain_invalid_decl : Error< + "domain argument %select{|%1 }0does not refer to global constant">; + def err_nserrordomain_wrong_type : Error< + "domain argument %0 does not point to an NSString or CFString constant">; + + def warn_nsconsumed_attribute_mismatch : Warning< + err_nsconsumed_attribute_mismatch.Text>, InGroup; + def warn_nsreturns_retained_attribute_mismatch : Warning< + err_nsreturns_retained_attribute_mismatch.Text>, InGroup; + + def note_getter_unavailable : Note< + "or because setter is declared here, but no getter method %0 is found">; + def err_invalid_protocol_qualifiers : Error< + "invalid protocol qualifiers on non-ObjC type">; + def warn_ivar_use_hidden : Warning< + "local declaration of %0 hides instance variable">, + InGroup; + def warn_direct_initialize_call : Warning< + "explicit call to +initialize results in duplicate call to +initialize">, + InGroup; + def warn_direct_super_initialize_call : Warning< + "explicit call to [super initialize] should only be in implementation " + "of +initialize">, + InGroup; + def err_ivar_use_in_class_method : Error< + "instance variable %0 accessed in class method">; + def err_private_ivar_access : Error<"instance variable %0 is private">, + AccessControl; + def err_protected_ivar_access : Error<"instance variable %0 is protected">, + AccessControl; + def warn_maynot_respond : Warning<"%0 may not respond to %1">; + def ext_typecheck_base_super : Warning< + "method parameter type " + "%diff{$ does not match super class method parameter type $|" + "does not match super class method parameter type}0,1">, + InGroup, DefaultIgnore; + def warn_missing_method_return_type : Warning< + "method has no return type specified; defaults to 'id'">, + InGroup, DefaultIgnore; + def warn_direct_ivar_access : Warning<"instance variable %0 is being " + "directly accessed">, InGroup>, DefaultIgnore; + + // Spell-checking diagnostics + def err_unknown_typename : Error< + "unknown type name %0">; + def err_unknown_type_or_class_name_suggest : Error< + "unknown %select{type|class}1 name %0; did you mean %2?">; + def err_unknown_typename_suggest : Error< + "unknown type name %0; did you mean %1?">; + def err_unknown_nested_typename_suggest : Error< + "no type named %0 in %1; did you mean %select{|simply }2%3?">; + def err_no_member_suggest : Error<"no member named %0 in %1; did you mean %select{|simply }2%3?">; + def err_undeclared_use_suggest : Error< + "use of undeclared %0; did you mean %1?">; + def err_undeclared_var_use_suggest : Error< + "use of undeclared identifier %0; did you mean %1?">; + def err_no_template : Error<"no template named %0">; + def err_no_template_suggest : Error<"no template named %0; did you mean %1?">; + def err_no_member_template : Error<"no template named %0 in %1">; + def err_no_member_template_suggest : Error< + "no template named %0 in %1; did you mean %select{|simply }2%3?">; + def err_non_template_in_template_id : Error< + "%0 does not name a template but is followed by template arguments">; + def err_non_template_in_template_id_suggest : Error< + "%0 does not name a template but is followed by template arguments; " + "did you mean %1?">; + def err_non_template_in_member_template_id_suggest : Error< + "member %0 of %1 is not a template; did you mean %select{|simply }2%3?">; + def note_non_template_in_template_id_found : Note< + "non-template declaration found by name lookup">; + def err_mem_init_not_member_or_class_suggest : Error< + "initializer %0 does not name a non-static data member or base " + "class; did you mean the %select{base class|member}1 %2?">; + def err_field_designator_unknown_suggest : Error< + "field designator %0 does not refer to any field in type %1; did you mean " + "%2?">; + def err_typecheck_member_reference_ivar_suggest : Error< + "%0 does not have a member named %1; did you mean %2?">; + def err_property_not_found_suggest : Error< + "property %0 not found on object of type %1; did you mean %2?">; + def err_class_property_found : Error< + "property %0 is a class property; did you mean to access it with class '%1'?">; + def err_ivar_access_using_property_syntax_suggest : Error< + "property %0 not found on object of type %1; did you mean to access instance variable %2?">; + def warn_property_access_suggest : Warning< + "property %0 not found on object of type %1; did you mean to access property %2?">, + InGroup; + def err_property_found_suggest : Error< + "property %0 found on object of type %1; did you mean to access " + "it with the \".\" operator?">; + def err_undef_interface_suggest : Error< + "cannot find interface declaration for %0; did you mean %1?">; + def warn_undef_interface_suggest : Warning< + "cannot find interface declaration for %0; did you mean %1?">; + def err_undef_superclass_suggest : Error< + "cannot find interface declaration for %0, superclass of %1; did you mean " + "%2?">; + def err_undeclared_protocol_suggest : Error< + "cannot find protocol declaration for %0; did you mean %1?">; + def note_base_class_specified_here : Note< + "base class %0 specified here">; + def err_using_directive_suggest : Error< + "no namespace named %0; did you mean %1?">; + def err_using_directive_member_suggest : Error< + "no namespace named %0 in %1; did you mean %select{|simply }2%3?">; + def note_namespace_defined_here : Note<"namespace %0 defined here">; + def err_sizeof_pack_no_pack_name_suggest : Error< + "%0 does not refer to the name of a parameter pack; did you mean %1?">; + def note_parameter_pack_here : Note<"parameter pack %0 declared here">; + + def err_uncasted_use_of_unknown_any : Error< + "%0 has unknown type; cast it to its declared type to use it">; + def err_uncasted_call_of_unknown_any : Error< + "%0 has unknown return type; cast the call to its declared return type">; + def err_uncasted_send_to_unknown_any_method : Error< + "no known method %select{%objcinstance1|%objcclass1}0; cast the " + "message send to the method's return type">; + def err_unsupported_unknown_any_decl : Error< + "%0 has unknown type, which is not supported for this kind of declaration">; + def err_unsupported_unknown_any_expr : Error< + "unsupported expression with unknown type">; + def err_unsupported_unknown_any_call : Error< + "call to unsupported expression with unknown type">; + def err_unknown_any_addrof : Error< + "the address of a declaration with unknown type " + "can only be cast to a pointer type">; + def err_unknown_any_addrof_call : Error< + "address-of operator cannot be applied to a call to a function with " + "unknown return type">; + def err_unknown_any_var_function_type : Error< + "variable %0 with unknown type cannot be given a function type">; + def err_unknown_any_function : Error< + "function %0 with unknown type must be given a function type">; + + def err_filter_expression_integral : Error< + "filter expression has non-integral type %0">; + + def err_non_asm_stmt_in_naked_function : Error< + "non-ASM statement in naked function is not supported">; + def err_asm_naked_this_ref : Error< + "'this' pointer references not allowed in naked functions">; + def err_asm_naked_parm_ref : Error< + "parameter references not allowed in naked functions">; + + // OpenCL warnings and errors. + def err_invalid_astype_of_different_size : Error< + "invalid reinterpretation: sizes of %0 and %1 must match">; + def err_static_kernel : Error< + "kernel functions cannot be declared static">; + def err_method_kernel : Error< + "kernel functions cannot be class members">; + def err_template_kernel : Error< + "kernel functions cannot be used in a template declaration, instantiation or specialization">; + def err_opencl_ptrptr_kernel_param : Error< + "kernel parameter cannot be declared as a pointer to a pointer">; + def err_kernel_arg_address_space : Error< + "pointer arguments to kernel functions must reside in '__global', " + "'__constant' or '__local' address space">; + def err_opencl_ext_vector_component_invalid_length : Error< + "vector component access has invalid length %0. Supported: 1,2,3,4,8,16.">; + def err_opencl_function_variable : Error< + "%select{non-kernel function|function scope}0 variable cannot be declared in %1 address space">; + def err_opencl_addrspace_scope : Error< + "variables in the %0 address space can only be declared in the outermost " + "scope of a kernel function">; + def err_static_function_scope : Error< + "variables in function scope cannot be declared static">; + def err_opencl_bitfields : Error< + "bit-fields are not supported in OpenCL">; + def err_opencl_vla : Error< + "variable length arrays are not supported in OpenCL">; + def err_opencl_scalar_type_rank_greater_than_vector_type : Error< + "scalar operand type has greater rank than the type of the vector " + "element. (%0 and %1)">; + def err_bad_kernel_param_type : Error< + "%0 cannot be used as the type of a kernel parameter">; + def err_opencl_implicit_function_decl : Error< + "implicit declaration of function %0 is invalid in OpenCL">; + def err_record_with_pointers_kernel_param : Error< + "%select{struct|union}0 kernel parameters may not contain pointers">; + def note_within_field_of_type : Note< + "within field of type %0 declared here">; + def note_illegal_field_declared_here : Note< + "field of illegal %select{type|pointer type}0 %1 declared here">; + def err_opencl_type_struct_or_union_field : Error< + "the %0 type cannot be used to declare a structure or union field">; + def err_event_t_addr_space_qual : Error< + "the event_t type can only be used with __private address space qualifier">; + def err_expected_kernel_void_return_type : Error< + "kernel must have void return type">; + def err_sampler_initializer_not_integer : Error< + "sampler_t initialization requires 32-bit integer, not %0">; + def warn_sampler_initializer_invalid_bits : Warning< + "sampler initializer has invalid %0 bits">, InGroup, DefaultIgnore; + def err_sampler_argument_required : Error< + "sampler_t variable required - got %0">; + def err_wrong_sampler_addressspace: Error< + "sampler type cannot be used with the __local and __global address space qualifiers">; + def err_opencl_nonconst_global_sampler : Error< + "global sampler requires a const or constant address space qualifier">; + def err_opencl_cast_non_zero_to_event_t : Error< + "cannot cast non-zero value '%0' to 'event_t'">; + def err_opencl_global_invalid_addr_space : Error< + "%select{program scope|static local|extern}0 variable must reside in %1 address space">; + def err_missing_actual_pipe_type : Error< + "missing actual type specifier for pipe">; + def err_reference_pipe_type : Error < + "pipes packet types cannot be of reference type">; + def err_opencl_no_main : Error<"%select{function|kernel}0 cannot be called 'main'">; + def err_opencl_kernel_attr : + Error<"attribute %0 can only be applied to an OpenCL kernel function">; + def err_opencl_return_value_with_address_space : Error< + "return value cannot be qualified with address space">; + def err_opencl_constant_no_init : Error< + "variable in constant address space must be initialized">; + def err_opencl_atomic_init: Error< + "atomic variable can be %select{assigned|initialized}0 to a variable only " + "in global address space">; + def err_opencl_implicit_vector_conversion : Error< + "implicit conversions between vector types (%0 and %1) are not permitted">; + def err_opencl_invalid_type_array : Error< + "array of %0 type is invalid in OpenCL">; + def err_opencl_ternary_with_block : Error< + "block type cannot be used as expression in ternary expression in OpenCL">; + def err_opencl_pointer_to_type : Error< + "pointer to type %0 is invalid in OpenCL">; + def err_opencl_type_can_only_be_used_as_function_parameter : Error < + "type %0 can only be used as a function parameter in OpenCL">; + def err_opencl_type_not_found : Error< + "%0 type %1 not found; include the base header with -finclude-default-header">; + def warn_opencl_attr_deprecated_ignored : Warning < + "%0 attribute is deprecated and ignored in %1">, InGroup; + def err_opencl_variadic_function : Error< + "invalid prototype, variadic arguments are not allowed in OpenCL">; + def err_opencl_requires_extension : Error< + "use of %select{type|declaration}0 %1 requires %2 support">; + def ext_opencl_double_without_pragma : Extension< + "Clang permits use of type 'double' regardless pragma if 'cl_khr_fp64' is" + " supported">; + def warn_opencl_generic_address_space_arg : Warning< + "passing non-generic address space pointer to %0" + " may cause dynamic conversion affecting performance">, + InGroup, DefaultIgnore; + + // OpenCL v2.0 s6.13.6 -- Builtin Pipe Functions + def err_opencl_builtin_pipe_first_arg : Error< + "first argument to %0 must be a pipe type">; + def err_opencl_builtin_pipe_arg_num : Error< + "invalid number of arguments to function: %0">; + def err_opencl_builtin_pipe_invalid_arg : Error< + "invalid argument type to function %0 (expecting %1 having %2)">; + def err_opencl_builtin_pipe_invalid_access_modifier : Error< + "invalid pipe access modifier (expecting %0)">; + + // OpenCL access qualifier + def err_opencl_invalid_access_qualifier : Error< + "access qualifier can only be used for pipe and image type">; + def err_opencl_invalid_read_write : Error< + "access qualifier %0 can not be used for %1 %select{|prior to OpenCL C version 2.0 or in version 3.0 " + "and without __opencl_c_read_write_images feature}2">; + def err_opencl_multiple_access_qualifiers : Error< + "multiple access qualifiers">; + def note_opencl_typedef_access_qualifier : Note< + "previously declared '%0' here">; + + // OpenCL v2.0 s6.12.5 Blocks restrictions + def err_opencl_block_storage_type : Error< + "the __block storage type is not permitted">; + def err_opencl_invalid_block_declaration : Error< + "invalid block variable declaration - must be %select{const qualified|initialized}0">; + def err_opencl_extern_block_declaration : Error< + "invalid block variable declaration - using 'extern' storage class is disallowed">; + def err_opencl_block_ref_block : Error< + "cannot refer to a block inside block">; + + // OpenCL v2.0 s6.13.9 - Address space qualifier functions. + def err_opencl_builtin_to_addr_invalid_arg : Error< + "invalid argument %0 to function: %1, expecting a generic pointer argument">; + + // OpenCL v2.0 s6.13.17 Enqueue kernel restrictions. + def err_opencl_enqueue_kernel_incorrect_args : Error< + "illegal call to enqueue_kernel, incorrect argument types">; + def err_opencl_enqueue_kernel_local_size_args : Error< + "mismatch in number of block parameters and local size arguments passed">; + def err_opencl_enqueue_kernel_invalid_local_size_type : Error< + "illegal call to enqueue_kernel, parameter needs to be specified as integer type">; + def err_opencl_enqueue_kernel_blocks_non_local_void_args : Error< + "blocks used in enqueue_kernel call are expected to have parameters of type 'local void*'">; + def err_opencl_enqueue_kernel_blocks_no_args : Error< + "blocks with parameters are not accepted in this prototype of enqueue_kernel call">; + + def err_opencl_builtin_expected_type : Error< + "illegal call to %0, expected %1 argument type">; + + // OpenCL v3.0 s6.3.7 - Vector Components + def ext_opencl_ext_vector_type_rgba_selector: ExtWarn< + "vector component name '%0' is a feature from OpenCL version 3.0 onwards">, + InGroup; + + def err_openclcxx_placement_new : Error< + "use of placement new requires explicit declaration">; + + // MIG routine annotations. + def warn_mig_server_routine_does_not_return_kern_return_t : Warning< + "'mig_server_routine' attribute only applies to routines that return a kern_return_t">, + InGroup; + } // end of sema category + + let CategoryName = "OpenMP Issue" in { + // OpenMP support. + def err_omp_expected_var_arg : Error< + "%0 is not a global variable, static local variable or static data member">; + def err_omp_expected_var_arg_suggest : Error< + "%0 is not a global variable, static local variable or static data member; " + "did you mean %1">; + def err_omp_global_var_arg : Error< + "arguments of '#pragma omp %0' must have %select{global storage|static storage duration}1">; + def err_omp_ref_type_arg : Error< + "arguments of '#pragma omp %0' cannot be of reference type %1">; + def err_omp_region_not_file_context : Error< + "directive must be at file or namespace scope">; + def err_omp_var_scope : Error< + "'#pragma omp %0' must appear in the scope of the %q1 variable declaration">; + def err_omp_var_used : Error< + "'#pragma omp %0' must precede all references to variable %q1">; + def err_omp_var_thread_local : Error< + "variable %0 cannot be threadprivate because it is %select{thread-local|a global named register variable}1">; + def err_omp_private_incomplete_type : Error< + "a private variable with incomplete type %0">; + def err_omp_firstprivate_incomplete_type : Error< + "a firstprivate variable with incomplete type %0">; + def err_omp_lastprivate_incomplete_type : Error< + "a lastprivate variable with incomplete type %0">; + def err_omp_reduction_incomplete_type : Error< + "a reduction list item with incomplete type %0">; + def err_omp_unexpected_clause_value : Error< + "expected %0 in OpenMP clause '%1'">; + def err_omp_expected_var_name_member_expr : Error< + "expected variable name%select{| or data member of current class}0">; + def err_omp_expected_var_name_member_expr_or_array_item : Error< + "expected variable name%select{|, data member of current class}0, array element or array section">; + def err_omp_expected_addressable_lvalue_or_array_item : Error< + "expected addressable lvalue expression, array element%select{ or array section|, array section or array shaping expression}0%select{| of non 'omp_depend_t' type}1">; + def err_omp_expected_named_var_member_or_array_expression: Error< + "expected expression containing only member accesses and/or array sections based on named variables">; + def err_omp_bit_fields_forbidden_in_clause : Error< + "bit fields cannot be used to specify storage in a '%0' clause">; + def err_array_section_does_not_specify_contiguous_storage : Error< + "array section does not specify contiguous storage">; + def err_array_section_does_not_specify_length : Error< + "array section does not specify length for outermost dimension">; + def err_omp_union_type_not_allowed : Error< + "mapping of union members is not allowed">; + def err_omp_expected_access_to_data_field : Error< + "expected access to data field">; + def err_omp_multiple_array_items_in_map_clause : Error< + "multiple array elements associated with the same variable are not allowed in map clauses of the same construct">; + def err_omp_duplicate_map_type_modifier : Error< + "same map type modifier has been specified more than once">; + def err_omp_duplicate_motion_modifier : Error< + "same motion modifier has been specified more than once">; + def err_omp_pointer_mapped_along_with_derived_section : Error< + "pointer cannot be mapped along with a section derived from itself">; + def err_omp_original_storage_is_shared_and_does_not_contain : Error< + "original storage of expression in data environment is shared but data environment do not fully contain mapped expression storage">; + def err_omp_same_pointer_dereferenced : Error< + "same pointer dereferenced in multiple different ways in map clause expressions">; + def note_omp_task_predetermined_firstprivate_here : Note< + "predetermined as a firstprivate in a task construct here">; + def err_omp_threadprivate_incomplete_type : Error< + "threadprivate variable with incomplete type %0">; + def err_omp_no_dsa_for_variable : Error< + "variable %0 must have explicitly specified data sharing attributes">; + def err_omp_defaultmap_no_attr_for_variable : Error< + "variable %0 must have explicitly specified data sharing attributes, data mapping attributes, or in an is_device_ptr clause">; + def note_omp_default_dsa_none : Note< + "explicit data sharing attribute requested here">; + def note_omp_defaultmap_attr_none : Note< + "explicit data sharing attribute, data mapping attribute, or is_device_ptr clause requested here">; + def err_omp_wrong_dsa : Error< + "%0 variable cannot be %1">; + def err_omp_variably_modified_type_not_supported : Error< + "arguments of OpenMP clause '%0' in '#pragma omp %2' directive cannot be of variably-modified type %1">; + def note_omp_explicit_dsa : Note< + "defined as %0">; + def note_omp_predetermined_dsa : Note< + "%select{static data member is predetermined as shared|" + "variable with static storage duration is predetermined as shared|" + "loop iteration variable is predetermined as private|" + "loop iteration variable is predetermined as linear|" + "loop iteration variable is predetermined as lastprivate|" + "constant variable is predetermined as shared|" + "global variable is predetermined as shared|" + "non-shared variable in a task construct is predetermined as firstprivate|" + "variable with automatic storage duration is predetermined as private}0" + "%select{|; perhaps you forget to enclose 'omp %2' directive into a parallel or another task region?}1">; + def note_omp_implicit_dsa : Note< + "implicitly determined as %0">; + def err_omp_loop_var_dsa : Error< + "loop iteration variable in the associated loop of 'omp %1' directive may not be %0, predetermined as %2">; + def err_omp_not_for : Error< + "%select{statement after '#pragma omp %1' must be a for loop|" + "expected %2 for loops after '#pragma omp %1'%select{|, but found only %4}3}0">; + def note_omp_collapse_ordered_expr : Note< + "as specified in %select{'collapse'|'ordered'|'collapse' and 'ordered'}0 clause%select{||s}0">; + def err_omp_negative_expression_in_clause : Error< + "argument to '%0' clause must be a %select{non-negative|strictly positive}1 integer value">; + def err_omp_not_integral : Error< + "expression must have integral or unscoped enumeration " + "type, not %0">; + def err_omp_threadprivate_in_target : Error< + "threadprivate variables cannot be used in target constructs">; + def err_omp_incomplete_type : Error< + "expression has incomplete class type %0">; + def err_omp_explicit_conversion : Error< + "expression requires explicit conversion from %0 to %1">; + def note_omp_conversion_here : Note< + "conversion to %select{integral|enumeration}0 type %1 declared here">; + def err_omp_ambiguous_conversion : Error< + "ambiguous conversion from type %0 to an integral or unscoped " + "enumeration type">; + def err_omp_iterator_not_integral_or_pointer : Error< + "expected integral or pointer type as the iterator-type, not %0">; + def err_omp_iterator_step_not_integral : Error< + "iterator step expression %0 is not the integral expression">; + def err_omp_iterator_step_constant_zero : Error< + "iterator step expression %0 evaluates to 0">; + def err_omp_required_access : Error< + "%0 variable must be %1">; + def err_omp_const_variable : Error< + "const-qualified variable cannot be %0">; + def err_omp_const_not_mutable_variable : Error< + "const-qualified variable without mutable fields cannot be %0">; + def err_omp_const_list_item : Error< + "const-qualified list item cannot be %0">; + def err_omp_linear_incomplete_type : Error< + "a linear variable with incomplete type %0">; + def err_omp_linear_expected_int_or_ptr : Error< + "argument of a linear clause should be of integral or pointer " + "type, not %0">; + def warn_omp_linear_step_zero : Warning< + "zero linear step (%0 %select{|and other variables in clause }1should probably be const)">, + InGroup; + def warn_omp_alignment_not_power_of_two : Warning< + "aligned clause will be ignored because the requested alignment is not a power of 2">, + InGroup; + def err_omp_invalid_target_decl : Error< + "%0 used in declare target directive is not a variable or a function name">; + def err_omp_declare_target_to_and_link : Error< + "%0 must not appear in both clauses 'to' and 'link'">; + def warn_omp_not_in_target_context : Warning< + "declaration is not declared in any declare target region">, + InGroup; + def err_omp_function_in_link_clause : Error< + "function name is not allowed in 'link' clause">; + def err_omp_aligned_expected_array_or_ptr : Error< + "argument of aligned clause should be array" + "%select{ or pointer|, pointer, reference to array or reference to pointer}1" + ", not %0">; + def err_omp_used_in_clause_twice : Error< + "%select{a variable|a parameter|'this'}0 cannot appear in more than one %1 clause">; + def err_omp_local_var_in_threadprivate_init : Error< + "variable with local storage in initial value of threadprivate variable">; + def err_omp_loop_not_canonical_init : Error< + "initialization clause of OpenMP for loop is not in canonical form " + "('var = init' or 'T var = init')">; + def ext_omp_loop_not_canonical_init : ExtWarn< + "initialization clause of OpenMP for loop is not in canonical form " + "('var = init' or 'T var = init')">, InGroup; + def err_omp_loop_not_canonical_cond : Error< + "condition of OpenMP for loop must be a relational comparison " + "('<', '<=', '>', %select{or '>='|'>=', or '!='}0) of loop variable %1">; + def err_omp_loop_not_canonical_incr : Error< + "increment clause of OpenMP for loop must perform simple addition " + "or subtraction on loop variable %0">; + def err_omp_loop_variable_type : Error< + "variable must be of integer or %select{pointer|random access iterator}0 type">; + def err_omp_loop_incr_not_compatible : Error< + "increment expression must cause %0 to %select{decrease|increase}1 " + "on each iteration of OpenMP for loop">; + def note_omp_loop_cond_requres_compatible_incr : Note< + "loop step is expected to be %select{negative|positive}0 due to this condition">; + def err_omp_loop_diff_cxx : Error< + "could not calculate number of iterations calling 'operator-' with " + "upper and lower loop bounds">; + def err_omp_loop_cannot_use_stmt : Error< + "'%0' statement cannot be used in OpenMP for loop">; + def err_omp_simd_region_cannot_use_stmt : Error< + "'%0' statement cannot be used in OpenMP simd region">; + def warn_omp_loop_64_bit_var : Warning< + "OpenMP loop iteration variable cannot have more than 64 bits size and will be narrowed">, + InGroup; + def err_omp_unknown_reduction_identifier : Error< + "incorrect reduction identifier, expected one of '+', '-', '*', '&', '|', '^', " + "'&&', '||', 'min' or 'max' or declare reduction for type %0">; + def err_omp_not_resolved_reduction_identifier : Error< + "unable to resolve declare reduction construct for type %0">; + def err_omp_reduction_ref_type_arg : Error< + "argument of OpenMP clause '%0' must reference the same object in all threads">; + def err_omp_clause_not_arithmetic_type_arg : Error< + "arguments of OpenMP clause '%0' for 'min' or 'max' must be of %select{scalar|arithmetic}1 type">; + def err_omp_clause_floating_type_arg : Error< + "arguments of OpenMP clause '%0' with bitwise operators cannot be of floating type">; + def err_omp_once_referenced : Error< + "variable can appear only once in OpenMP '%0' clause">; + def err_omp_once_referenced_in_target_update : Error< + "variable can appear only once in OpenMP 'target update' construct">; + def note_omp_referenced : Note< + "previously referenced here">; + def err_omp_reduction_in_task : Error< + "reduction variables may not be accessed in an explicit task">; + def err_omp_reduction_id_not_compatible : Error< + "list item of type %0 is not valid for specified reduction operation: unable to provide default initialization value">; + def err_omp_reduction_identifier_mismatch : Error< + "in_reduction variable must have the same reduction operation as in a task_reduction clause">; + def note_omp_previous_reduction_identifier : Note< + "previously marked as task_reduction with different reduction operation">; + def err_omp_prohibited_region : Error< + "region cannot be%select{| closely}0 nested inside '%1' region" + "%select{|; perhaps you forget to enclose 'omp %3' directive into a parallel region?|" + "; perhaps you forget to enclose 'omp %3' directive into a for or a parallel for region with 'ordered' clause?|" + "; perhaps you forget to enclose 'omp %3' directive into a target region?|" + "; perhaps you forget to enclose 'omp %3' directive into a teams region?|" + "; perhaps you forget to enclose 'omp %3' directive into a for, simd, for simd, parallel for, or parallel for simd region?}2">; + def err_omp_prohibited_region_simd : Error< + "OpenMP constructs may not be nested inside a simd region%select{| except for ordered simd, simd, scan, or atomic directive}0">; + def err_omp_prohibited_region_atomic : Error< + "OpenMP constructs may not be nested inside an atomic region">; + def err_omp_prohibited_region_critical_same_name : Error< + "cannot nest 'critical' regions having the same name %0">; + def note_omp_previous_critical_region : Note< + "previous 'critical' region starts here">; + def err_omp_several_directives_in_region : Error< + "exactly one '%0' directive must appear in the loop body of an enclosing directive">; + def note_omp_previous_directive : Note< + "previous '%0' directive used here">; + def err_omp_sections_not_compound_stmt : Error< + "the statement for '#pragma omp sections' must be a compound statement">; + def err_omp_parallel_sections_not_compound_stmt : Error< + "the statement for '#pragma omp parallel sections' must be a compound statement">; + def err_omp_orphaned_section_directive : Error< + "%select{orphaned 'omp section' directives are prohibited, it|'omp section' directive}0" + " must be closely nested to a sections region%select{|, not a %1 region}0">; + def err_omp_sections_substmt_not_section : Error< + "statement in 'omp sections' directive must be enclosed into a section region">; + def err_omp_parallel_sections_substmt_not_section : Error< + "statement in 'omp parallel sections' directive must be enclosed into a section region">; + def err_omp_parallel_reduction_in_task_firstprivate : Error< + "argument of a reduction clause of a %0 construct must not appear in a firstprivate clause on a task construct">; + def err_omp_atomic_read_not_expression_statement : Error< + "the statement for 'atomic read' must be an expression statement of form 'v = x;'," + " where v and x are both lvalue expressions with scalar type">; + def note_omp_atomic_read_write: Note< + "%select{expected an expression statement|expected built-in assignment operator|expected expression of scalar type|expected lvalue expression}0">; + def err_omp_atomic_write_not_expression_statement : Error< + "the statement for 'atomic write' must be an expression statement of form 'x = expr;'," + " where x is a lvalue expression with scalar type">; + def err_omp_atomic_update_not_expression_statement : Error< + "the statement for 'atomic update' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x'," + " where x is an lvalue expression with scalar type">; + def err_omp_atomic_not_expression_statement : Error< + "the statement for 'atomic' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x'," + " where x is an lvalue expression with scalar type">; + def note_omp_atomic_update: Note< + "%select{expected an expression statement|expected built-in binary or unary operator|expected unary decrement/increment operation|" + "expected expression of scalar type|expected assignment expression|expected built-in binary operator|" + "expected one of '+', '*', '-', '/', '&', '^', '%|', '<<', or '>>' built-in operations|expected in right hand side of expression}0">; + def err_omp_atomic_capture_not_expression_statement : Error< + "the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x'," + " where x and v are both lvalue expressions with scalar type">; + def err_omp_atomic_capture_not_compound_statement : Error< + "the statement for 'atomic capture' must be a compound statement of form '{v = x; x binop= expr;}', '{x binop= expr; v = x;}'," + " '{v = x; x = x binop expr;}', '{v = x; x = expr binop x;}', '{x = x binop expr; v = x;}', '{x = expr binop x; v = x;}' or '{v = x; x = expr;}'," + " '{v = x; x++;}', '{v = x; ++x;}', '{++x; v = x;}', '{x++; v = x;}', '{v = x; x--;}', '{v = x; --x;}', '{--x; v = x;}', '{x--; v = x;}'" + " where x is an lvalue expression with scalar type">; + def note_omp_atomic_capture: Note< + "%select{expected assignment expression|expected compound statement|expected exactly two expression statements|expected in right hand side of the first expression}0">; + def err_omp_atomic_several_clauses : Error< + "directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update' or 'capture' clause">; + def err_omp_several_mem_order_clauses : Error< + "directive '#pragma omp %0' cannot contain more than one %select{'seq_cst', 'relaxed', |}1'acq_rel', 'acquire' or 'release' clause">; + def err_omp_atomic_incompatible_mem_order_clause : Error< + "directive '#pragma omp atomic%select{ %0|}1' cannot be used with '%2' clause">; + def note_omp_previous_mem_order_clause : Note< + "'%0' clause used here">; + def err_omp_target_contains_not_only_teams : Error< + "target construct with nested teams region contains statements outside of the teams construct">; + def note_omp_nested_teams_construct_here : Note< + "nested teams construct here">; + def note_omp_nested_statement_here : Note< + "%select{statement|directive}0 outside teams construct here">; + def err_omp_single_copyprivate_with_nowait : Error< + "the 'copyprivate' clause must not be used with the 'nowait' clause">; + def note_omp_nowait_clause_here : Note< + "'nowait' clause is here">; + def err_omp_single_decl_in_declare_simd_variant : Error< + "single declaration is expected after 'declare %select{simd|variant}0' directive">; + def err_omp_function_expected : Error< + "'#pragma omp declare %select{simd|variant}0' can only be applied to functions">; + def err_omp_wrong_cancel_region : Error< + "one of 'for', 'parallel', 'sections' or 'taskgroup' is expected">; + def err_omp_parent_cancel_region_nowait : Error< + "parent region for 'omp %select{cancellation point|cancel}0' construct cannot be nowait">; + def err_omp_parent_cancel_region_ordered : Error< + "parent region for 'omp %select{cancellation point|cancel}0' construct cannot be ordered">; + def err_omp_reduction_wrong_type : Error<"reduction type cannot be %select{qualified with 'const', 'volatile' or 'restrict'|a function|a reference|an array}0 type">; + def err_omp_wrong_var_in_declare_reduction : Error<"only %select{'omp_priv' or 'omp_orig'|'omp_in' or 'omp_out'}0 variables are allowed in %select{initializer|combiner}0 expression">; + def err_omp_declare_reduction_redefinition : Error<"redefinition of user-defined reduction for type %0">; + def err_omp_mapper_wrong_type : Error< + "mapper type must be of struct, union or class type">; + def err_omp_declare_mapper_wrong_var : Error< + "only variable %0 is allowed in map clauses of this 'omp declare mapper' directive">; + def err_omp_declare_mapper_redefinition : Error< + "redefinition of user-defined mapper for type %0 with name %1">; + def err_omp_invalid_mapper: Error< + "cannot find a valid user-defined mapper for type %0 with name %1">; + def err_omp_array_section_use : Error<"OpenMP array section is not allowed here">; + def err_omp_array_shaping_use : Error<"OpenMP array shaping operation is not allowed here">; + def err_omp_iterator_use : Error<"OpenMP iterator is not allowed here">; + def err_omp_typecheck_section_value : Error< + "subscripted value is not an array or pointer">; + def err_omp_typecheck_section_not_integer : Error< + "array section %select{lower bound|length}0 is not an integer">; + def err_omp_typecheck_shaping_not_integer : Error< + "array shaping operation dimension is not an integer">; + def err_omp_shaping_dimension_not_positive : Error< + "array shaping dimension is evaluated to a non-positive value %0">; + def err_omp_section_function_type : Error< + "section of pointer to function type %0">; + def warn_omp_section_is_char : Warning<"array section %select{lower bound|length}0 is of type 'char'">, + InGroup, DefaultIgnore; + def err_omp_section_incomplete_type : Error< + "section of pointer to incomplete type %0">; + def err_omp_section_not_subset_of_array : Error< + "array section must be a subset of the original array">; + def err_omp_section_length_negative : Error< + "section length is evaluated to a negative value %0">; + def err_omp_section_stride_non_positive : Error< + "section stride is evaluated to a non-positive value %0">; + def err_omp_section_length_undefined : Error< + "section length is unspecified and cannot be inferred because subscripted value is %select{not an array|an array of unknown bound}0">; + def err_omp_wrong_linear_modifier : Error< + "expected %select{'val' modifier|one of 'ref', val' or 'uval' modifiers}0">; + def err_omp_wrong_linear_modifier_non_reference : Error< + "variable of non-reference type %0 can be used only with 'val' modifier, but used with '%1'">; + def err_omp_wrong_simdlen_safelen_values : Error< + "the value of 'simdlen' parameter must be less than or equal to the value of the 'safelen' parameter">; + def err_omp_wrong_if_directive_name_modifier : Error< + "directive name modifier '%0' is not allowed for '#pragma omp %1'">; + def err_omp_no_more_if_clause : Error< + "no more 'if' clause is allowed">; + def err_omp_unnamed_if_clause : Error< + "expected%select{| one of}0 %1 directive name modifier%select{|s}0">; + def note_omp_previous_named_if_clause : Note< + "previous clause with directive name modifier specified here">; + def err_omp_ordered_directive_with_param : Error< + "'ordered' directive %select{without any clauses|with 'threads' clause}0 cannot be closely nested inside ordered region with specified parameter">; + def err_omp_ordered_directive_without_param : Error< + "'ordered' directive with 'depend' clause cannot be closely nested inside ordered region without specified parameter">; + def note_omp_ordered_param : Note< + "'ordered' clause%select{| with specified parameter}0">; + def err_omp_expected_base_var_name : Error< + "expected variable name as a base of the array %select{subscript|section}0">; + def err_omp_map_shared_storage : Error< + "variable already marked as mapped in current construct">; + def err_omp_invalid_map_type_for_directive : Error< + "%select{map type '%1' is not allowed|map type must be specified}0 for '#pragma omp %2'">; + def err_omp_invalid_map_type_modifier_for_directive : Error< + "map type modifier '%0' is not allowed for '#pragma omp %1'">; + def err_omp_no_clause_for_directive : Error< + "expected at least one %0 clause for '#pragma omp %1'">; + def err_omp_threadprivate_in_clause : Error< + "threadprivate variables are not allowed in '%0' clause">; + def err_omp_wrong_ordered_loop_count : Error< + "the parameter of the 'ordered' clause must be greater than or equal to the parameter of the 'collapse' clause">; + def note_collapse_loop_count : Note< + "parameter of the 'collapse' clause">; + def err_omp_clauses_mutually_exclusive : Error< + "'%0' and '%1' clause are mutually exclusive and may not appear on the same directive">; + def note_omp_previous_clause : Note< + "'%0' clause is specified here">; + def err_omp_hint_clause_no_name : Error< + "the name of the construct must be specified in presence of 'hint' clause">; + def err_omp_critical_with_hint : Error< + "constructs with the same name must have a 'hint' clause with the same value">; + def note_omp_critical_hint_here : Note< + "%select{|previous }0'hint' clause with value '%1'">; + def note_omp_critical_no_hint : Note< + "%select{|previous }0directive with no 'hint' clause specified">; + def err_omp_depend_clause_thread_simd : Error< + "'depend' clauses cannot be mixed with '%0' clause">; + def err_omp_depend_sink_expected_loop_iteration : Error< + "expected%select{| %1}0 loop iteration variable">; + def err_omp_depend_sink_unexpected_expr : Error< + "unexpected expression: number of expressions is larger than the number of associated loops">; + def err_omp_depend_sink_expected_plus_minus : Error< + "expected '+' or '-' operation">; + def err_omp_depend_sink_source_not_allowed : Error< + "'depend(%select{source|sink:vec}0)' clause%select{|s}0 cannot be mixed with 'depend(%select{sink:vec|source}0)' clause%select{s|}0">; + def err_omp_depend_zero_length_array_section_not_allowed : Error< + "zero-length array section is not allowed in 'depend' clause">; + def err_omp_depend_sink_source_with_modifier : Error< + "depend modifier cannot be used with 'sink' or 'source' depend type">; + def err_omp_depend_modifier_not_iterator : Error< + "expected iterator specification as depend modifier">; + def err_omp_linear_ordered : Error< + "'linear' clause cannot be specified along with 'ordered' clause with a parameter">; + def err_omp_unexpected_schedule_modifier : Error< + "modifier '%0' cannot be used along with modifier '%1'">; + def err_omp_schedule_nonmonotonic_static : Error< + "'nonmonotonic' modifier can only be specified with 'dynamic' or 'guided' schedule kind">; + def err_omp_simple_clause_incompatible_with_ordered : Error< + "'%0' clause with '%1' modifier cannot be specified if an 'ordered' clause is specified">; + def err_omp_ordered_simd : Error< + "'ordered' clause with a parameter can not be specified in '#pragma omp %0' directive">; + def err_omp_variable_in_given_clause_and_dsa : Error< + "%0 variable cannot be in a %1 clause in '#pragma omp %2' directive">; + def err_omp_param_or_this_in_clause : Error< + "expected reference to one of the parameters of function %0%select{| or 'this'}1">; + def err_omp_expected_uniform_param : Error< + "expected a reference to a parameter specified in a 'uniform' clause">; + def err_omp_expected_int_param : Error< + "expected a reference to an integer-typed parameter">; + def err_omp_at_least_one_motion_clause_required : Error< + "expected at least one 'to' clause or 'from' clause specified to '#pragma omp target update'">; + def err_omp_usedeviceptr_not_a_pointer : Error< + "expected pointer or reference to pointer in 'use_device_ptr' clause">; + def err_omp_argument_type_isdeviceptr : Error < + "expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'">; + def warn_omp_nesting_simd : Warning< + "OpenMP only allows an ordered construct with the simd clause nested in a simd construct">, + InGroup; + def err_omp_orphaned_device_directive : Error< + "orphaned 'omp %0' directives are prohibited" + "; perhaps you forget to enclose the directive into a " + "%select{|||target |teams|for, simd, for simd, parallel for, or parallel for simd }1region?">; + def err_omp_reduction_non_addressable_expression : Error< + "expected addressable reduction item for the task-based directives">; + def err_omp_reduction_with_nogroup : Error< + "'reduction' clause cannot be used with 'nogroup' clause">; + def err_omp_reduction_vla_unsupported : Error< + "cannot generate code for reduction on %select{|array section, which requires a }0variable length array">; + def err_omp_linear_distribute_var_non_loop_iteration : Error< + "only loop iteration variables are allowed in 'linear' clause in distribute directives">; + def warn_omp_non_trivial_type_mapped : Warning< + "Type %0 is not trivially copyable and not guaranteed to be mapped correctly">, + InGroup; + def err_omp_requires_clause_redeclaration : Error < + "Only one %0 clause can appear on a requires directive in a single translation unit">; + def note_omp_requires_previous_clause : Note < + "%0 clause previously used here">; + def err_omp_directive_before_requires : Error < + "'%0' region encountered before requires directive with '%1' clause">; + def note_omp_requires_encountered_directive : Note < + "'%0' previously encountered here">; + def err_omp_invalid_scope : Error < + "'#pragma omp %0' directive must appear only in file scope">; + def note_omp_invalid_length_on_this_ptr_mapping : Note < + "expected length on mapping of 'this' array section expression to be '1'">; + def note_omp_invalid_lower_bound_on_this_ptr_mapping : Note < + "expected lower bound on mapping of 'this' array section expression to be '0' or not specified">; + def note_omp_invalid_subscript_on_this_ptr_map : Note < + "expected 'this' subscript expression on map clause to be 'this[0]'">; + def err_omp_invalid_map_this_expr : Error < + "invalid 'this' expression on 'map' clause">; + def err_omp_implied_type_not_found : Error< + "'%0' type not found; include ">; + def err_omp_expected_omp_depend_t_lvalue : Error< + "expected lvalue expression%select{ of 'omp_depend_t' type, not %1|}0">; + def err_omp_depobj_expected : Error< + "expected depobj expression">; + def err_omp_depobj_single_clause_expected : Error< + "exactly one of 'depend', 'destroy', or 'update' clauses is expected">; + def err_omp_scan_single_clause_expected : Error< + "exactly one of 'inclusive' or 'exclusive' clauses is expected">; + def err_omp_inclusive_exclusive_not_reduction : Error< + "the list item must appear in 'reduction' clause with the 'inscan' modifier " + "of the parent directive">; + def err_omp_reduction_not_inclusive_exclusive : Error< + "the inscan reduction list item must appear as a list item in an 'inclusive' or" + " 'exclusive' clause on an inner 'omp scan' directive">; + def err_omp_wrong_inscan_reduction : Error< + "'inscan' modifier can be used only in 'omp for', 'omp simd', 'omp for simd'," + " 'omp parallel for', or 'omp parallel for simd' directive">; + def err_omp_inscan_reduction_expected : Error< + "expected 'reduction' clause with the 'inscan' modifier">; + def note_omp_previous_inscan_reduction : Note< + "'reduction' clause with 'inscan' modifier is used here">; + def err_omp_expected_predefined_allocator : Error< + "expected one of the predefined allocators for the variables with the static " + "storage: 'omp_default_mem_alloc', 'omp_large_cap_mem_alloc', " + "'omp_const_mem_alloc', 'omp_high_bw_mem_alloc', 'omp_low_lat_mem_alloc', " + "'omp_cgroup_mem_alloc', 'omp_pteam_mem_alloc' or 'omp_thread_mem_alloc'">; + def warn_omp_used_different_allocator : Warning< + "allocate directive specifies %select{default|'%1'}0 allocator while " + "previously used %select{default|'%3'}2">, + InGroup; + def note_omp_previous_allocator : Note< + "previous allocator is specified here">; + def err_expected_allocator_clause : Error<"expected an 'allocator' clause " + "inside of the target region; provide an 'allocator' clause or use 'requires'" + " directive with the 'dynamic_allocators' clause">; + def err_expected_allocator_expression : Error<"expected an allocator expression " + "inside of the target region; provide an allocator expression or use 'requires'" + " directive with the 'dynamic_allocators' clause">; + def warn_omp_allocate_thread_on_task_target_directive : Warning< + "allocator with the 'thread' trait access has unspecified behavior on '%0' directive">, + InGroup; + def err_omp_expected_private_copy_for_allocate : Error< + "the referenced item is not found in any private clause on the same directive">; + def err_omp_stmt_depends_on_loop_counter : Error< + "the loop %select{initializer|condition}0 expression depends on the current loop control variable">; + def err_omp_invariant_dependency : Error< + "expected loop invariant expression">; + def err_omp_invariant_or_linear_dependency : Error< + "expected loop invariant expression or ' * %0 + ' kind of expression">; + def err_omp_wrong_dependency_iterator_type : Error< + "expected an integer or a pointer type of the outer loop counter '%0' for non-rectangular nests">; + def err_device_unsupported_type + : Error<"%0 requires %select{|%2 bit size}1 %3 type support, but device " + "'%4' does not support it">; + def err_omp_lambda_capture_in_declare_target_not_to : Error< + "variable captured in declare target region must appear in a to clause">; + def err_omp_device_type_mismatch : Error< + "'device_type(%0)' does not match previously specified 'device_type(%1)' for the same declaration">; + def err_omp_wrong_device_function_call : Error< + "function with 'device_type(%0)' is not available on %select{device|host}1">; + def note_omp_marked_device_type_here : Note<"marked as 'device_type(%0)' here">; + def warn_omp_declare_target_after_first_use : Warning< + "declaration marked as declare target after first use, it may lead to incorrect results">, + InGroup; + def err_omp_declare_variant_incompat_attributes : Error< + "'#pragma omp declare variant' is not compatible with any target-specific attributes">; + def warn_omp_declare_variant_score_not_constant + : Warning<"score expressions in the OpenMP context selector need to be " + "constant; %0 is not and will be ignored">, + InGroup; + def err_omp_declare_variant_user_condition_not_constant + : Error<"the user condition in the OpenMP context selector needs to be " + "constant; %0 is not">; + def warn_omp_declare_variant_after_used : Warning< + "'#pragma omp declare variant' cannot be applied for function after first " + "usage; the original function might be used">, InGroup; + def warn_omp_declare_variant_after_emitted : Warning< + "'#pragma omp declare variant' cannot be applied to the function that was defined already;" + " the original function might be used">, InGroup; + def err_omp_declare_variant_doesnt_support : Error< + "'#pragma omp declare variant' does not " + "support %select{function templates|virtual functions|" + "deduced return types|constructors|destructors|deleted functions|" + "defaulted functions|constexpr functions|consteval function}0">; + def err_omp_declare_variant_diff : Error< + "function with '#pragma omp declare variant' has a different %select{calling convention" + "|return type|constexpr specification|inline specification|storage class|" + "linkage}0">; + def err_omp_declare_variant_incompat_types : Error< + "variant in '#pragma omp declare variant' with type %0 is incompatible with type %1" + >; + def warn_omp_declare_variant_marked_as_declare_variant : Warning< + "variant function in '#pragma omp declare variant' is itself marked as '#pragma omp declare variant'" + >, InGroup; + def note_omp_marked_declare_variant_here : Note<"marked as 'declare variant' here">; + def err_omp_one_defaultmap_each_category: Error< + "at most one defaultmap clause for each variable-category can appear on the directive">; + def err_omp_lastprivate_conditional_non_scalar : Error< + "expected list item of scalar type in 'lastprivate' clause with 'conditional' modifier" + >; + def err_omp_flush_order_clause_and_list : Error< + "'flush' directive with memory order clause '%0' cannot have the list">; + def note_omp_flush_order_clause_here : Note< + "memory order clause '%0' is specified here">; + def err_omp_non_lvalue_in_map_or_motion_clauses: Error< + "expected addressable lvalue in '%0' clause">; + def err_omp_var_expected : Error< + "expected variable of the '%0' type%select{|, not %2}1">; + def warn_unknown_declare_variant_isa_trait + : Warning<"isa trait '%0' is not known to the current target; verify the " + "spelling or consider restricting the context selector with the " + "'arch' selector further">, + InGroup; + def err_omp_non_pointer_type_array_shaping_base : Error< + "expected expression with a pointer to a complete type as a base of an array " + "shaping operation">; + def err_omp_reduction_task_not_parallel_or_worksharing : Error< + "'reduction' clause with 'task' modifier allowed only on non-simd parallel or" + " worksharing constructs">; + def err_omp_expected_array_alloctraits : Error< + "expected constant sized array of 'omp_alloctrait_t' elements, not %0">; + def err_omp_predefined_allocator_with_traits : Error< + "predefined allocator cannot have traits specified">; + def note_omp_predefined_allocator : Note< + "predefined trait '%0' used here">; + def err_omp_nonpredefined_allocator_without_traits : Error< + "non-predefined allocator must have traits specified">; + def err_omp_allocator_used_in_clauses : Error< + "allocators used in 'uses_allocators' clause cannot appear in other " + "data-sharing or data-mapping attribute clauses">; + def err_omp_allocator_not_in_uses_allocators : Error< + "allocator must be specified in the 'uses_allocators' clause">; + def note_omp_protected_structured_block + : Note<"jump bypasses OpenMP structured block">; + def note_omp_exits_structured_block + : Note<"jump exits scope of OpenMP structured block">; + def err_omp_interop_variable_expected : Error< + "expected%select{| non-const}0 variable of type 'omp_interop_t'">; + def err_omp_interop_variable_wrong_type : Error< + "interop variable must be of type 'omp_interop_t'">; + def err_omp_interop_prefer_type : Error< + "prefer_list item must be a string literal or constant integral " + "expression">; + def err_omp_interop_bad_depend_clause : Error< + "'depend' clause requires the 'targetsync' interop type">; + def err_omp_interop_var_multiple_actions : Error< + "interop variable %0 used in multiple action clauses">; + def err_omp_dispatch_statement_call + : Error<"statement after '#pragma omp dispatch' must be a direct call" + " to a target function or an assignment to one">; + def err_omp_unroll_full_variable_trip_count : Error< + "loop to be fully unrolled must have a constant trip count">; + def note_omp_directive_here : Note<"'%0' directive found here">; + def err_omp_instantiation_not_supported + : Error<"instantiation of '%0' not supported yet">; + } // end of OpenMP category + + let CategoryName = "Related Result Type Issue" in { + // Objective-C related result type compatibility + def warn_related_result_type_compatibility_class : Warning< + "method is expected to return an instance of its class type " + "%diff{$, but is declared to return $|" + ", but is declared to return different type}0,1">; + def warn_related_result_type_compatibility_protocol : Warning< + "protocol method is expected to return an instance of the implementing " + "class, but is declared to return %0">; + def note_related_result_type_family : Note< + "%select{overridden|current}0 method is part of the '%select{|alloc|copy|init|" + "mutableCopy|new|autorelease|dealloc|finalize|release|retain|retainCount|" + "self}1' method family%select{| and is expected to return an instance of its " + "class type}0">; + def note_related_result_type_overridden : Note< + "overridden method returns an instance of its class type">; + def note_related_result_type_inferred : Note< + "%select{class|instance}0 method %1 is assumed to return an instance of " + "its receiver type (%2)">; + def note_related_result_type_explicit : Note< + "%select{overridden|current}0 method is explicitly declared 'instancetype'" + "%select{| and is expected to return an instance of its class type}0">; + def err_invalid_type_for_program_scope_var : Error< + "the %0 type cannot be used to declare a program scope variable">; + + } + + let CategoryName = "Modules Issue" in { + def err_module_decl_in_module_map_module : Error< + "'module' declaration found while building module from module map">; + def err_module_decl_in_header_module : Error< + "'module' declaration found while building header unit">; + def err_module_interface_implementation_mismatch : Error< + "missing 'export' specifier in module declaration while " + "building module interface">; + def err_current_module_name_mismatch : Error< + "module name '%0' specified on command line does not match name of module">; + def err_module_redefinition : Error< + "redefinition of module '%0'">; + def note_prev_module_definition : Note<"previously defined here">; + def note_prev_module_definition_from_ast_file : Note<"module loaded from '%0'">; + def err_module_not_defined : Error< + "definition of module '%0' is not available; use -fmodule-file= to specify " + "path to precompiled module interface">; + def err_module_redeclaration : Error< + "translation unit contains multiple module declarations">; + def note_prev_module_declaration : Note<"previous module declaration is here">; + def err_module_declaration_missing : Error< + "missing 'export module' declaration in module interface unit">; + def err_module_declaration_missing_after_global_module_introducer : Error< + "missing 'module' declaration at end of global module fragment " + "introduced here">; + def err_module_private_specialization : Error< + "%select{template|partial|member}0 specialization cannot be " + "declared __module_private__">; + def err_module_private_local : Error< + "%select{local variable|parameter|typedef}0 %1 cannot be declared " + "__module_private__">; + def err_module_private_local_class : Error< + "local %select{struct|interface|union|class|enum}0 cannot be declared " + "__module_private__">; + def err_module_unimported_use : Error< + "%select{declaration|definition|default argument|" + "explicit specialization|partial specialization}0 of %1 must be imported " + "from module '%2' before it is required">; + def err_module_unimported_use_header : Error< + "%select{missing '#include'|missing '#include %3'}2; " + "%select{||default argument of |explicit specialization of |" + "partial specialization of }0%1 must be " + "%select{declared|defined|defined|declared|declared}0 " + "before it is used">; + def err_module_unimported_use_multiple : Error< + "%select{declaration|definition|default argument|" + "explicit specialization|partial specialization}0 of %1 must be imported " + "from one of the following modules before it is required:%2">; + def note_unreachable_entity : Note< + "%select{declaration|definition|default argument declared|" + "explicit specialization declared|partial specialization declared}0 here " + "is not %select{visible|reachable|reachable|reachable|reachable|reachable}0">; + def ext_module_import_in_extern_c : ExtWarn< + "import of C++ module '%0' appears within extern \"C\" language linkage " + "specification">, DefaultError, + InGroup>; + def err_module_import_not_at_top_level_fatal : Error< + "import of module '%0' appears within %1">, DefaultFatal; + def ext_module_import_not_at_top_level_noop : ExtWarn< + "redundant #include of module '%0' appears within %1">, DefaultError, + InGroup>; + def note_module_import_not_at_top_level : Note<"%0 begins here">; + def err_module_self_import : Error< + "import of module '%0' appears within same top-level module '%1'">; + def err_module_import_in_implementation : Error< + "@import of module '%0' in implementation of '%1'; use #import">; + + // C++ Modules + def err_module_decl_not_at_start : Error< + "module declaration must occur at the start of the translation unit">; + def note_global_module_introducer_missing : Note< + "add 'module;' to the start of the file to introduce a " + "global module fragment">; + def err_export_within_anonymous_namespace : Error< + "export declaration appears within anonymous namespace">; + def note_anonymous_namespace : Note<"anonymous namespace begins here">; + def ext_export_no_name_block : ExtWarn< + "ISO C++20 does not permit %select{an empty|a static_assert}0 declaration " + "to appear in an export block">, InGroup; + def ext_export_no_names : ExtWarn< + "ISO C++20 does not permit a declaration that does not introduce any names " + "to be exported">, InGroup; + def note_export : Note<"export block begins here">; + def err_export_no_name : Error< + "%select{empty|static_assert|asm}0 declaration cannot be exported">; + def ext_export_using_directive : ExtWarn< + "ISO C++20 does not permit using directive to be exported">, + InGroup>; + def err_export_within_export : Error< + "export declaration appears within another export declaration">; + def err_export_internal : Error< + "declaration of %0 with internal linkage cannot be exported">; + def err_export_using_internal : Error< + "using declaration referring to %0 with internal linkage cannot be exported">; + def err_export_not_in_module_interface : Error< + "export declaration can only be used within a module interface unit" + "%select{ after the module declaration|}0">; + def err_export_in_private_module_fragment : Error< + "export declaration cannot be used in a private module fragment">; + def note_private_module_fragment : Note< + "private module fragment begins here">; + def err_private_module_fragment_not_module : Error< + "private module fragment declaration with no preceding module declaration">; + def err_private_module_fragment_redefined : Error< + "private module fragment redefined">; + def err_private_module_fragment_not_module_interface : Error< + "private module fragment in module implementation unit">; + def note_not_module_interface_add_export : Note< + "add 'export' here if this is intended to be a module interface unit">; + + def ext_equivalent_internal_linkage_decl_in_modules : ExtWarn< + "ambiguous use of internal linkage declaration %0 defined in multiple modules">, + InGroup>; + def note_equivalent_internal_linkage_decl : Note< + "declared here%select{ in module '%1'|}0">; + + def note_redefinition_modules_same_file : Note< + "'%0' included multiple times, additional include site in header from module '%1'">; + def note_redefinition_include_same_file : Note< + "'%0' included multiple times, additional include site here">; + } + + let CategoryName = "Coroutines Issue" in { + def err_return_in_coroutine : Error< + "return statement not allowed in coroutine; did you mean 'co_return'?">; + def note_declared_coroutine_here : Note< + "function is a coroutine due to use of '%0' here">; + def err_coroutine_objc_method : Error< + "Objective-C methods as coroutines are not yet supported">; + def err_coroutine_unevaluated_context : Error< + "'%0' cannot be used in an unevaluated context">; + def err_coroutine_within_handler : Error< + "'%0' cannot be used in the handler of a try block">; + def err_coroutine_outside_function : Error< + "'%0' cannot be used outside a function">; + def err_coroutine_invalid_func_context : Error< + "'%1' cannot be used in %select{a constructor|a destructor" + "|the 'main' function|a constexpr function" + "|a function with a deduced return type|a varargs function" + "|a consteval function}0">; + def err_implied_coroutine_type_not_found : Error< + "%0 type was not found; include before defining " + "a coroutine">; + def err_implicit_coroutine_std_nothrow_type_not_found : Error< + "std::nothrow was not found; include before defining a coroutine which " + "uses get_return_object_on_allocation_failure()">; + def err_malformed_std_nothrow : Error< + "std::nothrow must be a valid variable declaration">; + def err_malformed_std_coroutine_handle : Error< + "std::experimental::coroutine_handle must be a class template">; + def err_coroutine_handle_missing_member : Error< + "std::experimental::coroutine_handle missing a member named '%0'">; + def err_malformed_std_coroutine_traits : Error< + "'std::experimental::coroutine_traits' must be a class template">; + def err_implied_std_coroutine_traits_promise_type_not_found : Error< + "this function cannot be a coroutine: %q0 has no member named 'promise_type'">; + def err_implied_std_coroutine_traits_promise_type_not_class : Error< + "this function cannot be a coroutine: %0 is not a class">; + def err_coroutine_promise_type_incomplete : Error< + "this function cannot be a coroutine: %0 is an incomplete type">; + def err_coroutine_type_missing_specialization : Error< + "this function cannot be a coroutine: missing definition of " + "specialization %0">; + def err_coroutine_promise_incompatible_return_functions : Error< + "the coroutine promise type %0 declares both 'return_value' and 'return_void'">; + def err_coroutine_promise_requires_return_function : Error< + "the coroutine promise type %0 must declare either 'return_value' or 'return_void'">; + def note_coroutine_promise_implicit_await_transform_required_here : Note< + "call to 'await_transform' implicitly required by 'co_await' here">; + def note_coroutine_promise_suspend_implicitly_required : Note< + "call to '%select{initial_suspend|final_suspend}0' implicitly " + "required by the %select{initial suspend point|final suspend point}0">; + def err_coroutine_promise_unhandled_exception_required : Error< + "%0 is required to declare the member 'unhandled_exception()'">; + def warn_coroutine_promise_unhandled_exception_required_with_exceptions : Warning< + "%0 is required to declare the member 'unhandled_exception()' when exceptions are enabled">, + InGroup; + def err_coroutine_promise_get_return_object_on_allocation_failure : Error< + "%0: 'get_return_object_on_allocation_failure()' must be a static member function">; + def err_seh_in_a_coroutine_with_cxx_exceptions : Error< + "cannot use SEH '__try' in a coroutine when C++ exceptions are enabled">; + def err_coroutine_promise_new_requires_nothrow : Error< + "%0 is required to have a non-throwing noexcept specification when the promise " + "type declares 'get_return_object_on_allocation_failure()'">; + def note_coroutine_promise_call_implicitly_required : Note< + "call to %0 implicitly required by coroutine function here">; + def err_await_suspend_invalid_return_type : Error< + "return type of 'await_suspend' is required to be 'void' or 'bool' (have %0)" + >; + def note_await_ready_no_bool_conversion : Note< + "return type of 'await_ready' is required to be contextually convertible to 'bool'" + >; + def warn_coroutine_handle_address_invalid_return_type : Warning < + "return type of 'coroutine_handle<>::address should be 'void*' (have %0) in order to get capability with existing async C API.">, + InGroup; + def err_coroutine_promise_final_suspend_requires_nothrow : Error< + "the expression 'co_await __promise.final_suspend()' is required to be non-throwing" + >; + def note_coroutine_function_declare_noexcept : Note< + "must be declared with 'noexcept'" + >; + } // end of coroutines issue category + + let CategoryName = "Documentation Issue" in { + def warn_not_a_doxygen_trailing_member_comment : Warning< + "not a Doxygen trailing comment">, InGroup, DefaultIgnore; + } // end of documentation issue category + + let CategoryName = "Nullability Issue" in { + + def warn_mismatched_nullability_attr : Warning< + "nullability specifier %0 conflicts with existing specifier %1">, + InGroup; + + def warn_nullability_declspec : Warning< + "nullability specifier %0 cannot be applied " + "to non-pointer type %1; did you mean to apply the specifier to the " + "%select{pointer|block pointer|member pointer|function pointer|" + "member function pointer}2?">, + InGroup, + DefaultError; + + def note_nullability_here : Note<"%0 specified here">; + + def err_nullability_nonpointer : Error< + "nullability specifier %0 cannot be applied to non-pointer type %1">; + + def warn_nullability_lost : Warning< + "implicit conversion from nullable pointer %0 to non-nullable pointer " + "type %1">, + InGroup, DefaultIgnore; + def warn_zero_as_null_pointer_constant : Warning< + "zero as null pointer constant">, + InGroup>, DefaultIgnore; + + def err_nullability_cs_multilevel : Error< + "nullability keyword %0 cannot be applied to multi-level pointer type %1">; + def note_nullability_type_specifier : Note< + "use nullability type specifier %0 to affect the innermost " + "pointer type of %1">; + + def warn_null_resettable_setter : Warning< + "synthesized setter %0 for null_resettable property %1 does not handle nil">, + InGroup; + + def warn_nullability_missing : Warning< + "%select{pointer|block pointer|member pointer}0 is missing a nullability " + "type specifier (_Nonnull, _Nullable, or _Null_unspecified)">, + InGroup; + def warn_nullability_missing_array : Warning< + "array parameter is missing a nullability type specifier (_Nonnull, " + "_Nullable, or _Null_unspecified)">, + InGroup; + def note_nullability_fix_it : Note< + "insert '%select{_Nonnull|_Nullable|_Null_unspecified}0' if the " + "%select{pointer|block pointer|member pointer|array parameter}1 " + "%select{should never be null|may be null|should not declare nullability}0">; + + def warn_nullability_inferred_on_nested_type : Warning< + "inferring '_Nonnull' for pointer type within %select{array|reference}0 is " + "deprecated">, + InGroup; + + def err_objc_type_arg_explicit_nullability : Error< + "type argument %0 cannot explicitly specify nullability">; + + def err_objc_type_param_bound_explicit_nullability : Error< + "type parameter %0 bound %1 cannot explicitly specify nullability">; + + } + + let CategoryName = "Generics Issue" in { + + def err_objc_type_param_bound_nonobject : Error< + "type bound %0 for type parameter %1 is not an Objective-C pointer type">; + + def err_objc_type_param_bound_missing_pointer : Error< + "missing '*' in type bound %0 for type parameter %1">; + def err_objc_type_param_bound_qualified : Error< + "type bound %1 for type parameter %0 cannot be qualified with '%2'">; + + def err_objc_type_param_redecl : Error< + "redeclaration of type parameter %0">; + + def err_objc_type_param_arity_mismatch : Error< + "%select{forward class declaration|class definition|category|extension}0 has " + "too %select{few|many}1 type parameters (expected %2, have %3)">; + + def err_objc_type_param_bound_conflict : Error< + "type bound %0 for type parameter %1 conflicts with " + "%select{implicit|previous}2 bound %3%select{for type parameter %5|}4">; + + def err_objc_type_param_variance_conflict : Error< + "%select{in|co|contra}0variant type parameter %1 conflicts with previous " + "%select{in|co|contra}2variant type parameter %3">; + + def note_objc_type_param_here : Note<"type parameter %0 declared here">; + + def err_objc_type_param_bound_missing : Error< + "missing type bound %0 for type parameter %1 in %select{@interface|@class}2">; + + def err_objc_parameterized_category_nonclass : Error< + "%select{extension|category}0 of non-parameterized class %1 cannot have type " + "parameters">; + + def err_objc_parameterized_forward_class : Error< + "forward declaration of non-parameterized class %0 cannot have type " + "parameters">; + + def err_objc_parameterized_forward_class_first : Error< + "class %0 previously declared with type parameters">; + + def err_objc_type_arg_missing_star : Error< + "type argument %0 must be a pointer (requires a '*')">; + def err_objc_type_arg_qualified : Error< + "type argument %0 cannot be qualified with '%1'">; + + def err_objc_type_arg_missing : Error< + "no type or protocol named %0">; + + def err_objc_type_args_and_protocols : Error< + "angle brackets contain both a %select{type|protocol}0 (%1) and a " + "%select{protocol|type}0 (%2)">; + + def err_objc_type_args_non_class : Error< + "type arguments cannot be applied to non-class type %0">; + + def err_objc_type_args_non_parameterized_class : Error< + "type arguments cannot be applied to non-parameterized class %0">; + + def err_objc_type_args_specialized_class : Error< + "type arguments cannot be applied to already-specialized class type %0">; + + def err_objc_type_args_wrong_arity : Error< + "too %select{many|few}0 type arguments for class %1 (have %2, expected %3)">; + } + + def err_objc_type_arg_not_id_compatible : Error< + "type argument %0 is neither an Objective-C object nor a block type">; + + def err_objc_type_arg_does_not_match_bound : Error< + "type argument %0 does not satisfy the bound (%1) of type parameter %2">; + + def warn_objc_redundant_qualified_class_type : Warning< + "parameterized class %0 already conforms to the protocols listed; did you " + "forget a '*'?">, InGroup; + + def warn_block_literal_attributes_on_omitted_return_type : Warning< + "attribute %0 ignored, because it cannot be applied to omitted return type">, + InGroup; + + def warn_block_literal_qualifiers_on_omitted_return_type : Warning< + "'%0' qualifier on omitted return type %1 has no effect">, + InGroup; + + def warn_shadow_field : Warning< + "%select{parameter|non-static data member}3 %0 %select{|of %1 }3shadows " + "member inherited from type %2">, InGroup, DefaultIgnore; + def note_shadow_field : Note<"declared here">; + + def err_multiversion_required_in_redecl : Error< + "function declaration is missing %select{'target'|'cpu_specific' or " + "'cpu_dispatch'}0 attribute in a multiversioned function">; + def note_multiversioning_caused_here : Note< + "function multiversioning caused by this declaration">; + def err_multiversion_after_used : Error< + "function declaration cannot become a multiversioned function after first " + "usage">; + def err_bad_multiversion_option : Error< + "function multiversioning doesn't support %select{feature|architecture}0 " + "'%1'">; + def err_multiversion_duplicate : Error< + "multiversioned function redeclarations require identical target attributes">; + def err_multiversion_noproto : Error< + "multiversioned function must have a prototype">; + def err_multiversion_disallowed_other_attr : Error< + "attribute '%select{target|cpu_specific|cpu_dispatch}0' multiversioning cannot be combined" + " with attribute %1">; + def err_multiversion_mismatched_attrs + : Error<"attributes on multiversioned functions must all match, attribute " + "%0 %select{is missing|has different arguments}1">; + def err_multiversion_diff : Error< + "multiversioned function declaration has a different %select{calling convention" + "|return type|constexpr specification|inline specification|linkage|" + "language linkage}0">; + def err_multiversion_doesnt_support : Error< + "attribute '%select{target|cpu_specific|cpu_dispatch}0' multiversioned functions do not " + "yet support %select{function templates|virtual functions|" + "deduced return types|constructors|destructors|deleted functions|" + "defaulted functions|constexpr functions|consteval function}1">; + def err_multiversion_not_allowed_on_main : Error< + "'main' cannot be a multiversioned function">; + def err_multiversion_not_supported : Error< + "function multiversioning is not supported on the current target">; + def err_multiversion_types_mixed : Error< + "multiversioning attributes cannot be combined">; + def err_cpu_dispatch_mismatch : Error< + "'cpu_dispatch' function redeclared with different CPUs">; + def err_cpu_specific_multiple_defs : Error< + "multiple 'cpu_specific' functions cannot specify the same CPU: %0">; + def warn_multiversion_duplicate_entries : Warning< + "CPU list contains duplicate entries; attribute ignored">, + InGroup; + def warn_dispatch_body_ignored : Warning< + "body of cpu_dispatch function will be ignored">, + InGroup; + + // three-way comparison operator diagnostics + def err_implied_comparison_category_type_not_found : Error< + "cannot %select{use builtin operator '<=>'|default 'operator<=>'}1 " + "because type '%0' was not found; include ">; + def err_spaceship_argument_narrowing : Error< + "argument to 'operator<=>' " + "%select{cannot be narrowed from type %1 to %2|" + "evaluates to %1, which cannot be narrowed to type %2}0">; + def err_std_compare_type_not_supported : Error< + "standard library implementation of %0 is not supported; " + "%select{member '%2' does not have expected form|" + "member '%2' is missing|" + "the type is not trivially copyable|" + "the type does not have the expected form}1">; + def note_rewriting_operator_as_spaceship : Note< + "while rewriting comparison as call to 'operator<=>' declared here">; + def err_three_way_vector_comparison : Error< + "three-way comparison between vectors is not supported">; + + // Memory Tagging Extensions (MTE) diagnostics + def err_memtag_arg_null_or_pointer : Error< + "%0 argument of MTE builtin function must be a null or a pointer (%1 invalid)">; + def err_memtag_any2arg_pointer : Error< + "at least one argument of MTE builtin function must be a pointer (%0, %1 invalid)">; + def err_memtag_arg_must_be_pointer : Error< + "%0 argument of MTE builtin function must be a pointer (%1 invalid)">; + def err_memtag_arg_must_be_integer : Error< + "%0 argument of MTE builtin function must be an integer type (%1 invalid)">; + + def warn_dereference_of_noderef_type : Warning< + "dereferencing %0; was declared with a 'noderef' type">, InGroup; + def warn_dereference_of_noderef_type_no_decl : Warning< + "dereferencing expression marked as 'noderef'">, InGroup; + def warn_noderef_on_non_pointer_or_array : Warning< + "'noderef' can only be used on an array or pointer type">, InGroup; + def warn_noderef_to_dereferenceable_pointer : Warning< + "casting to dereferenceable pointer removes 'noderef' attribute">, InGroup; + + def err_builtin_launder_invalid_arg : Error< + "%select{non-pointer|function pointer|void pointer}0 argument to " + "'__builtin_launder' is not allowed">; + + def err_builtin_matrix_disabled: Error< + "matrix types extension is disabled. Pass -fenable-matrix to enable it">; + def err_matrix_index_not_integer: Error< + "matrix %select{row|column}0 index is not an integer">; + def err_matrix_index_outside_range: Error< + "matrix %select{row|column}0 index is outside the allowed range [0, %1)">; + def err_matrix_incomplete_index: Error< + "single subscript expressions are not allowed for matrix values">; + def err_matrix_separate_incomplete_index: Error< + "matrix row and column subscripts cannot be separated by any expression">; + def err_matrix_subscript_comma: Error< + "comma expressions are not allowed as indices in matrix subscript expressions">; + def err_builtin_matrix_arg: Error<"1st argument must be a matrix">; + def err_builtin_matrix_scalar_unsigned_arg: Error< + "%0 argument must be a constant unsigned integer expression">; + def err_builtin_matrix_pointer_arg: Error< + "%ordinal0 argument must be a pointer to a valid matrix element type">; + def err_builtin_matrix_pointer_arg_mismatch: Error< + "the pointee of the 2nd argument must match the element type of the 1st argument (%0 != %1)">; + def err_builtin_matrix_store_to_const: Error< + "cannot store matrix to read-only pointer">; + def err_builtin_matrix_stride_too_small: Error< + "stride must be greater or equal to the number of rows">; + def err_builtin_matrix_invalid_dimension: Error< + "%0 dimension is outside the allowed range [1, %1]">; + + def warn_mismatched_import : Warning< + "import %select{module|name}0 (%1) does not match the import %select{module|name}0 (%2) of the " + "previous declaration">, + InGroup; + def warn_import_on_definition : Warning< + "import %select{module|name}0 cannot be applied to a function with a definition">, + InGroup; + + def err_preserve_field_info_not_field : Error< + "__builtin_preserve_field_info argument %0 not a field access">; + def err_preserve_field_info_not_const: Error< + "__builtin_preserve_field_info argument %0 not a constant">; + def err_btf_type_id_not_const: Error< + "__builtin_btf_type_id argument %0 not a constant">; + def err_preserve_type_info_invalid : Error< + "__builtin_preserve_type_info argument %0 invalid">; + def err_preserve_type_info_not_const: Error< + "__builtin_preserve_type_info argument %0 not a constant">; + def err_preserve_enum_value_invalid : Error< + "__builtin_preserve_enum_value argument %0 invalid">; + def err_preserve_enum_value_not_const: Error< + "__builtin_preserve_enum_value argument %0 not a constant">; + + def err_bit_cast_non_trivially_copyable : Error< + "__builtin_bit_cast %select{source|destination}0 type must be trivially copyable">; + def err_bit_cast_type_size_mismatch : Error< + "__builtin_bit_cast source size does not equal destination size (%0 vs %1)">; + + // SYCL-specific diagnostics + def warn_sycl_kernel_num_of_template_params : Warning< + "'sycl_kernel' attribute only applies to a function template with at least" + " two template parameters">, InGroup; + def warn_sycl_kernel_invalid_template_param_type : Warning< + "template parameter of a function template with the 'sycl_kernel' attribute" + " cannot be a non-type template parameter">, InGroup; + def warn_sycl_kernel_num_of_function_params : Warning< + "function template with 'sycl_kernel' attribute must have a single parameter">, + InGroup; + def warn_sycl_kernel_return_type : Warning< + "function template with 'sycl_kernel' attribute must have a 'void' return type">, + InGroup; + + def err_ext_int_bad_size : Error<"%select{signed|unsigned}0 _ExtInt must " + "have a bit size of at least %select{2|1}0">; + def err_ext_int_max_size : Error<"%select{signed|unsigned}0 _ExtInt of bit " + "sizes greater than %1 not supported">; + + // errors of expect.with.probability + def err_probability_not_constant_float : Error< + "probability argument to __builtin_expect_with_probability must be constant " + "floating-point expression">; + def err_probability_out_of_range : Error< + "probability argument to __builtin_expect_with_probability is outside the " + "range [0.0, 1.0]">; + + // TCB warnings + def err_tcb_conflicting_attributes : Error< + "attributes '%0(\"%2\")' and '%1(\"%2\")' are mutually exclusive">; + def warn_tcb_enforcement_violation : Warning< + "calling %0 is a violation of trusted computing base '%1'">, + InGroup>; + + // RISC-V builtin required extension warning + def err_riscv_builtin_requires_extension : Error< + "builtin requires '%0' extension support to be enabled">; + def err_riscv_builtin_invalid_lmul : Error< + "LMUL argument must be in the range [0,3] or [5,7]">; + } // end of sema component. +diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp +index c3c653f6889e..0a414afc1616 100644 +--- a/clang/lib/Sema/SemaChecking.cpp ++++ b/clang/lib/Sema/SemaChecking.cpp +@@ -3221,13643 +3221,13655 @@ bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { + /// advancing the pointer over the consumed characters. The decoded type is + /// returned. If the decoded type represents a constant integer with a + /// constraint on its value then Mask is set to that value. The type descriptors + /// used in Str are specific to PPC MMA builtins and are documented in the file + /// defining the PPC builtins. + static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, + unsigned &Mask) { + bool RequireICE = false; + ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; + switch (*Str++) { + case 'V': + return Context.getVectorType(Context.UnsignedCharTy, 16, + VectorType::VectorKind::AltiVecVector); + case 'i': { + char *End; + unsigned size = strtoul(Str, &End, 10); + assert(End != Str && "Missing constant parameter constraint"); + Str = End; + Mask = size; + return Context.IntTy; + } + case 'W': { + char *End; + unsigned size = strtoul(Str, &End, 10); + assert(End != Str && "Missing PowerPC MMA type size"); + Str = End; + QualType Type; + switch (size) { + #define PPC_VECTOR_TYPE(typeName, Id, size) \ + case size: Type = Context.Id##Ty; break; + #include "clang/Basic/PPCTypes.def" + default: llvm_unreachable("Invalid PowerPC MMA vector type"); + } + bool CheckVectorArgs = false; + while (!CheckVectorArgs) { + switch (*Str++) { + case '*': + Type = Context.getPointerType(Type); + break; + case 'C': + Type = Type.withConst(); + break; + default: + CheckVectorArgs = true; + --Str; + break; + } + } + return Type; + } + default: + return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); + } + } + + static bool isPPC_64Builtin(unsigned BuiltinID) { + // These builtins only work on PPC 64bit targets. + switch (BuiltinID) { + case PPC::BI__builtin_divde: + case PPC::BI__builtin_divdeu: + case PPC::BI__builtin_bpermd: + case PPC::BI__builtin_ppc_ldarx: + case PPC::BI__builtin_ppc_stdcx: + case PPC::BI__builtin_ppc_tdw: + case PPC::BI__builtin_ppc_trapd: + case PPC::BI__builtin_ppc_cmpeqb: + case PPC::BI__builtin_ppc_setb: + case PPC::BI__builtin_ppc_mulhd: + case PPC::BI__builtin_ppc_mulhdu: + case PPC::BI__builtin_ppc_maddhd: + case PPC::BI__builtin_ppc_maddhdu: + case PPC::BI__builtin_ppc_maddld: + case PPC::BI__builtin_ppc_load8r: + case PPC::BI__builtin_ppc_store8r: + case PPC::BI__builtin_ppc_insert_exp: + case PPC::BI__builtin_ppc_extract_sig: + case PPC::BI__builtin_ppc_addex: + case PPC::BI__builtin_darn: + case PPC::BI__builtin_darn_raw: + return true; + } + return false; + } + + static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, + StringRef FeatureToCheck, unsigned DiagID, + StringRef DiagArg = "") { + if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) + return false; + + if (DiagArg.empty()) + S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); + else + S.Diag(TheCall->getBeginLoc(), DiagID) + << DiagArg << TheCall->getSourceRange(); + + return true; + } + + /// Returns true if the argument consists of one contiguous run of 1s with any + /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so + /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, + /// since all 1s are not contiguous. + bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { + llvm::APSInt Result; + // We can't check the value of a dependent argument. + Expr *Arg = TheCall->getArg(ArgNum); + if (Arg->isTypeDependent() || Arg->isValueDependent()) + return false; + + // Check constant-ness first. + if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) + return true; + + // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. + if (Result.isShiftedMask() || (~Result).isShiftedMask()) + return false; + + return Diag(TheCall->getBeginLoc(), + diag::err_argument_not_contiguous_bit_field) + << ArgNum << Arg->getSourceRange(); + } + + bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, + CallExpr *TheCall) { + unsigned i = 0, l = 0, u = 0; + bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; + llvm::APSInt Result; + + if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) + return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) + << TheCall->getSourceRange(); + + switch (BuiltinID) { + default: return false; + case PPC::BI__builtin_altivec_crypto_vshasigmaw: + case PPC::BI__builtin_altivec_crypto_vshasigmad: + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || + SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); + case PPC::BI__builtin_altivec_dss: + return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); + case PPC::BI__builtin_tbegin: + case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; + case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; + case PPC::BI__builtin_tabortwc: + case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; + case PPC::BI__builtin_tabortwci: + case PPC::BI__builtin_tabortdci: + return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || + SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); + case PPC::BI__builtin_altivec_dst: + case PPC::BI__builtin_altivec_dstt: + case PPC::BI__builtin_altivec_dstst: + case PPC::BI__builtin_altivec_dststt: + return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); + case PPC::BI__builtin_vsx_xxpermdi: + case PPC::BI__builtin_vsx_xxsldwi: + return SemaBuiltinVSX(TheCall); + case PPC::BI__builtin_divwe: + case PPC::BI__builtin_divweu: + case PPC::BI__builtin_divde: + case PPC::BI__builtin_divdeu: + return SemaFeatureCheck(*this, TheCall, "extdiv", + diag::err_ppc_builtin_only_on_arch, "7"); + case PPC::BI__builtin_bpermd: + return SemaFeatureCheck(*this, TheCall, "bpermd", + diag::err_ppc_builtin_only_on_arch, "7"); + case PPC::BI__builtin_unpack_vector_int128: + return SemaFeatureCheck(*this, TheCall, "vsx", + diag::err_ppc_builtin_only_on_arch, "7") || + SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); + case PPC::BI__builtin_pack_vector_int128: + return SemaFeatureCheck(*this, TheCall, "vsx", + diag::err_ppc_builtin_only_on_arch, "7"); + case PPC::BI__builtin_altivec_vgnb: + return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); + case PPC::BI__builtin_altivec_vec_replace_elt: + case PPC::BI__builtin_altivec_vec_replace_unaligned: { + QualType VecTy = TheCall->getArg(0)->getType(); + QualType EltTy = TheCall->getArg(1)->getType(); + unsigned Width = Context.getIntWidth(EltTy); + return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || + !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); + } + case PPC::BI__builtin_vsx_xxeval: + return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); + case PPC::BI__builtin_altivec_vsldbi: + return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); + case PPC::BI__builtin_altivec_vsrdbi: + return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); + case PPC::BI__builtin_vsx_xxpermx: + return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); + case PPC::BI__builtin_ppc_tw: + case PPC::BI__builtin_ppc_tdw: + return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); + case PPC::BI__builtin_ppc_cmpeqb: + case PPC::BI__builtin_ppc_setb: + case PPC::BI__builtin_ppc_maddhd: + case PPC::BI__builtin_ppc_maddhdu: + case PPC::BI__builtin_ppc_maddld: + return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", + diag::err_ppc_builtin_only_on_arch, "9"); + case PPC::BI__builtin_ppc_cmprb: + return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", + diag::err_ppc_builtin_only_on_arch, "9") || + SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); + // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must + // be a constant that represents a contiguous bit field. + case PPC::BI__builtin_ppc_rlwnm: + return SemaBuiltinConstantArg(TheCall, 1, Result) || + SemaValueIsRunOfOnes(TheCall, 2); + case PPC::BI__builtin_ppc_rlwimi: + case PPC::BI__builtin_ppc_rldimi: + return SemaBuiltinConstantArg(TheCall, 2, Result) || + SemaValueIsRunOfOnes(TheCall, 3); + case PPC::BI__builtin_ppc_extract_exp: + case PPC::BI__builtin_ppc_extract_sig: + case PPC::BI__builtin_ppc_insert_exp: + return SemaFeatureCheck(*this, TheCall, "power9-vector", + diag::err_ppc_builtin_only_on_arch, "9"); + case PPC::BI__builtin_ppc_addex: { + if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", + diag::err_ppc_builtin_only_on_arch, "9") || + SemaBuiltinConstantArgRange(TheCall, 2, 0, 3)) + return true; + // Output warning for reserved values 1 to 3. + int ArgValue = + TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue(); + if (ArgValue != 0) + Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour) + << ArgValue; + return false; + } + case PPC::BI__builtin_ppc_mtfsb0: + case PPC::BI__builtin_ppc_mtfsb1: + return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); + case PPC::BI__builtin_ppc_mtfsf: + return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); + case PPC::BI__builtin_ppc_mtfsfi: + return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || + SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); + case PPC::BI__builtin_ppc_alignx: + return SemaBuiltinConstantArgPower2(TheCall, 0); + case PPC::BI__builtin_ppc_rdlam: + return SemaValueIsRunOfOnes(TheCall, 2); + case PPC::BI__builtin_ppc_icbt: + case PPC::BI__builtin_ppc_sthcx: + case PPC::BI__builtin_ppc_stbcx: + case PPC::BI__builtin_ppc_lharx: + case PPC::BI__builtin_ppc_lbarx: + return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", + diag::err_ppc_builtin_only_on_arch, "8"); + case PPC::BI__builtin_vsx_ldrmb: + case PPC::BI__builtin_vsx_strmb: + return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", + diag::err_ppc_builtin_only_on_arch, "8") || + SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); + case PPC::BI__builtin_altivec_vcntmbb: + case PPC::BI__builtin_altivec_vcntmbh: + case PPC::BI__builtin_altivec_vcntmbw: + case PPC::BI__builtin_altivec_vcntmbd: + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); + case PPC::BI__builtin_darn: + case PPC::BI__builtin_darn_raw: + case PPC::BI__builtin_darn_32: + return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", + diag::err_ppc_builtin_only_on_arch, "9"); + case PPC::BI__builtin_vsx_xxgenpcvbm: + case PPC::BI__builtin_vsx_xxgenpcvhm: + case PPC::BI__builtin_vsx_xxgenpcvwm: + case PPC::BI__builtin_vsx_xxgenpcvdm: + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); + #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ + case PPC::BI__builtin_##Name: \ + return SemaBuiltinPPCMMACall(TheCall, Types); + #include "clang/Basic/BuiltinsPPC.def" + } + return SemaBuiltinConstantArgRange(TheCall, i, l, u); + } + + // Check if the given type is a non-pointer PPC MMA type. This function is used + // in Sema to prevent invalid uses of restricted PPC MMA types. + bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { + if (Type->isPointerType() || Type->isArrayType()) + return false; + + QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); + #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty + if (false + #include "clang/Basic/PPCTypes.def" + ) { + Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); + return true; + } + return false; + } + + bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, + CallExpr *TheCall) { + // position of memory order and scope arguments in the builtin + unsigned OrderIndex, ScopeIndex; + switch (BuiltinID) { + case AMDGPU::BI__builtin_amdgcn_atomic_inc32: + case AMDGPU::BI__builtin_amdgcn_atomic_inc64: + case AMDGPU::BI__builtin_amdgcn_atomic_dec32: + case AMDGPU::BI__builtin_amdgcn_atomic_dec64: + OrderIndex = 2; + ScopeIndex = 3; + break; + case AMDGPU::BI__builtin_amdgcn_fence: + OrderIndex = 0; + ScopeIndex = 1; + break; + default: + return false; + } + + ExprResult Arg = TheCall->getArg(OrderIndex); + auto ArgExpr = Arg.get(); + Expr::EvalResult ArgResult; + + if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) + return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) + << ArgExpr->getType(); + auto Ord = ArgResult.Val.getInt().getZExtValue(); + + // Check validity of memory ordering as per C11 / C++11's memody model. + // Only fence needs check. Atomic dec/inc allow all memory orders. + if (!llvm::isValidAtomicOrderingCABI(Ord)) + return Diag(ArgExpr->getBeginLoc(), + diag::warn_atomic_op_has_invalid_memory_order) + << ArgExpr->getSourceRange(); + switch (static_cast(Ord)) { + case llvm::AtomicOrderingCABI::relaxed: + case llvm::AtomicOrderingCABI::consume: + if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) + return Diag(ArgExpr->getBeginLoc(), + diag::warn_atomic_op_has_invalid_memory_order) + << ArgExpr->getSourceRange(); + break; + case llvm::AtomicOrderingCABI::acquire: + case llvm::AtomicOrderingCABI::release: + case llvm::AtomicOrderingCABI::acq_rel: + case llvm::AtomicOrderingCABI::seq_cst: + break; + } + + Arg = TheCall->getArg(ScopeIndex); + ArgExpr = Arg.get(); + Expr::EvalResult ArgResult1; + // Check that sync scope is a constant literal + if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) + return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) + << ArgExpr->getType(); + + return false; + } + + bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { + llvm::APSInt Result; + + // We can't check the value of a dependent argument. + Expr *Arg = TheCall->getArg(ArgNum); + if (Arg->isTypeDependent() || Arg->isValueDependent()) + return false; + + // Check constant-ness first. + if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) + return true; + + int64_t Val = Result.getSExtValue(); + if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) + return false; + + return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) + << Arg->getSourceRange(); + } + + bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, + unsigned BuiltinID, + CallExpr *TheCall) { + // CodeGenFunction can also detect this, but this gives a better error + // message. + bool FeatureMissing = false; + SmallVector ReqFeatures; + StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); + Features.split(ReqFeatures, ','); + + // Check if each required feature is included + for (StringRef F : ReqFeatures) { + if (TI.hasFeature(F)) + continue; + + // If the feature is 64bit, alter the string so it will print better in + // the diagnostic. + if (F == "64bit") + F = "RV64"; + + // Convert features like "zbr" and "experimental-zbr" to "Zbr". + F.consume_front("experimental-"); + std::string FeatureStr = F.str(); + FeatureStr[0] = std::toupper(FeatureStr[0]); + + // Error message + FeatureMissing = true; + Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) + << TheCall->getSourceRange() << StringRef(FeatureStr); + } + + if (FeatureMissing) + return true; + + switch (BuiltinID) { + case RISCV::BI__builtin_rvv_vsetvli: + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || + CheckRISCVLMUL(TheCall, 2); + case RISCV::BI__builtin_rvv_vsetvlimax: + return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || + CheckRISCVLMUL(TheCall, 1); + case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1: + case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1: + case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1: + case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1: + case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1: + case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1: + case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1: + case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1: + case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1: + case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1: + case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2: + case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2: + case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2: + case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2: + case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2: + case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2: + case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2: + case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2: + case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2: + case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2: + case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4: + case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4: + case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4: + case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4: + case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4: + case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4: + case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4: + case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4: + case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4: + case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4: + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); + case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1: + case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1: + case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1: + case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1: + case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1: + case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1: + case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1: + case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1: + case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1: + case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1: + case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2: + case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2: + case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2: + case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2: + case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2: + case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2: + case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2: + case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2: + case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2: + case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2: + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); + case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1: + case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1: + case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1: + case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1: + case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1: + case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1: + case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1: + case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1: + case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1: + case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1: + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); + case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2: + case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2: + case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2: + case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2: + case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2: + case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2: + case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2: + case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2: + case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2: + case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2: + case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4: + case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4: + case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4: + case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4: + case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4: + case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4: + case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4: + case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4: + case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4: + case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4: + case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8: + case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8: + case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8: + case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8: + case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8: + case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8: + case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8: + case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8: + case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8: + case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8: + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); + case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4: + case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4: + case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4: + case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4: + case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4: + case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4: + case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4: + case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4: + case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4: + case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4: + case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8: + case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8: + case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8: + case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8: + case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8: + case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8: + case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8: + case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8: + case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8: + case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8: + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); + case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8: + case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8: + case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8: + case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8: + case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8: + case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8: + case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8: + case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8: + case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8: + case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8: + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); + } + + return false; + } + + bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, + CallExpr *TheCall) { + if (BuiltinID == SystemZ::BI__builtin_tabort) { + Expr *Arg = TheCall->getArg(0); + if (Optional AbortCode = Arg->getIntegerConstantExpr(Context)) + if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) + return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) + << Arg->getSourceRange(); + } + + // For intrinsics which take an immediate value as part of the instruction, + // range check them here. + unsigned i = 0, l = 0, u = 0; + switch (BuiltinID) { + default: return false; + case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; + case SystemZ::BI__builtin_s390_verimb: + case SystemZ::BI__builtin_s390_verimh: + case SystemZ::BI__builtin_s390_verimf: + case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; + case SystemZ::BI__builtin_s390_vfaeb: + case SystemZ::BI__builtin_s390_vfaeh: + case SystemZ::BI__builtin_s390_vfaef: + case SystemZ::BI__builtin_s390_vfaebs: + case SystemZ::BI__builtin_s390_vfaehs: + case SystemZ::BI__builtin_s390_vfaefs: + case SystemZ::BI__builtin_s390_vfaezb: + case SystemZ::BI__builtin_s390_vfaezh: + case SystemZ::BI__builtin_s390_vfaezf: + case SystemZ::BI__builtin_s390_vfaezbs: + case SystemZ::BI__builtin_s390_vfaezhs: + case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; + case SystemZ::BI__builtin_s390_vfisb: + case SystemZ::BI__builtin_s390_vfidb: + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || + SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); + case SystemZ::BI__builtin_s390_vftcisb: + case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; + case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; + case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; + case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; + case SystemZ::BI__builtin_s390_vstrcb: + case SystemZ::BI__builtin_s390_vstrch: + case SystemZ::BI__builtin_s390_vstrcf: + case SystemZ::BI__builtin_s390_vstrczb: + case SystemZ::BI__builtin_s390_vstrczh: + case SystemZ::BI__builtin_s390_vstrczf: + case SystemZ::BI__builtin_s390_vstrcbs: + case SystemZ::BI__builtin_s390_vstrchs: + case SystemZ::BI__builtin_s390_vstrcfs: + case SystemZ::BI__builtin_s390_vstrczbs: + case SystemZ::BI__builtin_s390_vstrczhs: + case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; + case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; + case SystemZ::BI__builtin_s390_vfminsb: + case SystemZ::BI__builtin_s390_vfmaxsb: + case SystemZ::BI__builtin_s390_vfmindb: + case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; + case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; + case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; + case SystemZ::BI__builtin_s390_vclfnhs: + case SystemZ::BI__builtin_s390_vclfnls: + case SystemZ::BI__builtin_s390_vcfn: + case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; + case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; + } + return SemaBuiltinConstantArgRange(TheCall, i, l, u); + } + + /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). + /// This checks that the target supports __builtin_cpu_supports and + /// that the string argument is constant and valid. + static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, + CallExpr *TheCall) { + Expr *Arg = TheCall->getArg(0); + + // Check if the argument is a string literal. + if (!isa(Arg->IgnoreParenImpCasts())) + return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) + << Arg->getSourceRange(); + + // Check the contents of the string. + StringRef Feature = + cast(Arg->IgnoreParenImpCasts())->getString(); + if (!TI.validateCpuSupports(Feature)) + return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) + << Arg->getSourceRange(); + return false; + } + + /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). + /// This checks that the target supports __builtin_cpu_is and + /// that the string argument is constant and valid. + static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { + Expr *Arg = TheCall->getArg(0); + + // Check if the argument is a string literal. + if (!isa(Arg->IgnoreParenImpCasts())) + return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) + << Arg->getSourceRange(); + + // Check the contents of the string. + StringRef Feature = + cast(Arg->IgnoreParenImpCasts())->getString(); + if (!TI.validateCpuIs(Feature)) + return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) + << Arg->getSourceRange(); + return false; + } + + // Check if the rounding mode is legal. + bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { + // Indicates if this instruction has rounding control or just SAE. + bool HasRC = false; + + unsigned ArgNum = 0; + switch (BuiltinID) { + default: + return false; + case X86::BI__builtin_ia32_vcvttsd2si32: + case X86::BI__builtin_ia32_vcvttsd2si64: + case X86::BI__builtin_ia32_vcvttsd2usi32: + case X86::BI__builtin_ia32_vcvttsd2usi64: + case X86::BI__builtin_ia32_vcvttss2si32: + case X86::BI__builtin_ia32_vcvttss2si64: + case X86::BI__builtin_ia32_vcvttss2usi32: + case X86::BI__builtin_ia32_vcvttss2usi64: + case X86::BI__builtin_ia32_vcvttsh2si32: + case X86::BI__builtin_ia32_vcvttsh2si64: + case X86::BI__builtin_ia32_vcvttsh2usi32: + case X86::BI__builtin_ia32_vcvttsh2usi64: + ArgNum = 1; + break; + case X86::BI__builtin_ia32_maxpd512: + case X86::BI__builtin_ia32_maxps512: + case X86::BI__builtin_ia32_minpd512: + case X86::BI__builtin_ia32_minps512: + case X86::BI__builtin_ia32_maxph512: + case X86::BI__builtin_ia32_minph512: + ArgNum = 2; + break; + case X86::BI__builtin_ia32_vcvtph2pd512_mask: + case X86::BI__builtin_ia32_vcvtph2psx512_mask: + case X86::BI__builtin_ia32_cvtps2pd512_mask: + case X86::BI__builtin_ia32_cvttpd2dq512_mask: + case X86::BI__builtin_ia32_cvttpd2qq512_mask: + case X86::BI__builtin_ia32_cvttpd2udq512_mask: + case X86::BI__builtin_ia32_cvttpd2uqq512_mask: + case X86::BI__builtin_ia32_cvttps2dq512_mask: + case X86::BI__builtin_ia32_cvttps2qq512_mask: + case X86::BI__builtin_ia32_cvttps2udq512_mask: + case X86::BI__builtin_ia32_cvttps2uqq512_mask: + case X86::BI__builtin_ia32_vcvttph2w512_mask: + case X86::BI__builtin_ia32_vcvttph2uw512_mask: + case X86::BI__builtin_ia32_vcvttph2dq512_mask: + case X86::BI__builtin_ia32_vcvttph2udq512_mask: + case X86::BI__builtin_ia32_vcvttph2qq512_mask: + case X86::BI__builtin_ia32_vcvttph2uqq512_mask: + case X86::BI__builtin_ia32_exp2pd_mask: + case X86::BI__builtin_ia32_exp2ps_mask: + case X86::BI__builtin_ia32_getexppd512_mask: + case X86::BI__builtin_ia32_getexpps512_mask: + case X86::BI__builtin_ia32_getexpph512_mask: + case X86::BI__builtin_ia32_rcp28pd_mask: + case X86::BI__builtin_ia32_rcp28ps_mask: + case X86::BI__builtin_ia32_rsqrt28pd_mask: + case X86::BI__builtin_ia32_rsqrt28ps_mask: + case X86::BI__builtin_ia32_vcomisd: + case X86::BI__builtin_ia32_vcomiss: + case X86::BI__builtin_ia32_vcomish: + case X86::BI__builtin_ia32_vcvtph2ps512_mask: + ArgNum = 3; + break; + case X86::BI__builtin_ia32_cmppd512_mask: + case X86::BI__builtin_ia32_cmpps512_mask: + case X86::BI__builtin_ia32_cmpsd_mask: + case X86::BI__builtin_ia32_cmpss_mask: + case X86::BI__builtin_ia32_cmpsh_mask: + case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: + case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: + case X86::BI__builtin_ia32_cvtss2sd_round_mask: + case X86::BI__builtin_ia32_getexpsd128_round_mask: + case X86::BI__builtin_ia32_getexpss128_round_mask: + case X86::BI__builtin_ia32_getexpsh128_round_mask: + case X86::BI__builtin_ia32_getmantpd512_mask: + case X86::BI__builtin_ia32_getmantps512_mask: + case X86::BI__builtin_ia32_getmantph512_mask: + case X86::BI__builtin_ia32_maxsd_round_mask: + case X86::BI__builtin_ia32_maxss_round_mask: + case X86::BI__builtin_ia32_maxsh_round_mask: + case X86::BI__builtin_ia32_minsd_round_mask: + case X86::BI__builtin_ia32_minss_round_mask: + case X86::BI__builtin_ia32_minsh_round_mask: + case X86::BI__builtin_ia32_rcp28sd_round_mask: + case X86::BI__builtin_ia32_rcp28ss_round_mask: + case X86::BI__builtin_ia32_reducepd512_mask: + case X86::BI__builtin_ia32_reduceps512_mask: + case X86::BI__builtin_ia32_reduceph512_mask: + case X86::BI__builtin_ia32_rndscalepd_mask: + case X86::BI__builtin_ia32_rndscaleps_mask: + case X86::BI__builtin_ia32_rndscaleph_mask: + case X86::BI__builtin_ia32_rsqrt28sd_round_mask: + case X86::BI__builtin_ia32_rsqrt28ss_round_mask: + ArgNum = 4; + break; + case X86::BI__builtin_ia32_fixupimmpd512_mask: + case X86::BI__builtin_ia32_fixupimmpd512_maskz: + case X86::BI__builtin_ia32_fixupimmps512_mask: + case X86::BI__builtin_ia32_fixupimmps512_maskz: + case X86::BI__builtin_ia32_fixupimmsd_mask: + case X86::BI__builtin_ia32_fixupimmsd_maskz: + case X86::BI__builtin_ia32_fixupimmss_mask: + case X86::BI__builtin_ia32_fixupimmss_maskz: + case X86::BI__builtin_ia32_getmantsd_round_mask: + case X86::BI__builtin_ia32_getmantss_round_mask: + case X86::BI__builtin_ia32_getmantsh_round_mask: + case X86::BI__builtin_ia32_rangepd512_mask: + case X86::BI__builtin_ia32_rangeps512_mask: + case X86::BI__builtin_ia32_rangesd128_round_mask: + case X86::BI__builtin_ia32_rangess128_round_mask: + case X86::BI__builtin_ia32_reducesd_mask: + case X86::BI__builtin_ia32_reducess_mask: + case X86::BI__builtin_ia32_reducesh_mask: + case X86::BI__builtin_ia32_rndscalesd_round_mask: + case X86::BI__builtin_ia32_rndscaless_round_mask: + case X86::BI__builtin_ia32_rndscalesh_round_mask: + ArgNum = 5; + break; + case X86::BI__builtin_ia32_vcvtsd2si64: + case X86::BI__builtin_ia32_vcvtsd2si32: + case X86::BI__builtin_ia32_vcvtsd2usi32: + case X86::BI__builtin_ia32_vcvtsd2usi64: + case X86::BI__builtin_ia32_vcvtss2si32: + case X86::BI__builtin_ia32_vcvtss2si64: + case X86::BI__builtin_ia32_vcvtss2usi32: + case X86::BI__builtin_ia32_vcvtss2usi64: + case X86::BI__builtin_ia32_vcvtsh2si32: + case X86::BI__builtin_ia32_vcvtsh2si64: + case X86::BI__builtin_ia32_vcvtsh2usi32: + case X86::BI__builtin_ia32_vcvtsh2usi64: + case X86::BI__builtin_ia32_sqrtpd512: + case X86::BI__builtin_ia32_sqrtps512: + case X86::BI__builtin_ia32_sqrtph512: + ArgNum = 1; + HasRC = true; + break; + case X86::BI__builtin_ia32_addph512: + case X86::BI__builtin_ia32_divph512: + case X86::BI__builtin_ia32_mulph512: + case X86::BI__builtin_ia32_subph512: + case X86::BI__builtin_ia32_addpd512: + case X86::BI__builtin_ia32_addps512: + case X86::BI__builtin_ia32_divpd512: + case X86::BI__builtin_ia32_divps512: + case X86::BI__builtin_ia32_mulpd512: + case X86::BI__builtin_ia32_mulps512: + case X86::BI__builtin_ia32_subpd512: + case X86::BI__builtin_ia32_subps512: + case X86::BI__builtin_ia32_cvtsi2sd64: + case X86::BI__builtin_ia32_cvtsi2ss32: + case X86::BI__builtin_ia32_cvtsi2ss64: + case X86::BI__builtin_ia32_cvtusi2sd64: + case X86::BI__builtin_ia32_cvtusi2ss32: + case X86::BI__builtin_ia32_cvtusi2ss64: + case X86::BI__builtin_ia32_vcvtusi2sh: + case X86::BI__builtin_ia32_vcvtusi642sh: + case X86::BI__builtin_ia32_vcvtsi2sh: + case X86::BI__builtin_ia32_vcvtsi642sh: + ArgNum = 2; + HasRC = true; + break; + case X86::BI__builtin_ia32_cvtdq2ps512_mask: + case X86::BI__builtin_ia32_cvtudq2ps512_mask: + case X86::BI__builtin_ia32_vcvtpd2ph512_mask: + case X86::BI__builtin_ia32_vcvtps2phx512_mask: + case X86::BI__builtin_ia32_cvtpd2ps512_mask: + case X86::BI__builtin_ia32_cvtpd2dq512_mask: + case X86::BI__builtin_ia32_cvtpd2qq512_mask: + case X86::BI__builtin_ia32_cvtpd2udq512_mask: + case X86::BI__builtin_ia32_cvtpd2uqq512_mask: + case X86::BI__builtin_ia32_cvtps2dq512_mask: + case X86::BI__builtin_ia32_cvtps2qq512_mask: + case X86::BI__builtin_ia32_cvtps2udq512_mask: + case X86::BI__builtin_ia32_cvtps2uqq512_mask: + case X86::BI__builtin_ia32_cvtqq2pd512_mask: + case X86::BI__builtin_ia32_cvtqq2ps512_mask: + case X86::BI__builtin_ia32_cvtuqq2pd512_mask: + case X86::BI__builtin_ia32_cvtuqq2ps512_mask: + case X86::BI__builtin_ia32_vcvtdq2ph512_mask: + case X86::BI__builtin_ia32_vcvtudq2ph512_mask: + case X86::BI__builtin_ia32_vcvtw2ph512_mask: + case X86::BI__builtin_ia32_vcvtuw2ph512_mask: + case X86::BI__builtin_ia32_vcvtph2w512_mask: + case X86::BI__builtin_ia32_vcvtph2uw512_mask: + case X86::BI__builtin_ia32_vcvtph2dq512_mask: + case X86::BI__builtin_ia32_vcvtph2udq512_mask: + case X86::BI__builtin_ia32_vcvtph2qq512_mask: + case X86::BI__builtin_ia32_vcvtph2uqq512_mask: + case X86::BI__builtin_ia32_vcvtqq2ph512_mask: + case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: + ArgNum = 3; + HasRC = true; + break; + case X86::BI__builtin_ia32_addsh_round_mask: + case X86::BI__builtin_ia32_addss_round_mask: + case X86::BI__builtin_ia32_addsd_round_mask: + case X86::BI__builtin_ia32_divsh_round_mask: + case X86::BI__builtin_ia32_divss_round_mask: + case X86::BI__builtin_ia32_divsd_round_mask: + case X86::BI__builtin_ia32_mulsh_round_mask: + case X86::BI__builtin_ia32_mulss_round_mask: + case X86::BI__builtin_ia32_mulsd_round_mask: + case X86::BI__builtin_ia32_subsh_round_mask: + case X86::BI__builtin_ia32_subss_round_mask: + case X86::BI__builtin_ia32_subsd_round_mask: + case X86::BI__builtin_ia32_scalefph512_mask: + case X86::BI__builtin_ia32_scalefpd512_mask: + case X86::BI__builtin_ia32_scalefps512_mask: + case X86::BI__builtin_ia32_scalefsd_round_mask: + case X86::BI__builtin_ia32_scalefss_round_mask: + case X86::BI__builtin_ia32_scalefsh_round_mask: + case X86::BI__builtin_ia32_cvtsd2ss_round_mask: + case X86::BI__builtin_ia32_vcvtss2sh_round_mask: + case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: + case X86::BI__builtin_ia32_sqrtsd_round_mask: + case X86::BI__builtin_ia32_sqrtss_round_mask: + case X86::BI__builtin_ia32_sqrtsh_round_mask: + case X86::BI__builtin_ia32_vfmaddsd3_mask: + case X86::BI__builtin_ia32_vfmaddsd3_maskz: + case X86::BI__builtin_ia32_vfmaddsd3_mask3: + case X86::BI__builtin_ia32_vfmaddss3_mask: + case X86::BI__builtin_ia32_vfmaddss3_maskz: + case X86::BI__builtin_ia32_vfmaddss3_mask3: + case X86::BI__builtin_ia32_vfmaddsh3_mask: + case X86::BI__builtin_ia32_vfmaddsh3_maskz: + case X86::BI__builtin_ia32_vfmaddsh3_mask3: + case X86::BI__builtin_ia32_vfmaddpd512_mask: + case X86::BI__builtin_ia32_vfmaddpd512_maskz: + case X86::BI__builtin_ia32_vfmaddpd512_mask3: + case X86::BI__builtin_ia32_vfmsubpd512_mask3: + case X86::BI__builtin_ia32_vfmaddps512_mask: + case X86::BI__builtin_ia32_vfmaddps512_maskz: + case X86::BI__builtin_ia32_vfmaddps512_mask3: + case X86::BI__builtin_ia32_vfmsubps512_mask3: + case X86::BI__builtin_ia32_vfmaddph512_mask: + case X86::BI__builtin_ia32_vfmaddph512_maskz: + case X86::BI__builtin_ia32_vfmaddph512_mask3: + case X86::BI__builtin_ia32_vfmsubph512_mask3: + case X86::BI__builtin_ia32_vfmaddsubpd512_mask: + case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: + case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: + case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: + case X86::BI__builtin_ia32_vfmaddsubps512_mask: + case X86::BI__builtin_ia32_vfmaddsubps512_maskz: + case X86::BI__builtin_ia32_vfmaddsubps512_mask3: + case X86::BI__builtin_ia32_vfmsubaddps512_mask3: + case X86::BI__builtin_ia32_vfmaddsubph512_mask: + case X86::BI__builtin_ia32_vfmaddsubph512_maskz: + case X86::BI__builtin_ia32_vfmaddsubph512_mask3: + case X86::BI__builtin_ia32_vfmsubaddph512_mask3: + case X86::BI__builtin_ia32_vfmaddcsh_mask: + case X86::BI__builtin_ia32_vfmaddcph512_mask: + case X86::BI__builtin_ia32_vfmaddcph512_maskz: + case X86::BI__builtin_ia32_vfcmaddcsh_mask: + case X86::BI__builtin_ia32_vfcmaddcph512_mask: + case X86::BI__builtin_ia32_vfcmaddcph512_maskz: + case X86::BI__builtin_ia32_vfmulcsh_mask: + case X86::BI__builtin_ia32_vfmulcph512_mask: + case X86::BI__builtin_ia32_vfcmulcsh_mask: + case X86::BI__builtin_ia32_vfcmulcph512_mask: + ArgNum = 4; + HasRC = true; + break; + } + + llvm::APSInt Result; + + // We can't check the value of a dependent argument. + Expr *Arg = TheCall->getArg(ArgNum); + if (Arg->isTypeDependent() || Arg->isValueDependent()) + return false; + + // Check constant-ness first. + if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) + return true; + + // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit + // is set. If the intrinsic has rounding control(bits 1:0), make sure its only + // combined with ROUND_NO_EXC. If the intrinsic does not have rounding + // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. + if (Result == 4/*ROUND_CUR_DIRECTION*/ || + Result == 8/*ROUND_NO_EXC*/ || + (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || + (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) + return false; + + return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) + << Arg->getSourceRange(); + } + + // Check if the gather/scatter scale is legal. + bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, + CallExpr *TheCall) { + unsigned ArgNum = 0; + switch (BuiltinID) { + default: + return false; + case X86::BI__builtin_ia32_gatherpfdpd: + case X86::BI__builtin_ia32_gatherpfdps: + case X86::BI__builtin_ia32_gatherpfqpd: + case X86::BI__builtin_ia32_gatherpfqps: + case X86::BI__builtin_ia32_scatterpfdpd: + case X86::BI__builtin_ia32_scatterpfdps: + case X86::BI__builtin_ia32_scatterpfqpd: + case X86::BI__builtin_ia32_scatterpfqps: + ArgNum = 3; + break; + case X86::BI__builtin_ia32_gatherd_pd: + case X86::BI__builtin_ia32_gatherd_pd256: + case X86::BI__builtin_ia32_gatherq_pd: + case X86::BI__builtin_ia32_gatherq_pd256: + case X86::BI__builtin_ia32_gatherd_ps: + case X86::BI__builtin_ia32_gatherd_ps256: + case X86::BI__builtin_ia32_gatherq_ps: + case X86::BI__builtin_ia32_gatherq_ps256: + case X86::BI__builtin_ia32_gatherd_q: + case X86::BI__builtin_ia32_gatherd_q256: + case X86::BI__builtin_ia32_gatherq_q: + case X86::BI__builtin_ia32_gatherq_q256: + case X86::BI__builtin_ia32_gatherd_d: + case X86::BI__builtin_ia32_gatherd_d256: + case X86::BI__builtin_ia32_gatherq_d: + case X86::BI__builtin_ia32_gatherq_d256: + case X86::BI__builtin_ia32_gather3div2df: + case X86::BI__builtin_ia32_gather3div2di: + case X86::BI__builtin_ia32_gather3div4df: + case X86::BI__builtin_ia32_gather3div4di: + case X86::BI__builtin_ia32_gather3div4sf: + case X86::BI__builtin_ia32_gather3div4si: + case X86::BI__builtin_ia32_gather3div8sf: + case X86::BI__builtin_ia32_gather3div8si: + case X86::BI__builtin_ia32_gather3siv2df: + case X86::BI__builtin_ia32_gather3siv2di: + case X86::BI__builtin_ia32_gather3siv4df: + case X86::BI__builtin_ia32_gather3siv4di: + case X86::BI__builtin_ia32_gather3siv4sf: + case X86::BI__builtin_ia32_gather3siv4si: + case X86::BI__builtin_ia32_gather3siv8sf: + case X86::BI__builtin_ia32_gather3siv8si: + case X86::BI__builtin_ia32_gathersiv8df: + case X86::BI__builtin_ia32_gathersiv16sf: + case X86::BI__builtin_ia32_gatherdiv8df: + case X86::BI__builtin_ia32_gatherdiv16sf: + case X86::BI__builtin_ia32_gathersiv8di: + case X86::BI__builtin_ia32_gathersiv16si: + case X86::BI__builtin_ia32_gatherdiv8di: + case X86::BI__builtin_ia32_gatherdiv16si: + case X86::BI__builtin_ia32_scatterdiv2df: + case X86::BI__builtin_ia32_scatterdiv2di: + case X86::BI__builtin_ia32_scatterdiv4df: + case X86::BI__builtin_ia32_scatterdiv4di: + case X86::BI__builtin_ia32_scatterdiv4sf: + case X86::BI__builtin_ia32_scatterdiv4si: + case X86::BI__builtin_ia32_scatterdiv8sf: + case X86::BI__builtin_ia32_scatterdiv8si: + case X86::BI__builtin_ia32_scattersiv2df: + case X86::BI__builtin_ia32_scattersiv2di: + case X86::BI__builtin_ia32_scattersiv4df: + case X86::BI__builtin_ia32_scattersiv4di: + case X86::BI__builtin_ia32_scattersiv4sf: + case X86::BI__builtin_ia32_scattersiv4si: + case X86::BI__builtin_ia32_scattersiv8sf: + case X86::BI__builtin_ia32_scattersiv8si: + case X86::BI__builtin_ia32_scattersiv8df: + case X86::BI__builtin_ia32_scattersiv16sf: + case X86::BI__builtin_ia32_scatterdiv8df: + case X86::BI__builtin_ia32_scatterdiv16sf: + case X86::BI__builtin_ia32_scattersiv8di: + case X86::BI__builtin_ia32_scattersiv16si: + case X86::BI__builtin_ia32_scatterdiv8di: + case X86::BI__builtin_ia32_scatterdiv16si: + ArgNum = 4; + break; + } + + llvm::APSInt Result; + + // We can't check the value of a dependent argument. + Expr *Arg = TheCall->getArg(ArgNum); + if (Arg->isTypeDependent() || Arg->isValueDependent()) + return false; + + // Check constant-ness first. + if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) + return true; + + if (Result == 1 || Result == 2 || Result == 4 || Result == 8) + return false; + + return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) + << Arg->getSourceRange(); + } + + enum { TileRegLow = 0, TileRegHigh = 7 }; + + bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, + ArrayRef ArgNums) { + for (int ArgNum : ArgNums) { + if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) + return true; + } + return false; + } + + bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, + ArrayRef ArgNums) { + // Because the max number of tile register is TileRegHigh + 1, so here we use + // each bit to represent the usage of them in bitset. + std::bitset ArgValues; + for (int ArgNum : ArgNums) { + Expr *Arg = TheCall->getArg(ArgNum); + if (Arg->isTypeDependent() || Arg->isValueDependent()) + continue; + + llvm::APSInt Result; + if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) + return true; + int ArgExtValue = Result.getExtValue(); + assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && + "Incorrect tile register num."); + if (ArgValues.test(ArgExtValue)) + return Diag(TheCall->getBeginLoc(), + diag::err_x86_builtin_tile_arg_duplicate) + << TheCall->getArg(ArgNum)->getSourceRange(); + ArgValues.set(ArgExtValue); + } + return false; + } + + bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, + ArrayRef ArgNums) { + return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || + CheckX86BuiltinTileDuplicate(TheCall, ArgNums); + } + + bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { + switch (BuiltinID) { + default: + return false; + case X86::BI__builtin_ia32_tileloadd64: + case X86::BI__builtin_ia32_tileloaddt164: + case X86::BI__builtin_ia32_tilestored64: + case X86::BI__builtin_ia32_tilezero: + return CheckX86BuiltinTileArgumentsRange(TheCall, 0); + case X86::BI__builtin_ia32_tdpbssd: + case X86::BI__builtin_ia32_tdpbsud: + case X86::BI__builtin_ia32_tdpbusd: + case X86::BI__builtin_ia32_tdpbuud: + case X86::BI__builtin_ia32_tdpbf16ps: + return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); + } + } + static bool isX86_32Builtin(unsigned BuiltinID) { + // These builtins only work on x86-32 targets. + switch (BuiltinID) { + case X86::BI__builtin_ia32_readeflags_u32: + case X86::BI__builtin_ia32_writeeflags_u32: + return true; + } + + return false; + } + + bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, + CallExpr *TheCall) { + if (BuiltinID == X86::BI__builtin_cpu_supports) + return SemaBuiltinCpuSupports(*this, TI, TheCall); + + if (BuiltinID == X86::BI__builtin_cpu_is) + return SemaBuiltinCpuIs(*this, TI, TheCall); + + // Check for 32-bit only builtins on a 64-bit target. + const llvm::Triple &TT = TI.getTriple(); + if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) + return Diag(TheCall->getCallee()->getBeginLoc(), + diag::err_32_bit_builtin_64_bit_tgt); + + // If the intrinsic has rounding or SAE make sure its valid. + if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) + return true; + + // If the intrinsic has a gather/scatter scale immediate make sure its valid. + if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) + return true; + + // If the intrinsic has a tile arguments, make sure they are valid. + if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) + return true; + + // For intrinsics which take an immediate value as part of the instruction, + // range check them here. + int i = 0, l = 0, u = 0; + switch (BuiltinID) { + default: + return false; + case X86::BI__builtin_ia32_vec_ext_v2si: + case X86::BI__builtin_ia32_vec_ext_v2di: + case X86::BI__builtin_ia32_vextractf128_pd256: + case X86::BI__builtin_ia32_vextractf128_ps256: + case X86::BI__builtin_ia32_vextractf128_si256: + case X86::BI__builtin_ia32_extract128i256: + case X86::BI__builtin_ia32_extractf64x4_mask: + case X86::BI__builtin_ia32_extracti64x4_mask: + case X86::BI__builtin_ia32_extractf32x8_mask: + case X86::BI__builtin_ia32_extracti32x8_mask: + case X86::BI__builtin_ia32_extractf64x2_256_mask: + case X86::BI__builtin_ia32_extracti64x2_256_mask: + case X86::BI__builtin_ia32_extractf32x4_256_mask: + case X86::BI__builtin_ia32_extracti32x4_256_mask: + i = 1; l = 0; u = 1; + break; + case X86::BI__builtin_ia32_vec_set_v2di: + case X86::BI__builtin_ia32_vinsertf128_pd256: + case X86::BI__builtin_ia32_vinsertf128_ps256: + case X86::BI__builtin_ia32_vinsertf128_si256: + case X86::BI__builtin_ia32_insert128i256: + case X86::BI__builtin_ia32_insertf32x8: + case X86::BI__builtin_ia32_inserti32x8: + case X86::BI__builtin_ia32_insertf64x4: + case X86::BI__builtin_ia32_inserti64x4: + case X86::BI__builtin_ia32_insertf64x2_256: + case X86::BI__builtin_ia32_inserti64x2_256: + case X86::BI__builtin_ia32_insertf32x4_256: + case X86::BI__builtin_ia32_inserti32x4_256: + i = 2; l = 0; u = 1; + break; + case X86::BI__builtin_ia32_vpermilpd: + case X86::BI__builtin_ia32_vec_ext_v4hi: + case X86::BI__builtin_ia32_vec_ext_v4si: + case X86::BI__builtin_ia32_vec_ext_v4sf: + case X86::BI__builtin_ia32_vec_ext_v4di: + case X86::BI__builtin_ia32_extractf32x4_mask: + case X86::BI__builtin_ia32_extracti32x4_mask: + case X86::BI__builtin_ia32_extractf64x2_512_mask: + case X86::BI__builtin_ia32_extracti64x2_512_mask: + i = 1; l = 0; u = 3; + break; + case X86::BI_mm_prefetch: + case X86::BI__builtin_ia32_vec_ext_v8hi: + case X86::BI__builtin_ia32_vec_ext_v8si: + i = 1; l = 0; u = 7; + break; + case X86::BI__builtin_ia32_sha1rnds4: + case X86::BI__builtin_ia32_blendpd: + case X86::BI__builtin_ia32_shufpd: + case X86::BI__builtin_ia32_vec_set_v4hi: + case X86::BI__builtin_ia32_vec_set_v4si: + case X86::BI__builtin_ia32_vec_set_v4di: + case X86::BI__builtin_ia32_shuf_f32x4_256: + case X86::BI__builtin_ia32_shuf_f64x2_256: + case X86::BI__builtin_ia32_shuf_i32x4_256: + case X86::BI__builtin_ia32_shuf_i64x2_256: + case X86::BI__builtin_ia32_insertf64x2_512: + case X86::BI__builtin_ia32_inserti64x2_512: + case X86::BI__builtin_ia32_insertf32x4: + case X86::BI__builtin_ia32_inserti32x4: + i = 2; l = 0; u = 3; + break; + case X86::BI__builtin_ia32_vpermil2pd: + case X86::BI__builtin_ia32_vpermil2pd256: + case X86::BI__builtin_ia32_vpermil2ps: + case X86::BI__builtin_ia32_vpermil2ps256: + i = 3; l = 0; u = 3; + break; + case X86::BI__builtin_ia32_cmpb128_mask: + case X86::BI__builtin_ia32_cmpw128_mask: + case X86::BI__builtin_ia32_cmpd128_mask: + case X86::BI__builtin_ia32_cmpq128_mask: + case X86::BI__builtin_ia32_cmpb256_mask: + case X86::BI__builtin_ia32_cmpw256_mask: + case X86::BI__builtin_ia32_cmpd256_mask: + case X86::BI__builtin_ia32_cmpq256_mask: + case X86::BI__builtin_ia32_cmpb512_mask: + case X86::BI__builtin_ia32_cmpw512_mask: + case X86::BI__builtin_ia32_cmpd512_mask: + case X86::BI__builtin_ia32_cmpq512_mask: + case X86::BI__builtin_ia32_ucmpb128_mask: + case X86::BI__builtin_ia32_ucmpw128_mask: + case X86::BI__builtin_ia32_ucmpd128_mask: + case X86::BI__builtin_ia32_ucmpq128_mask: + case X86::BI__builtin_ia32_ucmpb256_mask: + case X86::BI__builtin_ia32_ucmpw256_mask: + case X86::BI__builtin_ia32_ucmpd256_mask: + case X86::BI__builtin_ia32_ucmpq256_mask: + case X86::BI__builtin_ia32_ucmpb512_mask: + case X86::BI__builtin_ia32_ucmpw512_mask: + case X86::BI__builtin_ia32_ucmpd512_mask: + case X86::BI__builtin_ia32_ucmpq512_mask: + case X86::BI__builtin_ia32_vpcomub: + case X86::BI__builtin_ia32_vpcomuw: + case X86::BI__builtin_ia32_vpcomud: + case X86::BI__builtin_ia32_vpcomuq: + case X86::BI__builtin_ia32_vpcomb: + case X86::BI__builtin_ia32_vpcomw: + case X86::BI__builtin_ia32_vpcomd: + case X86::BI__builtin_ia32_vpcomq: + case X86::BI__builtin_ia32_vec_set_v8hi: + case X86::BI__builtin_ia32_vec_set_v8si: + i = 2; l = 0; u = 7; + break; + case X86::BI__builtin_ia32_vpermilpd256: + case X86::BI__builtin_ia32_roundps: + case X86::BI__builtin_ia32_roundpd: + case X86::BI__builtin_ia32_roundps256: + case X86::BI__builtin_ia32_roundpd256: + case X86::BI__builtin_ia32_getmantpd128_mask: + case X86::BI__builtin_ia32_getmantpd256_mask: + case X86::BI__builtin_ia32_getmantps128_mask: + case X86::BI__builtin_ia32_getmantps256_mask: + case X86::BI__builtin_ia32_getmantpd512_mask: + case X86::BI__builtin_ia32_getmantps512_mask: + case X86::BI__builtin_ia32_getmantph128_mask: + case X86::BI__builtin_ia32_getmantph256_mask: + case X86::BI__builtin_ia32_getmantph512_mask: + case X86::BI__builtin_ia32_vec_ext_v16qi: + case X86::BI__builtin_ia32_vec_ext_v16hi: + i = 1; l = 0; u = 15; + break; + case X86::BI__builtin_ia32_pblendd128: + case X86::BI__builtin_ia32_blendps: + case X86::BI__builtin_ia32_blendpd256: + case X86::BI__builtin_ia32_shufpd256: + case X86::BI__builtin_ia32_roundss: + case X86::BI__builtin_ia32_roundsd: + case X86::BI__builtin_ia32_rangepd128_mask: + case X86::BI__builtin_ia32_rangepd256_mask: + case X86::BI__builtin_ia32_rangepd512_mask: + case X86::BI__builtin_ia32_rangeps128_mask: + case X86::BI__builtin_ia32_rangeps256_mask: + case X86::BI__builtin_ia32_rangeps512_mask: + case X86::BI__builtin_ia32_getmantsd_round_mask: + case X86::BI__builtin_ia32_getmantss_round_mask: + case X86::BI__builtin_ia32_getmantsh_round_mask: + case X86::BI__builtin_ia32_vec_set_v16qi: + case X86::BI__builtin_ia32_vec_set_v16hi: + i = 2; l = 0; u = 15; + break; + case X86::BI__builtin_ia32_vec_ext_v32qi: + i = 1; l = 0; u = 31; + break; + case X86::BI__builtin_ia32_cmpps: + case X86::BI__builtin_ia32_cmpss: + case X86::BI__builtin_ia32_cmppd: + case X86::BI__builtin_ia32_cmpsd: + case X86::BI__builtin_ia32_cmpps256: + case X86::BI__builtin_ia32_cmppd256: + case X86::BI__builtin_ia32_cmpps128_mask: + case X86::BI__builtin_ia32_cmppd128_mask: + case X86::BI__builtin_ia32_cmpps256_mask: + case X86::BI__builtin_ia32_cmppd256_mask: + case X86::BI__builtin_ia32_cmpps512_mask: + case X86::BI__builtin_ia32_cmppd512_mask: + case X86::BI__builtin_ia32_cmpsd_mask: + case X86::BI__builtin_ia32_cmpss_mask: + case X86::BI__builtin_ia32_vec_set_v32qi: + i = 2; l = 0; u = 31; + break; + case X86::BI__builtin_ia32_permdf256: + case X86::BI__builtin_ia32_permdi256: + case X86::BI__builtin_ia32_permdf512: + case X86::BI__builtin_ia32_permdi512: + case X86::BI__builtin_ia32_vpermilps: + case X86::BI__builtin_ia32_vpermilps256: + case X86::BI__builtin_ia32_vpermilpd512: + case X86::BI__builtin_ia32_vpermilps512: + case X86::BI__builtin_ia32_pshufd: + case X86::BI__builtin_ia32_pshufd256: + case X86::BI__builtin_ia32_pshufd512: + case X86::BI__builtin_ia32_pshufhw: + case X86::BI__builtin_ia32_pshufhw256: + case X86::BI__builtin_ia32_pshufhw512: + case X86::BI__builtin_ia32_pshuflw: + case X86::BI__builtin_ia32_pshuflw256: + case X86::BI__builtin_ia32_pshuflw512: + case X86::BI__builtin_ia32_vcvtps2ph: + case X86::BI__builtin_ia32_vcvtps2ph_mask: + case X86::BI__builtin_ia32_vcvtps2ph256: + case X86::BI__builtin_ia32_vcvtps2ph256_mask: + case X86::BI__builtin_ia32_vcvtps2ph512_mask: + case X86::BI__builtin_ia32_rndscaleps_128_mask: + case X86::BI__builtin_ia32_rndscalepd_128_mask: + case X86::BI__builtin_ia32_rndscaleps_256_mask: + case X86::BI__builtin_ia32_rndscalepd_256_mask: + case X86::BI__builtin_ia32_rndscaleps_mask: + case X86::BI__builtin_ia32_rndscalepd_mask: + case X86::BI__builtin_ia32_rndscaleph_mask: + case X86::BI__builtin_ia32_reducepd128_mask: + case X86::BI__builtin_ia32_reducepd256_mask: + case X86::BI__builtin_ia32_reducepd512_mask: + case X86::BI__builtin_ia32_reduceps128_mask: + case X86::BI__builtin_ia32_reduceps256_mask: + case X86::BI__builtin_ia32_reduceps512_mask: + case X86::BI__builtin_ia32_reduceph128_mask: + case X86::BI__builtin_ia32_reduceph256_mask: + case X86::BI__builtin_ia32_reduceph512_mask: + case X86::BI__builtin_ia32_prold512: + case X86::BI__builtin_ia32_prolq512: + case X86::BI__builtin_ia32_prold128: + case X86::BI__builtin_ia32_prold256: + case X86::BI__builtin_ia32_prolq128: + case X86::BI__builtin_ia32_prolq256: + case X86::BI__builtin_ia32_prord512: + case X86::BI__builtin_ia32_prorq512: + case X86::BI__builtin_ia32_prord128: + case X86::BI__builtin_ia32_prord256: + case X86::BI__builtin_ia32_prorq128: + case X86::BI__builtin_ia32_prorq256: + case X86::BI__builtin_ia32_fpclasspd128_mask: + case X86::BI__builtin_ia32_fpclasspd256_mask: + case X86::BI__builtin_ia32_fpclassps128_mask: + case X86::BI__builtin_ia32_fpclassps256_mask: + case X86::BI__builtin_ia32_fpclassps512_mask: + case X86::BI__builtin_ia32_fpclasspd512_mask: + case X86::BI__builtin_ia32_fpclassph128_mask: + case X86::BI__builtin_ia32_fpclassph256_mask: + case X86::BI__builtin_ia32_fpclassph512_mask: + case X86::BI__builtin_ia32_fpclasssd_mask: + case X86::BI__builtin_ia32_fpclassss_mask: + case X86::BI__builtin_ia32_fpclasssh_mask: + case X86::BI__builtin_ia32_pslldqi128_byteshift: + case X86::BI__builtin_ia32_pslldqi256_byteshift: + case X86::BI__builtin_ia32_pslldqi512_byteshift: + case X86::BI__builtin_ia32_psrldqi128_byteshift: + case X86::BI__builtin_ia32_psrldqi256_byteshift: + case X86::BI__builtin_ia32_psrldqi512_byteshift: + case X86::BI__builtin_ia32_kshiftliqi: + case X86::BI__builtin_ia32_kshiftlihi: + case X86::BI__builtin_ia32_kshiftlisi: + case X86::BI__builtin_ia32_kshiftlidi: + case X86::BI__builtin_ia32_kshiftriqi: + case X86::BI__builtin_ia32_kshiftrihi: + case X86::BI__builtin_ia32_kshiftrisi: + case X86::BI__builtin_ia32_kshiftridi: + i = 1; l = 0; u = 255; + break; + case X86::BI__builtin_ia32_vperm2f128_pd256: + case X86::BI__builtin_ia32_vperm2f128_ps256: + case X86::BI__builtin_ia32_vperm2f128_si256: + case X86::BI__builtin_ia32_permti256: + case X86::BI__builtin_ia32_pblendw128: + case X86::BI__builtin_ia32_pblendw256: + case X86::BI__builtin_ia32_blendps256: + case X86::BI__builtin_ia32_pblendd256: + case X86::BI__builtin_ia32_palignr128: + case X86::BI__builtin_ia32_palignr256: + case X86::BI__builtin_ia32_palignr512: + case X86::BI__builtin_ia32_alignq512: + case X86::BI__builtin_ia32_alignd512: + case X86::BI__builtin_ia32_alignd128: + case X86::BI__builtin_ia32_alignd256: + case X86::BI__builtin_ia32_alignq128: + case X86::BI__builtin_ia32_alignq256: + case X86::BI__builtin_ia32_vcomisd: + case X86::BI__builtin_ia32_vcomiss: + case X86::BI__builtin_ia32_shuf_f32x4: + case X86::BI__builtin_ia32_shuf_f64x2: + case X86::BI__builtin_ia32_shuf_i32x4: + case X86::BI__builtin_ia32_shuf_i64x2: + case X86::BI__builtin_ia32_shufpd512: + case X86::BI__builtin_ia32_shufps: + case X86::BI__builtin_ia32_shufps256: + case X86::BI__builtin_ia32_shufps512: + case X86::BI__builtin_ia32_dbpsadbw128: + case X86::BI__builtin_ia32_dbpsadbw256: + case X86::BI__builtin_ia32_dbpsadbw512: + case X86::BI__builtin_ia32_vpshldd128: + case X86::BI__builtin_ia32_vpshldd256: + case X86::BI__builtin_ia32_vpshldd512: + case X86::BI__builtin_ia32_vpshldq128: + case X86::BI__builtin_ia32_vpshldq256: + case X86::BI__builtin_ia32_vpshldq512: + case X86::BI__builtin_ia32_vpshldw128: + case X86::BI__builtin_ia32_vpshldw256: + case X86::BI__builtin_ia32_vpshldw512: + case X86::BI__builtin_ia32_vpshrdd128: + case X86::BI__builtin_ia32_vpshrdd256: + case X86::BI__builtin_ia32_vpshrdd512: + case X86::BI__builtin_ia32_vpshrdq128: + case X86::BI__builtin_ia32_vpshrdq256: + case X86::BI__builtin_ia32_vpshrdq512: + case X86::BI__builtin_ia32_vpshrdw128: + case X86::BI__builtin_ia32_vpshrdw256: + case X86::BI__builtin_ia32_vpshrdw512: + i = 2; l = 0; u = 255; + break; + case X86::BI__builtin_ia32_fixupimmpd512_mask: + case X86::BI__builtin_ia32_fixupimmpd512_maskz: + case X86::BI__builtin_ia32_fixupimmps512_mask: + case X86::BI__builtin_ia32_fixupimmps512_maskz: + case X86::BI__builtin_ia32_fixupimmsd_mask: + case X86::BI__builtin_ia32_fixupimmsd_maskz: + case X86::BI__builtin_ia32_fixupimmss_mask: + case X86::BI__builtin_ia32_fixupimmss_maskz: + case X86::BI__builtin_ia32_fixupimmpd128_mask: + case X86::BI__builtin_ia32_fixupimmpd128_maskz: + case X86::BI__builtin_ia32_fixupimmpd256_mask: + case X86::BI__builtin_ia32_fixupimmpd256_maskz: + case X86::BI__builtin_ia32_fixupimmps128_mask: + case X86::BI__builtin_ia32_fixupimmps128_maskz: + case X86::BI__builtin_ia32_fixupimmps256_mask: + case X86::BI__builtin_ia32_fixupimmps256_maskz: + case X86::BI__builtin_ia32_pternlogd512_mask: + case X86::BI__builtin_ia32_pternlogd512_maskz: + case X86::BI__builtin_ia32_pternlogq512_mask: + case X86::BI__builtin_ia32_pternlogq512_maskz: + case X86::BI__builtin_ia32_pternlogd128_mask: + case X86::BI__builtin_ia32_pternlogd128_maskz: + case X86::BI__builtin_ia32_pternlogd256_mask: + case X86::BI__builtin_ia32_pternlogd256_maskz: + case X86::BI__builtin_ia32_pternlogq128_mask: + case X86::BI__builtin_ia32_pternlogq128_maskz: + case X86::BI__builtin_ia32_pternlogq256_mask: + case X86::BI__builtin_ia32_pternlogq256_maskz: + i = 3; l = 0; u = 255; + break; + case X86::BI__builtin_ia32_gatherpfdpd: + case X86::BI__builtin_ia32_gatherpfdps: + case X86::BI__builtin_ia32_gatherpfqpd: + case X86::BI__builtin_ia32_gatherpfqps: + case X86::BI__builtin_ia32_scatterpfdpd: + case X86::BI__builtin_ia32_scatterpfdps: + case X86::BI__builtin_ia32_scatterpfqpd: + case X86::BI__builtin_ia32_scatterpfqps: + i = 4; l = 2; u = 3; + break; + case X86::BI__builtin_ia32_reducesd_mask: + case X86::BI__builtin_ia32_reducess_mask: + case X86::BI__builtin_ia32_rndscalesd_round_mask: + case X86::BI__builtin_ia32_rndscaless_round_mask: + case X86::BI__builtin_ia32_rndscalesh_round_mask: + case X86::BI__builtin_ia32_reducesh_mask: + i = 4; l = 0; u = 255; + break; + } + + // Note that we don't force a hard error on the range check here, allowing + // template-generated or macro-generated dead code to potentially have out-of- + // range values. These need to code generate, but don't need to necessarily + // make any sense. We use a warning that defaults to an error. + return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); + } + + /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo + /// parameter with the FormatAttr's correct format_idx and firstDataArg. + /// Returns true when the format fits the function and the FormatStringInfo has + /// been populated. + bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, + FormatStringInfo *FSI) { + FSI->HasVAListArg = Format->getFirstArg() == 0; + FSI->FormatIdx = Format->getFormatIdx() - 1; + FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; + + // The way the format attribute works in GCC, the implicit this argument + // of member functions is counted. However, it doesn't appear in our own + // lists, so decrement format_idx in that case. + if (IsCXXMember) { + if(FSI->FormatIdx == 0) + return false; + --FSI->FormatIdx; + if (FSI->FirstDataArg != 0) + --FSI->FirstDataArg; + } + return true; + } + + /// Checks if a the given expression evaluates to null. + /// + /// Returns true if the value evaluates to null. + static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { + // If the expression has non-null type, it doesn't evaluate to null. + if (auto nullability + = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { + if (*nullability == NullabilityKind::NonNull) + return false; + } + + // As a special case, transparent unions initialized with zero are + // considered null for the purposes of the nonnull attribute. + if (const RecordType *UT = Expr->getType()->getAsUnionType()) { + if (UT->getDecl()->hasAttr()) + if (const CompoundLiteralExpr *CLE = + dyn_cast(Expr)) + if (const InitListExpr *ILE = + dyn_cast(CLE->getInitializer())) + Expr = ILE->getInit(0); + } + + bool Result; + return (!Expr->isValueDependent() && + Expr->EvaluateAsBooleanCondition(Result, S.Context) && + !Result); + } + + static void CheckNonNullArgument(Sema &S, + const Expr *ArgExpr, + SourceLocation CallSiteLoc) { + if (CheckNonNullExpr(S, ArgExpr)) + S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, + S.PDiag(diag::warn_null_arg) + << ArgExpr->getSourceRange()); + } + + bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { + FormatStringInfo FSI; + if ((GetFormatStringType(Format) == FST_NSString) && + getFormatStringInfo(Format, false, &FSI)) { + Idx = FSI.FormatIdx; + return true; + } + return false; + } + + /// Diagnose use of %s directive in an NSString which is being passed + /// as formatting string to formatting method. + static void + DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, + const NamedDecl *FDecl, + Expr **Args, + unsigned NumArgs) { + unsigned Idx = 0; + bool Format = false; + ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); + if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { + Idx = 2; + Format = true; + } + else + for (const auto *I : FDecl->specific_attrs()) { + if (S.GetFormatNSStringIdx(I, Idx)) { + Format = true; + break; + } + } + if (!Format || NumArgs <= Idx) + return; + const Expr *FormatExpr = Args[Idx]; + if (const CStyleCastExpr *CSCE = dyn_cast(FormatExpr)) + FormatExpr = CSCE->getSubExpr(); + const StringLiteral *FormatString; + if (const ObjCStringLiteral *OSL = + dyn_cast(FormatExpr->IgnoreParenImpCasts())) + FormatString = OSL->getString(); + else + FormatString = dyn_cast(FormatExpr->IgnoreParenImpCasts()); + if (!FormatString) + return; + if (S.FormatStringHasSArg(FormatString)) { + S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) + << "%s" << 1 << 1; + S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) + << FDecl->getDeclName(); + } + } + + /// Determine whether the given type has a non-null nullability annotation. + static bool isNonNullType(ASTContext &ctx, QualType type) { + if (auto nullability = type->getNullability(ctx)) + return *nullability == NullabilityKind::NonNull; + + return false; + } + + static void CheckNonNullArguments(Sema &S, + const NamedDecl *FDecl, + const FunctionProtoType *Proto, + ArrayRef Args, + SourceLocation CallSiteLoc) { + assert((FDecl || Proto) && "Need a function declaration or prototype"); + + // Already checked by by constant evaluator. + if (S.isConstantEvaluated()) + return; + // Check the attributes attached to the method/function itself. + llvm::SmallBitVector NonNullArgs; + if (FDecl) { + // Handle the nonnull attribute on the function/method declaration itself. + for (const auto *NonNull : FDecl->specific_attrs()) { + if (!NonNull->args_size()) { + // Easy case: all pointer arguments are nonnull. + for (const auto *Arg : Args) + if (S.isValidPointerAttrType(Arg->getType())) + CheckNonNullArgument(S, Arg, CallSiteLoc); + return; + } + + for (const ParamIdx &Idx : NonNull->args()) { + unsigned IdxAST = Idx.getASTIndex(); + if (IdxAST >= Args.size()) + continue; + if (NonNullArgs.empty()) + NonNullArgs.resize(Args.size()); + NonNullArgs.set(IdxAST); + } + } + } + + if (FDecl && (isa(FDecl) || isa(FDecl))) { + // Handle the nonnull attribute on the parameters of the + // function/method. + ArrayRef parms; + if (const FunctionDecl *FD = dyn_cast(FDecl)) + parms = FD->parameters(); + else + parms = cast(FDecl)->parameters(); + + unsigned ParamIndex = 0; + for (ArrayRef::iterator I = parms.begin(), E = parms.end(); + I != E; ++I, ++ParamIndex) { + const ParmVarDecl *PVD = *I; + if (PVD->hasAttr() || + isNonNullType(S.Context, PVD->getType())) { + if (NonNullArgs.empty()) + NonNullArgs.resize(Args.size()); + + NonNullArgs.set(ParamIndex); + } + } + } else { + // If we have a non-function, non-method declaration but no + // function prototype, try to dig out the function prototype. + if (!Proto) { + if (const ValueDecl *VD = dyn_cast(FDecl)) { + QualType type = VD->getType().getNonReferenceType(); + if (auto pointerType = type->getAs()) + type = pointerType->getPointeeType(); + else if (auto blockType = type->getAs()) + type = blockType->getPointeeType(); + // FIXME: data member pointers? + + // Dig out the function prototype, if there is one. + Proto = type->getAs(); + } + } + + // Fill in non-null argument information from the nullability + // information on the parameter types (if we have them). + if (Proto) { + unsigned Index = 0; + for (auto paramType : Proto->getParamTypes()) { + if (isNonNullType(S.Context, paramType)) { + if (NonNullArgs.empty()) + NonNullArgs.resize(Args.size()); + + NonNullArgs.set(Index); + } + + ++Index; + } + } + } + + // Check for non-null arguments. + for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); + ArgIndex != ArgIndexEnd; ++ArgIndex) { + if (NonNullArgs[ArgIndex]) + CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); + } + } + + /// Warn if a pointer or reference argument passed to a function points to an + /// object that is less aligned than the parameter. This can happen when + /// creating a typedef with a lower alignment than the original type and then + /// calling functions defined in terms of the original type. + void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, + StringRef ParamName, QualType ArgTy, + QualType ParamTy) { + + // If a function accepts a pointer or reference type + if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) + return; + + // If the parameter is a pointer type, get the pointee type for the + // argument too. If the parameter is a reference type, don't try to get + // the pointee type for the argument. + if (ParamTy->isPointerType()) + ArgTy = ArgTy->getPointeeType(); + + // Remove reference or pointer + ParamTy = ParamTy->getPointeeType(); + + // Find expected alignment, and the actual alignment of the passed object. + // getTypeAlignInChars requires complete types + if (ArgTy.isNull() || ParamTy->isIncompleteType() || + ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || + ArgTy->isUndeducedType()) + return; + + CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); + CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); + + // If the argument is less aligned than the parameter, there is a + // potential alignment issue. + if (ArgAlign < ParamAlign) + Diag(Loc, diag::warn_param_mismatched_alignment) + << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() + << ParamName << FDecl; + } + + /// Handles the checks for format strings, non-POD arguments to vararg + /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if + /// attributes. + void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, + const Expr *ThisArg, ArrayRef Args, + bool IsMemberFunction, SourceLocation Loc, + SourceRange Range, VariadicCallType CallType) { + // FIXME: We should check as much as we can in the template definition. + if (CurContext->isDependentContext()) + return; + + // Printf and scanf checking. + llvm::SmallBitVector CheckedVarArgs; + if (FDecl) { + for (const auto *I : FDecl->specific_attrs()) { + // Only create vector if there are format attributes. + CheckedVarArgs.resize(Args.size()); + + CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, + CheckedVarArgs); + } + } + + // Refuse POD arguments that weren't caught by the format string + // checks above. + auto *FD = dyn_cast_or_null(FDecl); + if (CallType != VariadicDoesNotApply && + (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { + unsigned NumParams = Proto ? Proto->getNumParams() + : FDecl && isa(FDecl) + ? cast(FDecl)->getNumParams() + : FDecl && isa(FDecl) + ? cast(FDecl)->param_size() + : 0; + + for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { + // Args[ArgIdx] can be null in malformed code. + if (const Expr *Arg = Args[ArgIdx]) { + if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) + checkVariadicArgument(Arg, CallType); + } + } + } + + if (FDecl || Proto) { + CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); + + // Type safety checking. + if (FDecl) { + for (const auto *I : FDecl->specific_attrs()) + CheckArgumentWithTypeTag(I, Args, Loc); + } + } + + // Check that passed arguments match the alignment of original arguments. + // Try to get the missing prototype from the declaration. + if (!Proto && FDecl) { + const auto *FT = FDecl->getFunctionType(); + if (isa_and_nonnull(FT)) + Proto = cast(FDecl->getFunctionType()); + } + if (Proto) { + // For variadic functions, we may have more args than parameters. + // For some K&R functions, we may have less args than parameters. + const auto N = std::min(Proto->getNumParams(), Args.size()); + for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { + // Args[ArgIdx] can be null in malformed code. + if (const Expr *Arg = Args[ArgIdx]) { + if (Arg->containsErrors()) + continue; + + QualType ParamTy = Proto->getParamType(ArgIdx); + QualType ArgTy = Arg->getType(); + CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), + ArgTy, ParamTy); + } + } + } + + if (FDecl && FDecl->hasAttr()) { + auto *AA = FDecl->getAttr(); + const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; + if (!Arg->isValueDependent()) { + Expr::EvalResult Align; + if (Arg->EvaluateAsInt(Align, Context)) { + const llvm::APSInt &I = Align.Val.getInt(); + if (!I.isPowerOf2()) + Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) + << Arg->getSourceRange(); + + if (I > Sema::MaximumAlignment) + Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) + << Arg->getSourceRange() << Sema::MaximumAlignment; + } + } + } + + if (FD) + diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); + } + + /// CheckConstructorCall - Check a constructor call for correctness and safety + /// properties not enforced by the C type system. + void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, + ArrayRef Args, + const FunctionProtoType *Proto, + SourceLocation Loc) { + VariadicCallType CallType = + Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; + + auto *Ctor = cast(FDecl); + CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), + Context.getPointerType(Ctor->getThisObjectType())); + + checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, + Loc, SourceRange(), CallType); + } + + /// CheckFunctionCall - Check a direct function call for various correctness + /// and safety properties not strictly enforced by the C type system. + bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, + const FunctionProtoType *Proto) { + bool IsMemberOperatorCall = isa(TheCall) && + isa(FDecl); + bool IsMemberFunction = isa(TheCall) || + IsMemberOperatorCall; + VariadicCallType CallType = getVariadicCallType(FDecl, Proto, + TheCall->getCallee()); + Expr** Args = TheCall->getArgs(); + unsigned NumArgs = TheCall->getNumArgs(); + + Expr *ImplicitThis = nullptr; + if (IsMemberOperatorCall) { + // If this is a call to a member operator, hide the first argument + // from checkCall. + // FIXME: Our choice of AST representation here is less than ideal. + ImplicitThis = Args[0]; + ++Args; + --NumArgs; + } else if (IsMemberFunction) + ImplicitThis = + cast(TheCall)->getImplicitObjectArgument(); + + if (ImplicitThis) { + // ImplicitThis may or may not be a pointer, depending on whether . or -> is + // used. + QualType ThisType = ImplicitThis->getType(); + if (!ThisType->isPointerType()) { + assert(!ThisType->isReferenceType()); + ThisType = Context.getPointerType(ThisType); + } + + QualType ThisTypeFromDecl = + Context.getPointerType(cast(FDecl)->getThisObjectType()); + + CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, + ThisTypeFromDecl); + } + + checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), + IsMemberFunction, TheCall->getRParenLoc(), + TheCall->getCallee()->getSourceRange(), CallType); + + IdentifierInfo *FnInfo = FDecl->getIdentifier(); + // None of the checks below are needed for functions that don't have + // simple names (e.g., C++ conversion functions). + if (!FnInfo) + return false; + + CheckTCBEnforcement(TheCall, FDecl); + + CheckAbsoluteValueFunction(TheCall, FDecl); + CheckMaxUnsignedZero(TheCall, FDecl); + + if (getLangOpts().ObjC) + DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); + + unsigned CMId = FDecl->getMemoryFunctionKind(); + + // Handle memory setting and copying functions. + switch (CMId) { + case 0: + return false; + case Builtin::BIstrlcpy: // fallthrough + case Builtin::BIstrlcat: + CheckStrlcpycatArguments(TheCall, FnInfo); + break; + case Builtin::BIstrncat: + CheckStrncatArguments(TheCall, FnInfo); + break; + case Builtin::BIfree: + CheckFreeArguments(TheCall); + break; + default: + CheckMemaccessArguments(TheCall, CMId, FnInfo); + } + + return false; + } + + bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, + ArrayRef Args) { + VariadicCallType CallType = + Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; + + checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, + /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), + CallType); + + return false; + } + + bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, + const FunctionProtoType *Proto) { + QualType Ty; + if (const auto *V = dyn_cast(NDecl)) + Ty = V->getType().getNonReferenceType(); + else if (const auto *F = dyn_cast(NDecl)) + Ty = F->getType().getNonReferenceType(); + else + return false; + + if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && + !Ty->isFunctionProtoType()) + return false; + + VariadicCallType CallType; + if (!Proto || !Proto->isVariadic()) { + CallType = VariadicDoesNotApply; + } else if (Ty->isBlockPointerType()) { + CallType = VariadicBlock; + } else { // Ty->isFunctionPointerType() + CallType = VariadicFunction; + } + + checkCall(NDecl, Proto, /*ThisArg=*/nullptr, + llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), + /*IsMemberFunction=*/false, TheCall->getRParenLoc(), + TheCall->getCallee()->getSourceRange(), CallType); + + return false; + } + + /// Checks function calls when a FunctionDecl or a NamedDecl is not available, + /// such as function pointers returned from functions. + bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { + VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, + TheCall->getCallee()); + checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, + llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), + /*IsMemberFunction=*/false, TheCall->getRParenLoc(), + TheCall->getCallee()->getSourceRange(), CallType); + + return false; + } + + static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { + if (!llvm::isValidAtomicOrderingCABI(Ordering)) + return false; + + auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; + switch (Op) { + case AtomicExpr::AO__c11_atomic_init: + case AtomicExpr::AO__opencl_atomic_init: + llvm_unreachable("There is no ordering argument for an init"); + + case AtomicExpr::AO__c11_atomic_load: + case AtomicExpr::AO__opencl_atomic_load: + case AtomicExpr::AO__atomic_load_n: + case AtomicExpr::AO__atomic_load: + return OrderingCABI != llvm::AtomicOrderingCABI::release && + OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; + + case AtomicExpr::AO__c11_atomic_store: + case AtomicExpr::AO__opencl_atomic_store: + case AtomicExpr::AO__atomic_store: + case AtomicExpr::AO__atomic_store_n: + return OrderingCABI != llvm::AtomicOrderingCABI::consume && + OrderingCABI != llvm::AtomicOrderingCABI::acquire && + OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; + + default: + return true; + } + } + + ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, + AtomicExpr::AtomicOp Op) { + CallExpr *TheCall = cast(TheCallResult.get()); + DeclRefExpr *DRE =cast(TheCall->getCallee()->IgnoreParenCasts()); + MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; + return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, + DRE->getSourceRange(), TheCall->getRParenLoc(), Args, + Op); + } + + ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, + SourceLocation RParenLoc, MultiExprArg Args, + AtomicExpr::AtomicOp Op, + AtomicArgumentOrder ArgOrder) { + // All the non-OpenCL operations take one of the following forms. + // The OpenCL operations take the __c11 forms with one extra argument for + // synchronization scope. + enum { + // C __c11_atomic_init(A *, C) + Init, + + // C __c11_atomic_load(A *, int) + Load, + + // void __atomic_load(A *, CP, int) + LoadCopy, + + // void __atomic_store(A *, CP, int) + Copy, + + // C __c11_atomic_add(A *, M, int) + Arithmetic, + + // C __atomic_exchange_n(A *, CP, int) + Xchg, + + // void __atomic_exchange(A *, C *, CP, int) + GNUXchg, + + // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) + C11CmpXchg, + + // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) + GNUCmpXchg + } Form = Init; + + const unsigned NumForm = GNUCmpXchg + 1; + const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; + const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; + // where: + // C is an appropriate type, + // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, + // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, + // M is C if C is an integer, and ptrdiff_t if C is a pointer, and + // the int parameters are for orderings. + + static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm + && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, + "need to update code for modified forms"); + static_assert(AtomicExpr::AO__c11_atomic_init == 0 && + AtomicExpr::AO__c11_atomic_fetch_min + 1 == + AtomicExpr::AO__atomic_load, + "need to update code for modified C11 atomics"); + bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && + Op <= AtomicExpr::AO__opencl_atomic_fetch_max; + bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && + Op <= AtomicExpr::AO__c11_atomic_fetch_min) || + IsOpenCL; + bool IsN = Op == AtomicExpr::AO__atomic_load_n || + Op == AtomicExpr::AO__atomic_store_n || + Op == AtomicExpr::AO__atomic_exchange_n || + Op == AtomicExpr::AO__atomic_compare_exchange_n; + bool IsAddSub = false; + + switch (Op) { + case AtomicExpr::AO__c11_atomic_init: + case AtomicExpr::AO__opencl_atomic_init: + Form = Init; + break; + + case AtomicExpr::AO__c11_atomic_load: + case AtomicExpr::AO__opencl_atomic_load: + case AtomicExpr::AO__atomic_load_n: + Form = Load; + break; + + case AtomicExpr::AO__atomic_load: + Form = LoadCopy; + break; + + case AtomicExpr::AO__c11_atomic_store: + case AtomicExpr::AO__opencl_atomic_store: + case AtomicExpr::AO__atomic_store: + case AtomicExpr::AO__atomic_store_n: + Form = Copy; + break; + + case AtomicExpr::AO__c11_atomic_fetch_add: + case AtomicExpr::AO__c11_atomic_fetch_sub: + case AtomicExpr::AO__opencl_atomic_fetch_add: + case AtomicExpr::AO__opencl_atomic_fetch_sub: + case AtomicExpr::AO__atomic_fetch_add: + case AtomicExpr::AO__atomic_fetch_sub: + case AtomicExpr::AO__atomic_add_fetch: + case AtomicExpr::AO__atomic_sub_fetch: + IsAddSub = true; + Form = Arithmetic; + break; + case AtomicExpr::AO__c11_atomic_fetch_and: + case AtomicExpr::AO__c11_atomic_fetch_or: + case AtomicExpr::AO__c11_atomic_fetch_xor: + case AtomicExpr::AO__opencl_atomic_fetch_and: + case AtomicExpr::AO__opencl_atomic_fetch_or: + case AtomicExpr::AO__opencl_atomic_fetch_xor: + case AtomicExpr::AO__atomic_fetch_and: + case AtomicExpr::AO__atomic_fetch_or: + case AtomicExpr::AO__atomic_fetch_xor: + case AtomicExpr::AO__atomic_fetch_nand: + case AtomicExpr::AO__atomic_and_fetch: + case AtomicExpr::AO__atomic_or_fetch: + case AtomicExpr::AO__atomic_xor_fetch: + case AtomicExpr::AO__atomic_nand_fetch: + Form = Arithmetic; + break; + case AtomicExpr::AO__c11_atomic_fetch_min: + case AtomicExpr::AO__c11_atomic_fetch_max: + case AtomicExpr::AO__opencl_atomic_fetch_min: + case AtomicExpr::AO__opencl_atomic_fetch_max: + case AtomicExpr::AO__atomic_min_fetch: + case AtomicExpr::AO__atomic_max_fetch: + case AtomicExpr::AO__atomic_fetch_min: + case AtomicExpr::AO__atomic_fetch_max: + Form = Arithmetic; + break; + + case AtomicExpr::AO__c11_atomic_exchange: + case AtomicExpr::AO__opencl_atomic_exchange: + case AtomicExpr::AO__atomic_exchange_n: + Form = Xchg; + break; + + case AtomicExpr::AO__atomic_exchange: + Form = GNUXchg; + break; + + case AtomicExpr::AO__c11_atomic_compare_exchange_strong: + case AtomicExpr::AO__c11_atomic_compare_exchange_weak: + case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: + case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: + Form = C11CmpXchg; + break; + + case AtomicExpr::AO__atomic_compare_exchange: + case AtomicExpr::AO__atomic_compare_exchange_n: + Form = GNUCmpXchg; + break; + } + + unsigned AdjustedNumArgs = NumArgs[Form]; + if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) + ++AdjustedNumArgs; + // Check we have the right number of arguments. + if (Args.size() < AdjustedNumArgs) { + Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) + << 0 << AdjustedNumArgs << static_cast(Args.size()) + << ExprRange; + return ExprError(); + } else if (Args.size() > AdjustedNumArgs) { + Diag(Args[AdjustedNumArgs]->getBeginLoc(), + diag::err_typecheck_call_too_many_args) + << 0 << AdjustedNumArgs << static_cast(Args.size()) + << ExprRange; + return ExprError(); + } + + // Inspect the first argument of the atomic operation. + Expr *Ptr = Args[0]; + ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); + if (ConvertedPtr.isInvalid()) + return ExprError(); + + Ptr = ConvertedPtr.get(); + const PointerType *pointerType = Ptr->getType()->getAs(); + if (!pointerType) { + Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) + << Ptr->getType() << Ptr->getSourceRange(); + return ExprError(); + } + + // For a __c11 builtin, this should be a pointer to an _Atomic type. + QualType AtomTy = pointerType->getPointeeType(); // 'A' + QualType ValType = AtomTy; // 'C' + if (IsC11) { + if (!AtomTy->isAtomicType()) { + Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) + << Ptr->getType() << Ptr->getSourceRange(); + return ExprError(); + } + if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || + AtomTy.getAddressSpace() == LangAS::opencl_constant) { + Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) + << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() + << Ptr->getSourceRange(); + return ExprError(); + } + ValType = AtomTy->castAs()->getValueType(); + } else if (Form != Load && Form != LoadCopy) { + if (ValType.isConstQualified()) { + Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) + << Ptr->getType() << Ptr->getSourceRange(); + return ExprError(); + } + } + + // For an arithmetic operation, the implied arithmetic must be well-formed. + if (Form == Arithmetic) { + // gcc does not enforce these rules for GNU atomics, but we do so for + // sanity. + auto IsAllowedValueType = [&](QualType ValType) { + if (ValType->isIntegerType()) + return true; + if (ValType->isPointerType()) + return true; + if (!ValType->isFloatingType()) + return false; + // LLVM Parser does not allow atomicrmw with x86_fp80 type. + if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && + &Context.getTargetInfo().getLongDoubleFormat() == + &llvm::APFloat::x87DoubleExtended()) + return false; + return true; + }; + if (IsAddSub && !IsAllowedValueType(ValType)) { + Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) + << IsC11 << Ptr->getType() << Ptr->getSourceRange(); + return ExprError(); + } + if (!IsAddSub && !ValType->isIntegerType()) { + Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) + << IsC11 << Ptr->getType() << Ptr->getSourceRange(); + return ExprError(); + } + if (IsC11 && ValType->isPointerType() && + RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), + diag::err_incomplete_type)) { + return ExprError(); + } + } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { + // For __atomic_*_n operations, the value type must be a scalar integral or + // pointer type which is 1, 2, 4, 8 or 16 bytes in length. + Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) + << IsC11 << Ptr->getType() << Ptr->getSourceRange(); + return ExprError(); + } + + if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && + !AtomTy->isScalarType()) { + // For GNU atomics, require a trivially-copyable type. This is not part of + // the GNU atomics specification, but we enforce it for sanity. + Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) + << Ptr->getType() << Ptr->getSourceRange(); + return ExprError(); + } + + switch (ValType.getObjCLifetime()) { + case Qualifiers::OCL_None: + case Qualifiers::OCL_ExplicitNone: + // okay + break; + + case Qualifiers::OCL_Weak: + case Qualifiers::OCL_Strong: + case Qualifiers::OCL_Autoreleasing: + // FIXME: Can this happen? By this point, ValType should be known + // to be trivially copyable. + Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) + << ValType << Ptr->getSourceRange(); + return ExprError(); + } + + // All atomic operations have an overload which takes a pointer to a volatile + // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself + // into the result or the other operands. Similarly atomic_load takes a + // pointer to a const 'A'. + ValType.removeLocalVolatile(); + ValType.removeLocalConst(); + QualType ResultType = ValType; + if (Form == Copy || Form == LoadCopy || Form == GNUXchg || + Form == Init) + ResultType = Context.VoidTy; + else if (Form == C11CmpXchg || Form == GNUCmpXchg) + ResultType = Context.BoolTy; + + // The type of a parameter passed 'by value'. In the GNU atomics, such + // arguments are actually passed as pointers. + QualType ByValType = ValType; // 'CP' + bool IsPassedByAddress = false; + if (!IsC11 && !IsN) { + ByValType = Ptr->getType(); + IsPassedByAddress = true; + } + + SmallVector APIOrderedArgs; + if (ArgOrder == Sema::AtomicArgumentOrder::AST) { + APIOrderedArgs.push_back(Args[0]); + switch (Form) { + case Init: + case Load: + APIOrderedArgs.push_back(Args[1]); // Val1/Order + break; + case LoadCopy: + case Copy: + case Arithmetic: + case Xchg: + APIOrderedArgs.push_back(Args[2]); // Val1 + APIOrderedArgs.push_back(Args[1]); // Order + break; + case GNUXchg: + APIOrderedArgs.push_back(Args[2]); // Val1 + APIOrderedArgs.push_back(Args[3]); // Val2 + APIOrderedArgs.push_back(Args[1]); // Order + break; + case C11CmpXchg: + APIOrderedArgs.push_back(Args[2]); // Val1 + APIOrderedArgs.push_back(Args[4]); // Val2 + APIOrderedArgs.push_back(Args[1]); // Order + APIOrderedArgs.push_back(Args[3]); // OrderFail + break; + case GNUCmpXchg: + APIOrderedArgs.push_back(Args[2]); // Val1 + APIOrderedArgs.push_back(Args[4]); // Val2 + APIOrderedArgs.push_back(Args[5]); // Weak + APIOrderedArgs.push_back(Args[1]); // Order + APIOrderedArgs.push_back(Args[3]); // OrderFail + break; + } + } else + APIOrderedArgs.append(Args.begin(), Args.end()); + + // The first argument's non-CV pointer type is used to deduce the type of + // subsequent arguments, except for: + // - weak flag (always converted to bool) + // - memory order (always converted to int) + // - scope (always converted to int) + for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { + QualType Ty; + if (i < NumVals[Form] + 1) { + switch (i) { + case 0: + // The first argument is always a pointer. It has a fixed type. + // It is always dereferenced, a nullptr is undefined. + CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); + // Nothing else to do: we already know all we want about this pointer. + continue; + case 1: + // The second argument is the non-atomic operand. For arithmetic, this + // is always passed by value, and for a compare_exchange it is always + // passed by address. For the rest, GNU uses by-address and C11 uses + // by-value. + assert(Form != Load); + if (Form == Arithmetic && ValType->isPointerType()) + Ty = Context.getPointerDiffType(); + else if (Form == Init || Form == Arithmetic) + Ty = ValType; + else if (Form == Copy || Form == Xchg) { + if (IsPassedByAddress) { + // The value pointer is always dereferenced, a nullptr is undefined. + CheckNonNullArgument(*this, APIOrderedArgs[i], + ExprRange.getBegin()); + } + Ty = ByValType; + } else { + Expr *ValArg = APIOrderedArgs[i]; + // The value pointer is always dereferenced, a nullptr is undefined. + CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); + LangAS AS = LangAS::Default; + // Keep address space of non-atomic pointer type. + if (const PointerType *PtrTy = + ValArg->getType()->getAs()) { + AS = PtrTy->getPointeeType().getAddressSpace(); + } + Ty = Context.getPointerType( + Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); + } + break; + case 2: + // The third argument to compare_exchange / GNU exchange is the desired + // value, either by-value (for the C11 and *_n variant) or as a pointer. + if (IsPassedByAddress) + CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); + Ty = ByValType; + break; + case 3: + // The fourth argument to GNU compare_exchange is a 'weak' flag. + Ty = Context.BoolTy; + break; + } + } else { + // The order(s) and scope are always converted to int. + Ty = Context.IntTy; + } + + InitializedEntity Entity = + InitializedEntity::InitializeParameter(Context, Ty, false); + ExprResult Arg = APIOrderedArgs[i]; + Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); + if (Arg.isInvalid()) + return true; + APIOrderedArgs[i] = Arg.get(); + } + + // Permute the arguments into a 'consistent' order. + SmallVector SubExprs; + SubExprs.push_back(Ptr); + switch (Form) { + case Init: + // Note, AtomicExpr::getVal1() has a special case for this atomic. + SubExprs.push_back(APIOrderedArgs[1]); // Val1 + break; + case Load: + SubExprs.push_back(APIOrderedArgs[1]); // Order + break; + case LoadCopy: + case Copy: + case Arithmetic: + case Xchg: + SubExprs.push_back(APIOrderedArgs[2]); // Order + SubExprs.push_back(APIOrderedArgs[1]); // Val1 + break; + case GNUXchg: + // Note, AtomicExpr::getVal2() has a special case for this atomic. + SubExprs.push_back(APIOrderedArgs[3]); // Order + SubExprs.push_back(APIOrderedArgs[1]); // Val1 + SubExprs.push_back(APIOrderedArgs[2]); // Val2 + break; + case C11CmpXchg: + SubExprs.push_back(APIOrderedArgs[3]); // Order + SubExprs.push_back(APIOrderedArgs[1]); // Val1 + SubExprs.push_back(APIOrderedArgs[4]); // OrderFail + SubExprs.push_back(APIOrderedArgs[2]); // Val2 + break; + case GNUCmpXchg: + SubExprs.push_back(APIOrderedArgs[4]); // Order + SubExprs.push_back(APIOrderedArgs[1]); // Val1 + SubExprs.push_back(APIOrderedArgs[5]); // OrderFail + SubExprs.push_back(APIOrderedArgs[2]); // Val2 + SubExprs.push_back(APIOrderedArgs[3]); // Weak + break; + } + + if (SubExprs.size() >= 2 && Form != Init) { + if (Optional Result = + SubExprs[1]->getIntegerConstantExpr(Context)) + if (!isValidOrderingForOp(Result->getSExtValue(), Op)) + Diag(SubExprs[1]->getBeginLoc(), + diag::warn_atomic_op_has_invalid_memory_order) + << SubExprs[1]->getSourceRange(); + } + + if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { + auto *Scope = Args[Args.size() - 1]; + if (Optional Result = + Scope->getIntegerConstantExpr(Context)) { + if (!ScopeModel->isValid(Result->getZExtValue())) + Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) + << Scope->getSourceRange(); + } + SubExprs.push_back(Scope); + } + + AtomicExpr *AE = new (Context) + AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); + + if ((Op == AtomicExpr::AO__c11_atomic_load || + Op == AtomicExpr::AO__c11_atomic_store || + Op == AtomicExpr::AO__opencl_atomic_load || + Op == AtomicExpr::AO__opencl_atomic_store ) && + Context.AtomicUsesUnsupportedLibcall(AE)) + Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) + << ((Op == AtomicExpr::AO__c11_atomic_load || + Op == AtomicExpr::AO__opencl_atomic_load) + ? 0 + : 1); + + if (ValType->isExtIntType()) { + Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); + return ExprError(); + } + + return AE; + } + + /// checkBuiltinArgument - Given a call to a builtin function, perform + /// normal type-checking on the given argument, updating the call in + /// place. This is useful when a builtin function requires custom + /// type-checking for some of its arguments but not necessarily all of + /// them. + /// + /// Returns true on error. + static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { + FunctionDecl *Fn = E->getDirectCallee(); + assert(Fn && "builtin call without direct callee!"); + + ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); + InitializedEntity Entity = + InitializedEntity::InitializeParameter(S.Context, Param); + + ExprResult Arg = E->getArg(0); + Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); + if (Arg.isInvalid()) + return true; + + E->setArg(ArgIndex, Arg.get()); + return false; + } + + /// We have a call to a function like __sync_fetch_and_add, which is an + /// overloaded function based on the pointer type of its first argument. + /// The main BuildCallExpr routines have already promoted the types of + /// arguments because all of these calls are prototyped as void(...). + /// + /// This function goes through and does final semantic checking for these + /// builtins, as well as generating any warnings. + ExprResult + Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { + CallExpr *TheCall = static_cast(TheCallResult.get()); + Expr *Callee = TheCall->getCallee(); + DeclRefExpr *DRE = cast(Callee->IgnoreParenCasts()); + FunctionDecl *FDecl = cast(DRE->getDecl()); + + // Ensure that we have at least one argument to do type inference from. + if (TheCall->getNumArgs() < 1) { + Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) + << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); + return ExprError(); + } + + // Inspect the first argument of the atomic builtin. This should always be + // a pointer type, whose element is an integral scalar or pointer type. + // Because it is a pointer type, we don't have to worry about any implicit + // casts here. + // FIXME: We don't allow floating point scalars as input. + Expr *FirstArg = TheCall->getArg(0); + ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); + if (FirstArgResult.isInvalid()) + return ExprError(); + FirstArg = FirstArgResult.get(); + TheCall->setArg(0, FirstArg); + + const PointerType *pointerType = FirstArg->getType()->getAs(); + if (!pointerType) { + Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) + << FirstArg->getType() << FirstArg->getSourceRange(); + return ExprError(); + } + + QualType ValType = pointerType->getPointeeType(); + if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && + !ValType->isBlockPointerType()) { + Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) + << FirstArg->getType() << FirstArg->getSourceRange(); + return ExprError(); + } + + if (ValType.isConstQualified()) { + Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) + << FirstArg->getType() << FirstArg->getSourceRange(); + return ExprError(); + } + + switch (ValType.getObjCLifetime()) { + case Qualifiers::OCL_None: + case Qualifiers::OCL_ExplicitNone: + // okay + break; + + case Qualifiers::OCL_Weak: + case Qualifiers::OCL_Strong: + case Qualifiers::OCL_Autoreleasing: + Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) + << ValType << FirstArg->getSourceRange(); + return ExprError(); + } + + // Strip any qualifiers off ValType. + ValType = ValType.getUnqualifiedType(); + + // The majority of builtins return a value, but a few have special return + // types, so allow them to override appropriately below. + QualType ResultType = ValType; + + // We need to figure out which concrete builtin this maps onto. For example, + // __sync_fetch_and_add with a 2 byte object turns into + // __sync_fetch_and_add_2. + #define BUILTIN_ROW(x) \ + { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ + Builtin::BI##x##_8, Builtin::BI##x##_16 } + + static const unsigned BuiltinIndices[][5] = { + BUILTIN_ROW(__sync_fetch_and_add), + BUILTIN_ROW(__sync_fetch_and_sub), + BUILTIN_ROW(__sync_fetch_and_or), + BUILTIN_ROW(__sync_fetch_and_and), + BUILTIN_ROW(__sync_fetch_and_xor), + BUILTIN_ROW(__sync_fetch_and_nand), + + BUILTIN_ROW(__sync_add_and_fetch), + BUILTIN_ROW(__sync_sub_and_fetch), + BUILTIN_ROW(__sync_and_and_fetch), + BUILTIN_ROW(__sync_or_and_fetch), + BUILTIN_ROW(__sync_xor_and_fetch), + BUILTIN_ROW(__sync_nand_and_fetch), + + BUILTIN_ROW(__sync_val_compare_and_swap), + BUILTIN_ROW(__sync_bool_compare_and_swap), + BUILTIN_ROW(__sync_lock_test_and_set), + BUILTIN_ROW(__sync_lock_release), + BUILTIN_ROW(__sync_swap) + }; + #undef BUILTIN_ROW + + // Determine the index of the size. + unsigned SizeIndex; + switch (Context.getTypeSizeInChars(ValType).getQuantity()) { + case 1: SizeIndex = 0; break; + case 2: SizeIndex = 1; break; + case 4: SizeIndex = 2; break; + case 8: SizeIndex = 3; break; + case 16: SizeIndex = 4; break; + default: + Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) + << FirstArg->getType() << FirstArg->getSourceRange(); + return ExprError(); + } + + // Each of these builtins has one pointer argument, followed by some number of + // values (0, 1 or 2) followed by a potentially empty varags list of stuff + // that we ignore. Find out which row of BuiltinIndices to read from as well + // as the number of fixed args. + unsigned BuiltinID = FDecl->getBuiltinID(); + unsigned BuiltinIndex, NumFixed = 1; + bool WarnAboutSemanticsChange = false; + switch (BuiltinID) { + default: llvm_unreachable("Unknown overloaded atomic builtin!"); + case Builtin::BI__sync_fetch_and_add: + case Builtin::BI__sync_fetch_and_add_1: + case Builtin::BI__sync_fetch_and_add_2: + case Builtin::BI__sync_fetch_and_add_4: + case Builtin::BI__sync_fetch_and_add_8: + case Builtin::BI__sync_fetch_and_add_16: + BuiltinIndex = 0; + break; + + case Builtin::BI__sync_fetch_and_sub: + case Builtin::BI__sync_fetch_and_sub_1: + case Builtin::BI__sync_fetch_and_sub_2: + case Builtin::BI__sync_fetch_and_sub_4: + case Builtin::BI__sync_fetch_and_sub_8: + case Builtin::BI__sync_fetch_and_sub_16: + BuiltinIndex = 1; + break; + + case Builtin::BI__sync_fetch_and_or: + case Builtin::BI__sync_fetch_and_or_1: + case Builtin::BI__sync_fetch_and_or_2: + case Builtin::BI__sync_fetch_and_or_4: + case Builtin::BI__sync_fetch_and_or_8: + case Builtin::BI__sync_fetch_and_or_16: + BuiltinIndex = 2; + break; + + case Builtin::BI__sync_fetch_and_and: + case Builtin::BI__sync_fetch_and_and_1: + case Builtin::BI__sync_fetch_and_and_2: + case Builtin::BI__sync_fetch_and_and_4: + case Builtin::BI__sync_fetch_and_and_8: + case Builtin::BI__sync_fetch_and_and_16: + BuiltinIndex = 3; + break; + + case Builtin::BI__sync_fetch_and_xor: + case Builtin::BI__sync_fetch_and_xor_1: + case Builtin::BI__sync_fetch_and_xor_2: + case Builtin::BI__sync_fetch_and_xor_4: + case Builtin::BI__sync_fetch_and_xor_8: + case Builtin::BI__sync_fetch_and_xor_16: + BuiltinIndex = 4; + break; + + case Builtin::BI__sync_fetch_and_nand: + case Builtin::BI__sync_fetch_and_nand_1: + case Builtin::BI__sync_fetch_and_nand_2: + case Builtin::BI__sync_fetch_and_nand_4: + case Builtin::BI__sync_fetch_and_nand_8: + case Builtin::BI__sync_fetch_and_nand_16: + BuiltinIndex = 5; + WarnAboutSemanticsChange = true; + break; + + case Builtin::BI__sync_add_and_fetch: + case Builtin::BI__sync_add_and_fetch_1: + case Builtin::BI__sync_add_and_fetch_2: + case Builtin::BI__sync_add_and_fetch_4: + case Builtin::BI__sync_add_and_fetch_8: + case Builtin::BI__sync_add_and_fetch_16: + BuiltinIndex = 6; + break; + + case Builtin::BI__sync_sub_and_fetch: + case Builtin::BI__sync_sub_and_fetch_1: + case Builtin::BI__sync_sub_and_fetch_2: + case Builtin::BI__sync_sub_and_fetch_4: + case Builtin::BI__sync_sub_and_fetch_8: + case Builtin::BI__sync_sub_and_fetch_16: + BuiltinIndex = 7; + break; + + case Builtin::BI__sync_and_and_fetch: + case Builtin::BI__sync_and_and_fetch_1: + case Builtin::BI__sync_and_and_fetch_2: + case Builtin::BI__sync_and_and_fetch_4: + case Builtin::BI__sync_and_and_fetch_8: + case Builtin::BI__sync_and_and_fetch_16: + BuiltinIndex = 8; + break; + + case Builtin::BI__sync_or_and_fetch: + case Builtin::BI__sync_or_and_fetch_1: + case Builtin::BI__sync_or_and_fetch_2: + case Builtin::BI__sync_or_and_fetch_4: + case Builtin::BI__sync_or_and_fetch_8: + case Builtin::BI__sync_or_and_fetch_16: + BuiltinIndex = 9; + break; + + case Builtin::BI__sync_xor_and_fetch: + case Builtin::BI__sync_xor_and_fetch_1: + case Builtin::BI__sync_xor_and_fetch_2: + case Builtin::BI__sync_xor_and_fetch_4: + case Builtin::BI__sync_xor_and_fetch_8: + case Builtin::BI__sync_xor_and_fetch_16: + BuiltinIndex = 10; + break; + + case Builtin::BI__sync_nand_and_fetch: + case Builtin::BI__sync_nand_and_fetch_1: + case Builtin::BI__sync_nand_and_fetch_2: + case Builtin::BI__sync_nand_and_fetch_4: + case Builtin::BI__sync_nand_and_fetch_8: + case Builtin::BI__sync_nand_and_fetch_16: + BuiltinIndex = 11; + WarnAboutSemanticsChange = true; + break; + + case Builtin::BI__sync_val_compare_and_swap: + case Builtin::BI__sync_val_compare_and_swap_1: + case Builtin::BI__sync_val_compare_and_swap_2: + case Builtin::BI__sync_val_compare_and_swap_4: + case Builtin::BI__sync_val_compare_and_swap_8: + case Builtin::BI__sync_val_compare_and_swap_16: + BuiltinIndex = 12; + NumFixed = 2; + break; + + case Builtin::BI__sync_bool_compare_and_swap: + case Builtin::BI__sync_bool_compare_and_swap_1: + case Builtin::BI__sync_bool_compare_and_swap_2: + case Builtin::BI__sync_bool_compare_and_swap_4: + case Builtin::BI__sync_bool_compare_and_swap_8: + case Builtin::BI__sync_bool_compare_and_swap_16: + BuiltinIndex = 13; + NumFixed = 2; + ResultType = Context.BoolTy; + break; + + case Builtin::BI__sync_lock_test_and_set: + case Builtin::BI__sync_lock_test_and_set_1: + case Builtin::BI__sync_lock_test_and_set_2: + case Builtin::BI__sync_lock_test_and_set_4: + case Builtin::BI__sync_lock_test_and_set_8: + case Builtin::BI__sync_lock_test_and_set_16: + BuiltinIndex = 14; + break; + + case Builtin::BI__sync_lock_release: + case Builtin::BI__sync_lock_release_1: + case Builtin::BI__sync_lock_release_2: + case Builtin::BI__sync_lock_release_4: + case Builtin::BI__sync_lock_release_8: + case Builtin::BI__sync_lock_release_16: + BuiltinIndex = 15; + NumFixed = 0; + ResultType = Context.VoidTy; + break; + + case Builtin::BI__sync_swap: + case Builtin::BI__sync_swap_1: + case Builtin::BI__sync_swap_2: + case Builtin::BI__sync_swap_4: + case Builtin::BI__sync_swap_8: + case Builtin::BI__sync_swap_16: + BuiltinIndex = 16; + break; + } + + // Now that we know how many fixed arguments we expect, first check that we + // have at least that many. + if (TheCall->getNumArgs() < 1+NumFixed) { + Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) + << 0 << 1 + NumFixed << TheCall->getNumArgs() + << Callee->getSourceRange(); + return ExprError(); + } + + Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) + << Callee->getSourceRange(); + + if (WarnAboutSemanticsChange) { + Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) + << Callee->getSourceRange(); + } + + // Get the decl for the concrete builtin from this, we can tell what the + // concrete integer type we should convert to is. + unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; + const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); + FunctionDecl *NewBuiltinDecl; + if (NewBuiltinID == BuiltinID) + NewBuiltinDecl = FDecl; + else { + // Perform builtin lookup to avoid redeclaring it. + DeclarationName DN(&Context.Idents.get(NewBuiltinName)); + LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); + LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); + assert(Res.getFoundDecl()); + NewBuiltinDecl = dyn_cast(Res.getFoundDecl()); + if (!NewBuiltinDecl) + return ExprError(); + } + + // The first argument --- the pointer --- has a fixed type; we + // deduce the types of the rest of the arguments accordingly. Walk + // the remaining arguments, converting them to the deduced value type. + for (unsigned i = 0; i != NumFixed; ++i) { + ExprResult Arg = TheCall->getArg(i+1); + + // GCC does an implicit conversion to the pointer or integer ValType. This + // can fail in some cases (1i -> int**), check for this error case now. + // Initialize the argument. + InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, + ValType, /*consume*/ false); + Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); + if (Arg.isInvalid()) + return ExprError(); + + // Okay, we have something that *can* be converted to the right type. Check + // to see if there is a potentially weird extension going on here. This can + // happen when you do an atomic operation on something like an char* and + // pass in 42. The 42 gets converted to char. This is even more strange + // for things like 45.123 -> char, etc. + // FIXME: Do this check. + TheCall->setArg(i+1, Arg.get()); + } + + // Create a new DeclRefExpr to refer to the new decl. + DeclRefExpr *NewDRE = DeclRefExpr::Create( + Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, + /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, + DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); + + // Set the callee in the CallExpr. + // FIXME: This loses syntactic information. + QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); + ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, + CK_BuiltinFnToFnPtr); + TheCall->setCallee(PromotedCall.get()); + + // Change the result type of the call to match the original value type. This + // is arbitrary, but the codegen for these builtins ins design to handle it + // gracefully. + TheCall->setType(ResultType); + + // Prohibit use of _ExtInt with atomic builtins. + // The arguments would have already been converted to the first argument's + // type, so only need to check the first argument. + const auto *ExtIntValType = ValType->getAs(); + if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { + Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); + return ExprError(); + } + + return TheCallResult; + } + + /// SemaBuiltinNontemporalOverloaded - We have a call to + /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an + /// overloaded function based on the pointer type of its last argument. + /// + /// This function goes through and does final semantic checking for these + /// builtins. + ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { + CallExpr *TheCall = (CallExpr *)TheCallResult.get(); + DeclRefExpr *DRE = + cast(TheCall->getCallee()->IgnoreParenCasts()); + FunctionDecl *FDecl = cast(DRE->getDecl()); + unsigned BuiltinID = FDecl->getBuiltinID(); + assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || + BuiltinID == Builtin::BI__builtin_nontemporal_load) && + "Unexpected nontemporal load/store builtin!"); + bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; + unsigned numArgs = isStore ? 2 : 1; + + // Ensure that we have the proper number of arguments. + if (checkArgCount(*this, TheCall, numArgs)) + return ExprError(); + + // Inspect the last argument of the nontemporal builtin. This should always + // be a pointer type, from which we imply the type of the memory access. + // Because it is a pointer type, we don't have to worry about any implicit + // casts here. + Expr *PointerArg = TheCall->getArg(numArgs - 1); + ExprResult PointerArgResult = + DefaultFunctionArrayLvalueConversion(PointerArg); + + if (PointerArgResult.isInvalid()) + return ExprError(); + PointerArg = PointerArgResult.get(); + TheCall->setArg(numArgs - 1, PointerArg); + + const PointerType *pointerType = PointerArg->getType()->getAs(); + if (!pointerType) { + Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) + << PointerArg->getType() << PointerArg->getSourceRange(); + return ExprError(); + } + + QualType ValType = pointerType->getPointeeType(); + + // Strip any qualifiers off ValType. + ValType = ValType.getUnqualifiedType(); + if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && + !ValType->isBlockPointerType() && !ValType->isFloatingType() && + !ValType->isVectorType()) { + Diag(DRE->getBeginLoc(), + diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) + << PointerArg->getType() << PointerArg->getSourceRange(); + return ExprError(); + } + + if (!isStore) { + TheCall->setType(ValType); + return TheCallResult; + } + + ExprResult ValArg = TheCall->getArg(0); + InitializedEntity Entity = InitializedEntity::InitializeParameter( + Context, ValType, /*consume*/ false); + ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); + if (ValArg.isInvalid()) + return ExprError(); + + TheCall->setArg(0, ValArg.get()); + TheCall->setType(Context.VoidTy); + return TheCallResult; + } + + /// CheckObjCString - Checks that the argument to the builtin + /// CFString constructor is correct + /// Note: It might also make sense to do the UTF-16 conversion here (would + /// simplify the backend). + bool Sema::CheckObjCString(Expr *Arg) { + Arg = Arg->IgnoreParenCasts(); + StringLiteral *Literal = dyn_cast(Arg); + + if (!Literal || !Literal->isAscii()) { + Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) + << Arg->getSourceRange(); + return true; + } + + if (Literal->containsNonAsciiOrNull()) { + StringRef String = Literal->getString(); + unsigned NumBytes = String.size(); + SmallVector ToBuf(NumBytes); + const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); + llvm::UTF16 *ToPtr = &ToBuf[0]; + + llvm::ConversionResult Result = + llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, + ToPtr + NumBytes, llvm::strictConversion); + // Check for conversion failure. + if (Result != llvm::conversionOK) + Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) + << Arg->getSourceRange(); + } + return false; + } + + /// CheckObjCString - Checks that the format string argument to the os_log() + /// and os_trace() functions is correct, and converts it to const char *. + ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { + Arg = Arg->IgnoreParenCasts(); + auto *Literal = dyn_cast(Arg); + if (!Literal) { + if (auto *ObjcLiteral = dyn_cast(Arg)) { + Literal = ObjcLiteral->getString(); + } + } + + if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { + return ExprError( + Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) + << Arg->getSourceRange()); + } + + ExprResult Result(Literal); + QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); + InitializedEntity Entity = + InitializedEntity::InitializeParameter(Context, ResultTy, false); + Result = PerformCopyInitialization(Entity, SourceLocation(), Result); + return Result; + } + + /// Check that the user is calling the appropriate va_start builtin for the + /// target and calling convention. + static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { + const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); + bool IsX64 = TT.getArch() == llvm::Triple::x86_64; + bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || + TT.getArch() == llvm::Triple::aarch64_32); + bool IsWindows = TT.isOSWindows(); + bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; + if (IsX64 || IsAArch64) { + CallingConv CC = CC_C; + if (const FunctionDecl *FD = S.getCurFunctionDecl()) + CC = FD->getType()->castAs()->getCallConv(); + if (IsMSVAStart) { + // Don't allow this in System V ABI functions. + if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) + return S.Diag(Fn->getBeginLoc(), + diag::err_ms_va_start_used_in_sysv_function); + } else { + // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. + // On x64 Windows, don't allow this in System V ABI functions. + // (Yes, that means there's no corresponding way to support variadic + // System V ABI functions on Windows.) + if ((IsWindows && CC == CC_X86_64SysV) || + (!IsWindows && CC == CC_Win64)) + return S.Diag(Fn->getBeginLoc(), + diag::err_va_start_used_in_wrong_abi_function) + << !IsWindows; + } + return false; + } + + if (IsMSVAStart) + return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); + return false; + } + + static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, + ParmVarDecl **LastParam = nullptr) { + // Determine whether the current function, block, or obj-c method is variadic + // and get its parameter list. + bool IsVariadic = false; + ArrayRef Params; + DeclContext *Caller = S.CurContext; + if (auto *Block = dyn_cast(Caller)) { + IsVariadic = Block->isVariadic(); + Params = Block->parameters(); + } else if (auto *FD = dyn_cast(Caller)) { + IsVariadic = FD->isVariadic(); + Params = FD->parameters(); + } else if (auto *MD = dyn_cast(Caller)) { + IsVariadic = MD->isVariadic(); + // FIXME: This isn't correct for methods (results in bogus warning). + Params = MD->parameters(); + } else if (isa(Caller)) { + // We don't support va_start in a CapturedDecl. + S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); + return true; + } else { + // This must be some other declcontext that parses exprs. + S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); + return true; + } + + if (!IsVariadic) { + S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); + return true; + } + + if (LastParam) + *LastParam = Params.empty() ? nullptr : Params.back(); + + return false; + } + + /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' + /// for validity. Emit an error and return true on failure; return false + /// on success. + bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { + Expr *Fn = TheCall->getCallee(); + + if (checkVAStartABI(*this, BuiltinID, Fn)) + return true; + + if (checkArgCount(*this, TheCall, 2)) + return true; + + // Type-check the first argument normally. + if (checkBuiltinArgument(*this, TheCall, 0)) + return true; + + // Check that the current function is variadic, and get its last parameter. + ParmVarDecl *LastParam; + if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) + return true; + + // Verify that the second argument to the builtin is the last argument of the + // current function or method. + bool SecondArgIsLastNamedArgument = false; + const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); + + // These are valid if SecondArgIsLastNamedArgument is false after the next + // block. + QualType Type; + SourceLocation ParamLoc; + bool IsCRegister = false; + + if (const DeclRefExpr *DR = dyn_cast(Arg)) { + if (const ParmVarDecl *PV = dyn_cast(DR->getDecl())) { + SecondArgIsLastNamedArgument = PV == LastParam; + + Type = PV->getType(); + ParamLoc = PV->getLocation(); + IsCRegister = + PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; + } + } + + if (!SecondArgIsLastNamedArgument) + Diag(TheCall->getArg(1)->getBeginLoc(), + diag::warn_second_arg_of_va_start_not_last_named_param); + else if (IsCRegister || Type->isReferenceType() || + Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { + // Promotable integers are UB, but enumerations need a bit of + // extra checking to see what their promotable type actually is. + if (!Type->isPromotableIntegerType()) + return false; + if (!Type->isEnumeralType()) + return true; + const EnumDecl *ED = Type->castAs()->getDecl(); + return !(ED && + Context.typesAreCompatible(ED->getPromotionType(), Type)); + }()) { + unsigned Reason = 0; + if (Type->isReferenceType()) Reason = 1; + else if (IsCRegister) Reason = 2; + Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; + Diag(ParamLoc, diag::note_parameter_type) << Type; + } + + TheCall->setType(Context.VoidTy); + return false; + } + + bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { + auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { + const LangOptions &LO = getLangOpts(); + + if (LO.CPlusPlus) + return Arg->getType() + .getCanonicalType() + .getTypePtr() + ->getPointeeType() + .withoutLocalFastQualifiers() == Context.CharTy; + + // In C, allow aliasing through `char *`, this is required for AArch64 at + // least. + return true; + }; + + // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, + // const char *named_addr); + + Expr *Func = Call->getCallee(); + + if (Call->getNumArgs() < 3) + return Diag(Call->getEndLoc(), + diag::err_typecheck_call_too_few_args_at_least) + << 0 /*function call*/ << 3 << Call->getNumArgs(); + + // Type-check the first argument normally. + if (checkBuiltinArgument(*this, Call, 0)) + return true; + + // Check that the current function is variadic. + if (checkVAStartIsInVariadicFunction(*this, Func)) + return true; + + // __va_start on Windows does not validate the parameter qualifiers + + const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); + const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); + + const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); + const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); + + const QualType &ConstCharPtrTy = + Context.getPointerType(Context.CharTy.withConst()); + if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) + Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) + << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ + << 0 /* qualifier difference */ + << 3 /* parameter mismatch */ + << 2 << Arg1->getType() << ConstCharPtrTy; + + const QualType SizeTy = Context.getSizeType(); + if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) + Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) + << Arg2->getType() << SizeTy << 1 /* different class */ + << 0 /* qualifier difference */ + << 3 /* parameter mismatch */ + << 3 << Arg2->getType() << SizeTy; + + return false; + } + + /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and + /// friends. This is declared to take (...), so we have to check everything. + bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { + if (checkArgCount(*this, TheCall, 2)) + return true; + + ExprResult OrigArg0 = TheCall->getArg(0); + ExprResult OrigArg1 = TheCall->getArg(1); + + // Do standard promotions between the two arguments, returning their common + // type. + QualType Res = UsualArithmeticConversions( + OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); + if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) + return true; + + // Make sure any conversions are pushed back into the call; this is + // type safe since unordered compare builtins are declared as "_Bool + // foo(...)". + TheCall->setArg(0, OrigArg0.get()); + TheCall->setArg(1, OrigArg1.get()); + + if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) + return false; + + // If the common type isn't a real floating type, then the arguments were + // invalid for this operation. + if (Res.isNull() || !Res->isRealFloatingType()) + return Diag(OrigArg0.get()->getBeginLoc(), + diag::err_typecheck_call_invalid_ordered_compare) + << OrigArg0.get()->getType() << OrigArg1.get()->getType() + << SourceRange(OrigArg0.get()->getBeginLoc(), + OrigArg1.get()->getEndLoc()); + + return false; + } + + /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like + /// __builtin_isnan and friends. This is declared to take (...), so we have + /// to check everything. We expect the last argument to be a floating point + /// value. + bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { + if (checkArgCount(*this, TheCall, NumArgs)) + return true; + + // __builtin_fpclassify is the only case where NumArgs != 1, so we can count + // on all preceding parameters just being int. Try all of those. + for (unsigned i = 0; i < NumArgs - 1; ++i) { + Expr *Arg = TheCall->getArg(i); + + if (Arg->isTypeDependent()) + return false; + + ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); + + if (Res.isInvalid()) + return true; + TheCall->setArg(i, Res.get()); + } + + Expr *OrigArg = TheCall->getArg(NumArgs-1); + + if (OrigArg->isTypeDependent()) + return false; + + // Usual Unary Conversions will convert half to float, which we want for + // machines that use fp16 conversion intrinsics. Else, we wnat to leave the + // type how it is, but do normal L->Rvalue conversions. + if (Context.getTargetInfo().useFP16ConversionIntrinsics()) + OrigArg = UsualUnaryConversions(OrigArg).get(); + else + OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); + TheCall->setArg(NumArgs - 1, OrigArg); + + // This operation requires a non-_Complex floating-point number. + if (!OrigArg->getType()->isRealFloatingType()) + return Diag(OrigArg->getBeginLoc(), + diag::err_typecheck_call_invalid_unary_fp) + << OrigArg->getType() << OrigArg->getSourceRange(); + + return false; + } + + /// Perform semantic analysis for a call to __builtin_complex. + bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { + if (checkArgCount(*this, TheCall, 2)) + return true; + + bool Dependent = false; + for (unsigned I = 0; I != 2; ++I) { + Expr *Arg = TheCall->getArg(I); + QualType T = Arg->getType(); + if (T->isDependentType()) { + Dependent = true; + continue; + } + + // Despite supporting _Complex int, GCC requires a real floating point type + // for the operands of __builtin_complex. + if (!T->isRealFloatingType()) { + return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) + << Arg->getType() << Arg->getSourceRange(); + } + + ExprResult Converted = DefaultLvalueConversion(Arg); + if (Converted.isInvalid()) + return true; + TheCall->setArg(I, Converted.get()); + } + + if (Dependent) { + TheCall->setType(Context.DependentTy); + return false; + } + + Expr *Real = TheCall->getArg(0); + Expr *Imag = TheCall->getArg(1); + if (!Context.hasSameType(Real->getType(), Imag->getType())) { + return Diag(Real->getBeginLoc(), + diag::err_typecheck_call_different_arg_types) + << Real->getType() << Imag->getType() + << Real->getSourceRange() << Imag->getSourceRange(); + } + + // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; + // don't allow this builtin to form those types either. + // FIXME: Should we allow these types? + if (Real->getType()->isFloat16Type()) + return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) + << "_Float16"; + if (Real->getType()->isHalfType()) + return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) + << "half"; + + TheCall->setType(Context.getComplexType(Real->getType())); + return false; + } + + // Customized Sema Checking for VSX builtins that have the following signature: + // vector [...] builtinName(vector [...], vector [...], const int); + // Which takes the same type of vectors (any legal vector type) for the first + // two arguments and takes compile time constant for the third argument. + // Example builtins are : + // vector double vec_xxpermdi(vector double, vector double, int); + // vector short vec_xxsldwi(vector short, vector short, int); + bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { + unsigned ExpectedNumArgs = 3; + if (checkArgCount(*this, TheCall, ExpectedNumArgs)) + return true; + + // Check the third argument is a compile time constant + if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) + return Diag(TheCall->getBeginLoc(), + diag::err_vsx_builtin_nonconstant_argument) + << 3 /* argument index */ << TheCall->getDirectCallee() + << SourceRange(TheCall->getArg(2)->getBeginLoc(), + TheCall->getArg(2)->getEndLoc()); + + QualType Arg1Ty = TheCall->getArg(0)->getType(); + QualType Arg2Ty = TheCall->getArg(1)->getType(); + + // Check the type of argument 1 and argument 2 are vectors. + SourceLocation BuiltinLoc = TheCall->getBeginLoc(); + if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || + (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { + return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) + << TheCall->getDirectCallee() + << SourceRange(TheCall->getArg(0)->getBeginLoc(), + TheCall->getArg(1)->getEndLoc()); + } + + // Check the first two arguments are the same type. + if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { + return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) + << TheCall->getDirectCallee() + << SourceRange(TheCall->getArg(0)->getBeginLoc(), + TheCall->getArg(1)->getEndLoc()); + } + + // When default clang type checking is turned off and the customized type + // checking is used, the returning type of the function must be explicitly + // set. Otherwise it is _Bool by default. + TheCall->setType(Arg1Ty); + + return false; + } + + /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. + // This is declared to take (...), so we have to check everything. + ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { + if (TheCall->getNumArgs() < 2) + return ExprError(Diag(TheCall->getEndLoc(), + diag::err_typecheck_call_too_few_args_at_least) + << 0 /*function call*/ << 2 << TheCall->getNumArgs() + << TheCall->getSourceRange()); + + // Determine which of the following types of shufflevector we're checking: + // 1) unary, vector mask: (lhs, mask) + // 2) binary, scalar mask: (lhs, rhs, index, ..., index) + QualType resType = TheCall->getArg(0)->getType(); + unsigned numElements = 0; + + if (!TheCall->getArg(0)->isTypeDependent() && + !TheCall->getArg(1)->isTypeDependent()) { + QualType LHSType = TheCall->getArg(0)->getType(); + QualType RHSType = TheCall->getArg(1)->getType(); + + if (!LHSType->isVectorType() || !RHSType->isVectorType()) + return ExprError( + Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) + << TheCall->getDirectCallee() + << SourceRange(TheCall->getArg(0)->getBeginLoc(), + TheCall->getArg(1)->getEndLoc())); + + numElements = LHSType->castAs()->getNumElements(); + unsigned numResElements = TheCall->getNumArgs() - 2; + + // Check to see if we have a call with 2 vector arguments, the unary shuffle + // with mask. If so, verify that RHS is an integer vector type with the + // same number of elts as lhs. + if (TheCall->getNumArgs() == 2) { + if (!RHSType->hasIntegerRepresentation() || + RHSType->castAs()->getNumElements() != numElements) + return ExprError(Diag(TheCall->getBeginLoc(), + diag::err_vec_builtin_incompatible_vector) + << TheCall->getDirectCallee() + << SourceRange(TheCall->getArg(1)->getBeginLoc(), + TheCall->getArg(1)->getEndLoc())); + } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { + return ExprError(Diag(TheCall->getBeginLoc(), + diag::err_vec_builtin_incompatible_vector) + << TheCall->getDirectCallee() + << SourceRange(TheCall->getArg(0)->getBeginLoc(), + TheCall->getArg(1)->getEndLoc())); + } else if (numElements != numResElements) { + QualType eltType = LHSType->castAs()->getElementType(); + resType = Context.getVectorType(eltType, numResElements, + VectorType::GenericVector); + } + } + + for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { + if (TheCall->getArg(i)->isTypeDependent() || + TheCall->getArg(i)->isValueDependent()) + continue; + + Optional Result; + if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) + return ExprError(Diag(TheCall->getBeginLoc(), + diag::err_shufflevector_nonconstant_argument) + << TheCall->getArg(i)->getSourceRange()); + + // Allow -1 which will be translated to undef in the IR. + if (Result->isSigned() && Result->isAllOnesValue()) + continue; + + if (Result->getActiveBits() > 64 || + Result->getZExtValue() >= numElements * 2) + return ExprError(Diag(TheCall->getBeginLoc(), + diag::err_shufflevector_argument_too_large) + << TheCall->getArg(i)->getSourceRange()); + } + + SmallVector exprs; + + for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { + exprs.push_back(TheCall->getArg(i)); + TheCall->setArg(i, nullptr); + } + + return new (Context) ShuffleVectorExpr(Context, exprs, resType, + TheCall->getCallee()->getBeginLoc(), + TheCall->getRParenLoc()); + } + + /// SemaConvertVectorExpr - Handle __builtin_convertvector + ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, + SourceLocation BuiltinLoc, + SourceLocation RParenLoc) { + ExprValueKind VK = VK_PRValue; + ExprObjectKind OK = OK_Ordinary; + QualType DstTy = TInfo->getType(); + QualType SrcTy = E->getType(); + + if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) + return ExprError(Diag(BuiltinLoc, + diag::err_convertvector_non_vector) + << E->getSourceRange()); + if (!DstTy->isVectorType() && !DstTy->isDependentType()) + return ExprError(Diag(BuiltinLoc, + diag::err_convertvector_non_vector_type)); + + if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { + unsigned SrcElts = SrcTy->castAs()->getNumElements(); + unsigned DstElts = DstTy->castAs()->getNumElements(); + if (SrcElts != DstElts) + return ExprError(Diag(BuiltinLoc, + diag::err_convertvector_incompatible_vector) + << E->getSourceRange()); + } + + return new (Context) + ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); + } + + /// SemaBuiltinPrefetch - Handle __builtin_prefetch. + // This is declared to take (const void*, ...) and can take two + // optional constant int args. + bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { + unsigned NumArgs = TheCall->getNumArgs(); + + if (NumArgs > 3) + return Diag(TheCall->getEndLoc(), + diag::err_typecheck_call_too_many_args_at_most) + << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); + + // Argument 0 is checked for us and the remaining arguments must be + // constant integers. + for (unsigned i = 1; i != NumArgs; ++i) + if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) + return true; + + return false; + } + + /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. + bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { + if (!Context.getTargetInfo().checkArithmeticFenceSupported()) + return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) + << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); + if (checkArgCount(*this, TheCall, 1)) + return true; + Expr *Arg = TheCall->getArg(0); + if (Arg->isInstantiationDependent()) + return false; + + QualType ArgTy = Arg->getType(); + if (!ArgTy->hasFloatingRepresentation()) + return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) + << ArgTy; + if (Arg->isLValue()) { + ExprResult FirstArg = DefaultLvalueConversion(Arg); + TheCall->setArg(0, FirstArg.get()); + } + TheCall->setType(TheCall->getArg(0)->getType()); + return false; + } + + /// SemaBuiltinAssume - Handle __assume (MS Extension). + // __assume does not evaluate its arguments, and should warn if its argument + // has side effects. + bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { + Expr *Arg = TheCall->getArg(0); + if (Arg->isInstantiationDependent()) return false; + + if (Arg->HasSideEffects(Context)) + Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) + << Arg->getSourceRange() + << cast(TheCall->getCalleeDecl())->getIdentifier(); + + return false; + } + + /// Handle __builtin_alloca_with_align. This is declared + /// as (size_t, size_t) where the second size_t must be a power of 2 greater + /// than 8. + bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { + // The alignment must be a constant integer. + Expr *Arg = TheCall->getArg(1); + + // We can't check the value of a dependent argument. + if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { + if (const auto *UE = + dyn_cast(Arg->IgnoreParenImpCasts())) + if (UE->getKind() == UETT_AlignOf || + UE->getKind() == UETT_PreferredAlignOf) + Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) + << Arg->getSourceRange(); + + llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); + + if (!Result.isPowerOf2()) + return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) + << Arg->getSourceRange(); + + if (Result < Context.getCharWidth()) + return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) + << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); + + if (Result > std::numeric_limits::max()) + return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) + << std::numeric_limits::max() << Arg->getSourceRange(); + } + + return false; + } + + /// Handle __builtin_assume_aligned. This is declared + /// as (const void*, size_t, ...) and can take one optional constant int arg. + bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { + unsigned NumArgs = TheCall->getNumArgs(); + + if (NumArgs > 3) + return Diag(TheCall->getEndLoc(), + diag::err_typecheck_call_too_many_args_at_most) + << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); + + // The alignment must be a constant integer. + Expr *Arg = TheCall->getArg(1); + + // We can't check the value of a dependent argument. + if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { + llvm::APSInt Result; + if (SemaBuiltinConstantArg(TheCall, 1, Result)) + return true; + + if (!Result.isPowerOf2()) + return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) + << Arg->getSourceRange(); + + if (Result > Sema::MaximumAlignment) + Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) + << Arg->getSourceRange() << Sema::MaximumAlignment; + } + + if (NumArgs > 2) { + ExprResult Arg(TheCall->getArg(2)); + InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, + Context.getSizeType(), false); + Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); + if (Arg.isInvalid()) return true; + TheCall->setArg(2, Arg.get()); + } + + return false; + } + + bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { + unsigned BuiltinID = + cast(TheCall->getCalleeDecl())->getBuiltinID(); + bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; + + unsigned NumArgs = TheCall->getNumArgs(); + unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; + if (NumArgs < NumRequiredArgs) { + return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) + << 0 /* function call */ << NumRequiredArgs << NumArgs + << TheCall->getSourceRange(); + } + if (NumArgs >= NumRequiredArgs + 0x100) { + return Diag(TheCall->getEndLoc(), + diag::err_typecheck_call_too_many_args_at_most) + << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs + << TheCall->getSourceRange(); + } + unsigned i = 0; + + // For formatting call, check buffer arg. + if (!IsSizeCall) { + ExprResult Arg(TheCall->getArg(i)); + InitializedEntity Entity = InitializedEntity::InitializeParameter( + Context, Context.VoidPtrTy, false); + Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); + if (Arg.isInvalid()) + return true; + TheCall->setArg(i, Arg.get()); + i++; + } + + // Check string literal arg. + unsigned FormatIdx = i; + { + ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); + if (Arg.isInvalid()) + return true; + TheCall->setArg(i, Arg.get()); + i++; + } + + // Make sure variadic args are scalar. + unsigned FirstDataArg = i; + while (i < NumArgs) { + ExprResult Arg = DefaultVariadicArgumentPromotion( + TheCall->getArg(i), VariadicFunction, nullptr); + if (Arg.isInvalid()) + return true; + CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); + if (ArgSize.getQuantity() >= 0x100) { + return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) + << i << (int)ArgSize.getQuantity() << 0xff + << TheCall->getSourceRange(); + } + TheCall->setArg(i, Arg.get()); + i++; + } + + // Check formatting specifiers. NOTE: We're only doing this for the non-size + // call to avoid duplicate diagnostics. + if (!IsSizeCall) { + llvm::SmallBitVector CheckedVarArgs(NumArgs, false); + ArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs()); + bool Success = CheckFormatArguments( + Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, + VariadicFunction, TheCall->getBeginLoc(), SourceRange(), + CheckedVarArgs); + if (!Success) + return true; + } + + if (IsSizeCall) { + TheCall->setType(Context.getSizeType()); + } else { + TheCall->setType(Context.VoidPtrTy); + } + return false; + } + + /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr + /// TheCall is a constant expression. + bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, + llvm::APSInt &Result) { + Expr *Arg = TheCall->getArg(ArgNum); + DeclRefExpr *DRE =cast(TheCall->getCallee()->IgnoreParenCasts()); + FunctionDecl *FDecl = cast(DRE->getDecl()); + + if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; + + Optional R; + if (!(R = Arg->getIntegerConstantExpr(Context))) + return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) + << FDecl->getDeclName() << Arg->getSourceRange(); + Result = *R; + return false; + } + + /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr + /// TheCall is a constant expression in the range [Low, High]. + bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, + int Low, int High, bool RangeIsError) { + if (isConstantEvaluated()) + return false; + llvm::APSInt Result; + + // We can't check the value of a dependent argument. + Expr *Arg = TheCall->getArg(ArgNum); + if (Arg->isTypeDependent() || Arg->isValueDependent()) + return false; + + // Check constant-ness first. + if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) + return true; + + if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { + if (RangeIsError) + return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) + << toString(Result, 10) << Low << High << Arg->getSourceRange(); + else + // Defer the warning until we know if the code will be emitted so that + // dead code can ignore this. + DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, + PDiag(diag::warn_argument_invalid_range) + << toString(Result, 10) << Low << High + << Arg->getSourceRange()); + } + + return false; + } + + /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr + /// TheCall is a constant expression is a multiple of Num.. + bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, + unsigned Num) { + llvm::APSInt Result; + + // We can't check the value of a dependent argument. + Expr *Arg = TheCall->getArg(ArgNum); + if (Arg->isTypeDependent() || Arg->isValueDependent()) + return false; + + // Check constant-ness first. + if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) + return true; + + if (Result.getSExtValue() % Num != 0) + return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) + << Num << Arg->getSourceRange(); + + return false; + } + + /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a + /// constant expression representing a power of 2. + bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { + llvm::APSInt Result; + + // We can't check the value of a dependent argument. + Expr *Arg = TheCall->getArg(ArgNum); + if (Arg->isTypeDependent() || Arg->isValueDependent()) + return false; + + // Check constant-ness first. + if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) + return true; + + // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if + // and only if x is a power of 2. + if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) + return false; + + return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) + << Arg->getSourceRange(); + } + + static bool IsShiftedByte(llvm::APSInt Value) { + if (Value.isNegative()) + return false; + + // Check if it's a shifted byte, by shifting it down + while (true) { + // If the value fits in the bottom byte, the check passes. + if (Value < 0x100) + return true; + + // Otherwise, if the value has _any_ bits in the bottom byte, the check + // fails. + if ((Value & 0xFF) != 0) + return false; + + // If the bottom 8 bits are all 0, but something above that is nonzero, + // then shifting the value right by 8 bits won't affect whether it's a + // shifted byte or not. So do that, and go round again. + Value >>= 8; + } + } + + /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is + /// a constant expression representing an arbitrary byte value shifted left by + /// a multiple of 8 bits. + bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, + unsigned ArgBits) { + llvm::APSInt Result; + + // We can't check the value of a dependent argument. + Expr *Arg = TheCall->getArg(ArgNum); + if (Arg->isTypeDependent() || Arg->isValueDependent()) + return false; + + // Check constant-ness first. + if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) + return true; + + // Truncate to the given size. + Result = Result.getLoBits(ArgBits); + Result.setIsUnsigned(true); + + if (IsShiftedByte(Result)) + return false; + + return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) + << Arg->getSourceRange(); + } + + /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of + /// TheCall is a constant expression representing either a shifted byte value, + /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression + /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some + /// Arm MVE intrinsics. + bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, + int ArgNum, + unsigned ArgBits) { + llvm::APSInt Result; + + // We can't check the value of a dependent argument. + Expr *Arg = TheCall->getArg(ArgNum); + if (Arg->isTypeDependent() || Arg->isValueDependent()) + return false; + + // Check constant-ness first. + if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) + return true; + + // Truncate to the given size. + Result = Result.getLoBits(ArgBits); + Result.setIsUnsigned(true); + + // Check to see if it's in either of the required forms. + if (IsShiftedByte(Result) || + (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) + return false; + + return Diag(TheCall->getBeginLoc(), + diag::err_argument_not_shifted_byte_or_xxff) + << Arg->getSourceRange(); + } + + /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions + bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { + if (BuiltinID == AArch64::BI__builtin_arm_irg) { + if (checkArgCount(*this, TheCall, 2)) + return true; + Expr *Arg0 = TheCall->getArg(0); + Expr *Arg1 = TheCall->getArg(1); + + ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); + if (FirstArg.isInvalid()) + return true; + QualType FirstArgType = FirstArg.get()->getType(); + if (!FirstArgType->isAnyPointerType()) + return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) + << "first" << FirstArgType << Arg0->getSourceRange(); + TheCall->setArg(0, FirstArg.get()); + + ExprResult SecArg = DefaultLvalueConversion(Arg1); + if (SecArg.isInvalid()) + return true; + QualType SecArgType = SecArg.get()->getType(); + if (!SecArgType->isIntegerType()) + return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) + << "second" << SecArgType << Arg1->getSourceRange(); + + // Derive the return type from the pointer argument. + TheCall->setType(FirstArgType); + return false; + } + + if (BuiltinID == AArch64::BI__builtin_arm_addg) { + if (checkArgCount(*this, TheCall, 2)) + return true; + + Expr *Arg0 = TheCall->getArg(0); + ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); + if (FirstArg.isInvalid()) + return true; + QualType FirstArgType = FirstArg.get()->getType(); + if (!FirstArgType->isAnyPointerType()) + return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) + << "first" << FirstArgType << Arg0->getSourceRange(); + TheCall->setArg(0, FirstArg.get()); + + // Derive the return type from the pointer argument. + TheCall->setType(FirstArgType); + + // Second arg must be an constant in range [0,15] + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); + } + + if (BuiltinID == AArch64::BI__builtin_arm_gmi) { + if (checkArgCount(*this, TheCall, 2)) + return true; + Expr *Arg0 = TheCall->getArg(0); + Expr *Arg1 = TheCall->getArg(1); + + ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); + if (FirstArg.isInvalid()) + return true; + QualType FirstArgType = FirstArg.get()->getType(); + if (!FirstArgType->isAnyPointerType()) + return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) + << "first" << FirstArgType << Arg0->getSourceRange(); + + QualType SecArgType = Arg1->getType(); + if (!SecArgType->isIntegerType()) + return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) + << "second" << SecArgType << Arg1->getSourceRange(); + TheCall->setType(Context.IntTy); + return false; + } + + if (BuiltinID == AArch64::BI__builtin_arm_ldg || + BuiltinID == AArch64::BI__builtin_arm_stg) { + if (checkArgCount(*this, TheCall, 1)) + return true; + Expr *Arg0 = TheCall->getArg(0); + ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); + if (FirstArg.isInvalid()) + return true; + + QualType FirstArgType = FirstArg.get()->getType(); + if (!FirstArgType->isAnyPointerType()) + return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) + << "first" << FirstArgType << Arg0->getSourceRange(); + TheCall->setArg(0, FirstArg.get()); + + // Derive the return type from the pointer argument. + if (BuiltinID == AArch64::BI__builtin_arm_ldg) + TheCall->setType(FirstArgType); + return false; + } + + if (BuiltinID == AArch64::BI__builtin_arm_subp) { + Expr *ArgA = TheCall->getArg(0); + Expr *ArgB = TheCall->getArg(1); + + ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); + ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); + + if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) + return true; + + QualType ArgTypeA = ArgExprA.get()->getType(); + QualType ArgTypeB = ArgExprB.get()->getType(); + + auto isNull = [&] (Expr *E) -> bool { + return E->isNullPointerConstant( + Context, Expr::NPC_ValueDependentIsNotNull); }; + + // argument should be either a pointer or null + if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) + return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) + << "first" << ArgTypeA << ArgA->getSourceRange(); + + if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) + return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) + << "second" << ArgTypeB << ArgB->getSourceRange(); + + // Ensure Pointee types are compatible + if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && + ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { + QualType pointeeA = ArgTypeA->getPointeeType(); + QualType pointeeB = ArgTypeB->getPointeeType(); + if (!Context.typesAreCompatible( + Context.getCanonicalType(pointeeA).getUnqualifiedType(), + Context.getCanonicalType(pointeeB).getUnqualifiedType())) { + return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) + << ArgTypeA << ArgTypeB << ArgA->getSourceRange() + << ArgB->getSourceRange(); + } + } + + // at least one argument should be pointer type + if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) + return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) + << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); + + if (isNull(ArgA)) // adopt type of the other pointer + ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); + + if (isNull(ArgB)) + ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); + + TheCall->setArg(0, ArgExprA.get()); + TheCall->setArg(1, ArgExprB.get()); + TheCall->setType(Context.LongLongTy); + return false; + } + assert(false && "Unhandled ARM MTE intrinsic"); + return true; + } + + /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr + /// TheCall is an ARM/AArch64 special register string literal. + bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, + int ArgNum, unsigned ExpectedFieldNum, + bool AllowName) { + bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || + BuiltinID == ARM::BI__builtin_arm_wsr64 || + BuiltinID == ARM::BI__builtin_arm_rsr || + BuiltinID == ARM::BI__builtin_arm_rsrp || + BuiltinID == ARM::BI__builtin_arm_wsr || + BuiltinID == ARM::BI__builtin_arm_wsrp; + bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || + BuiltinID == AArch64::BI__builtin_arm_wsr64 || + BuiltinID == AArch64::BI__builtin_arm_rsr || + BuiltinID == AArch64::BI__builtin_arm_rsrp || + BuiltinID == AArch64::BI__builtin_arm_wsr || + BuiltinID == AArch64::BI__builtin_arm_wsrp; + assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); + + // We can't check the value of a dependent argument. + Expr *Arg = TheCall->getArg(ArgNum); + if (Arg->isTypeDependent() || Arg->isValueDependent()) + return false; + + // Check if the argument is a string literal. + if (!isa(Arg->IgnoreParenImpCasts())) + return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) + << Arg->getSourceRange(); + + // Check the type of special register given. + StringRef Reg = cast(Arg->IgnoreParenImpCasts())->getString(); + SmallVector Fields; + Reg.split(Fields, ":"); + + if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) + return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) + << Arg->getSourceRange(); + + // If the string is the name of a register then we cannot check that it is + // valid here but if the string is of one the forms described in ACLE then we + // can check that the supplied fields are integers and within the valid + // ranges. + if (Fields.size() > 1) { + bool FiveFields = Fields.size() == 5; + + bool ValidString = true; + if (IsARMBuiltin) { + ValidString &= Fields[0].startswith_insensitive("cp") || + Fields[0].startswith_insensitive("p"); + if (ValidString) + Fields[0] = Fields[0].drop_front( + Fields[0].startswith_insensitive("cp") ? 2 : 1); + + ValidString &= Fields[2].startswith_insensitive("c"); + if (ValidString) + Fields[2] = Fields[2].drop_front(1); + + if (FiveFields) { + ValidString &= Fields[3].startswith_insensitive("c"); + if (ValidString) + Fields[3] = Fields[3].drop_front(1); + } + } + + SmallVector Ranges; + if (FiveFields) + Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); + else + Ranges.append({15, 7, 15}); + + for (unsigned i=0; i= 0 && IntField <= Ranges[i]); + } + + if (!ValidString) + return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) + << Arg->getSourceRange(); + } else if (IsAArch64Builtin && Fields.size() == 1) { + // If the register name is one of those that appear in the condition below + // and the special register builtin being used is one of the write builtins, + // then we require that the argument provided for writing to the register + // is an integer constant expression. This is because it will be lowered to + // an MSR (immediate) instruction, so we need to know the immediate at + // compile time. + if (TheCall->getNumArgs() != 2) + return false; + + std::string RegLower = Reg.lower(); + if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && + RegLower != "pan" && RegLower != "uao") + return false; + + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); + } + + return false; + } + + /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. + /// Emit an error and return true on failure; return false on success. + /// TypeStr is a string containing the type descriptor of the value returned by + /// the builtin and the descriptors of the expected type of the arguments. + bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { + + assert((TypeStr[0] != '\0') && + "Invalid types in PPC MMA builtin declaration"); + + unsigned Mask = 0; + unsigned ArgNum = 0; + + // The first type in TypeStr is the type of the value returned by the + // builtin. So we first read that type and change the type of TheCall. + QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); + TheCall->setType(type); + + while (*TypeStr != '\0') { + Mask = 0; + QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); + if (ArgNum >= TheCall->getNumArgs()) { + ArgNum++; + break; + } + + Expr *Arg = TheCall->getArg(ArgNum); + QualType ArgType = Arg->getType(); + + if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || + (!ExpectedType->isVoidPointerType() && + ArgType.getCanonicalType() != ExpectedType)) + return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) + << ArgType << ExpectedType << 1 << 0 << 0; + + // If the value of the Mask is not 0, we have a constraint in the size of + // the integer argument so here we ensure the argument is a constant that + // is in the valid range. + if (Mask != 0 && + SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) + return true; + + ArgNum++; + } + + // In case we exited early from the previous loop, there are other types to + // read from TypeStr. So we need to read them all to ensure we have the right + // number of arguments in TheCall and if it is not the case, to display a + // better error message. + while (*TypeStr != '\0') { + (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); + ArgNum++; + } + if (checkArgCount(*this, TheCall, ArgNum)) + return true; + + return false; + } + + /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). + /// This checks that the target supports __builtin_longjmp and + /// that val is a constant 1. + bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { + if (!Context.getTargetInfo().hasSjLjLowering()) + return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) + << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); + + Expr *Arg = TheCall->getArg(1); + llvm::APSInt Result; + + // TODO: This is less than ideal. Overload this to take a value. + if (SemaBuiltinConstantArg(TheCall, 1, Result)) + return true; + + if (Result != 1) + return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) + << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); + + return false; + } + + /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). + /// This checks that the target supports __builtin_setjmp. + bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { + if (!Context.getTargetInfo().hasSjLjLowering()) + return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) + << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); + return false; + } + + namespace { + + class UncoveredArgHandler { + enum { Unknown = -1, AllCovered = -2 }; + + signed FirstUncoveredArg = Unknown; + SmallVector DiagnosticExprs; + + public: + UncoveredArgHandler() = default; + + bool hasUncoveredArg() const { + return (FirstUncoveredArg >= 0); + } + + unsigned getUncoveredArg() const { + assert(hasUncoveredArg() && "no uncovered argument"); + return FirstUncoveredArg; + } + + void setAllCovered() { + // A string has been found with all arguments covered, so clear out + // the diagnostics. + DiagnosticExprs.clear(); + FirstUncoveredArg = AllCovered; + } + + void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { + assert(NewFirstUncoveredArg >= 0 && "Outside range"); + + // Don't update if a previous string covers all arguments. + if (FirstUncoveredArg == AllCovered) + return; + + // UncoveredArgHandler tracks the highest uncovered argument index + // and with it all the strings that match this index. + if (NewFirstUncoveredArg == FirstUncoveredArg) + DiagnosticExprs.push_back(StrExpr); + else if (NewFirstUncoveredArg > FirstUncoveredArg) { + DiagnosticExprs.clear(); + DiagnosticExprs.push_back(StrExpr); + FirstUncoveredArg = NewFirstUncoveredArg; + } + } + + void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); + }; + + enum StringLiteralCheckType { + SLCT_NotALiteral, + SLCT_UncheckedLiteral, + SLCT_CheckedLiteral + }; + + } // namespace + + static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, + BinaryOperatorKind BinOpKind, + bool AddendIsRight) { + unsigned BitWidth = Offset.getBitWidth(); + unsigned AddendBitWidth = Addend.getBitWidth(); + // There might be negative interim results. + if (Addend.isUnsigned()) { + Addend = Addend.zext(++AddendBitWidth); + Addend.setIsSigned(true); + } + // Adjust the bit width of the APSInts. + if (AddendBitWidth > BitWidth) { + Offset = Offset.sext(AddendBitWidth); + BitWidth = AddendBitWidth; + } else if (BitWidth > AddendBitWidth) { + Addend = Addend.sext(BitWidth); + } + + bool Ov = false; + llvm::APSInt ResOffset = Offset; + if (BinOpKind == BO_Add) + ResOffset = Offset.sadd_ov(Addend, Ov); + else { + assert(AddendIsRight && BinOpKind == BO_Sub && + "operator must be add or sub with addend on the right"); + ResOffset = Offset.ssub_ov(Addend, Ov); + } + + // We add an offset to a pointer here so we should support an offset as big as + // possible. + if (Ov) { + assert(BitWidth <= std::numeric_limits::max() / 2 && + "index (intermediate) result too big"); + Offset = Offset.sext(2 * BitWidth); + sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); + return; + } + + Offset = ResOffset; + } + + namespace { + + // This is a wrapper class around StringLiteral to support offsetted string + // literals as format strings. It takes the offset into account when returning + // the string and its length or the source locations to display notes correctly. + class FormatStringLiteral { + const StringLiteral *FExpr; + int64_t Offset; + + public: + FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) + : FExpr(fexpr), Offset(Offset) {} + + StringRef getString() const { + return FExpr->getString().drop_front(Offset); + } + + unsigned getByteLength() const { + return FExpr->getByteLength() - getCharByteWidth() * Offset; + } + + unsigned getLength() const { return FExpr->getLength() - Offset; } + unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } + + StringLiteral::StringKind getKind() const { return FExpr->getKind(); } + + QualType getType() const { return FExpr->getType(); } + + bool isAscii() const { return FExpr->isAscii(); } + bool isWide() const { return FExpr->isWide(); } + bool isUTF8() const { return FExpr->isUTF8(); } + bool isUTF16() const { return FExpr->isUTF16(); } + bool isUTF32() const { return FExpr->isUTF32(); } + bool isPascal() const { return FExpr->isPascal(); } + + SourceLocation getLocationOfByte( + unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, + const TargetInfo &Target, unsigned *StartToken = nullptr, + unsigned *StartTokenByteOffset = nullptr) const { + return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, + StartToken, StartTokenByteOffset); + } + + SourceLocation getBeginLoc() const LLVM_READONLY { + return FExpr->getBeginLoc().getLocWithOffset(Offset); + } + + SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } + }; + + } // namespace + + static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, + const Expr *OrigFormatExpr, + ArrayRef Args, + bool HasVAListArg, unsigned format_idx, + unsigned firstDataArg, + Sema::FormatStringType Type, + bool inFunctionCall, + Sema::VariadicCallType CallType, + llvm::SmallBitVector &CheckedVarArgs, + UncoveredArgHandler &UncoveredArg, + bool IgnoreStringsWithoutSpecifiers); + + // Determine if an expression is a string literal or constant string. + // If this function returns false on the arguments to a function expecting a + // format string, we will usually need to emit a warning. + // True string literals are then checked by CheckFormatString. + static StringLiteralCheckType + checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef Args, + bool HasVAListArg, unsigned format_idx, + unsigned firstDataArg, Sema::FormatStringType Type, + Sema::VariadicCallType CallType, bool InFunctionCall, + llvm::SmallBitVector &CheckedVarArgs, + UncoveredArgHandler &UncoveredArg, + llvm::APSInt Offset, + bool IgnoreStringsWithoutSpecifiers = false) { + if (S.isConstantEvaluated()) + return SLCT_NotALiteral; + tryAgain: + assert(Offset.isSigned() && "invalid offset"); + + if (E->isTypeDependent() || E->isValueDependent()) + return SLCT_NotALiteral; + + E = E->IgnoreParenCasts(); + + if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) + // Technically -Wformat-nonliteral does not warn about this case. + // The behavior of printf and friends in this case is implementation + // dependent. Ideally if the format string cannot be null then + // it should have a 'nonnull' attribute in the function prototype. + return SLCT_UncheckedLiteral; + + switch (E->getStmtClass()) { + case Stmt::BinaryConditionalOperatorClass: + case Stmt::ConditionalOperatorClass: { + // The expression is a literal if both sub-expressions were, and it was + // completely checked only if both sub-expressions were checked. + const AbstractConditionalOperator *C = + cast(E); + + // Determine whether it is necessary to check both sub-expressions, for + // example, because the condition expression is a constant that can be + // evaluated at compile time. + bool CheckLeft = true, CheckRight = true; + + bool Cond; + if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), + S.isConstantEvaluated())) { + if (Cond) + CheckRight = false; + else + CheckLeft = false; + } + + // We need to maintain the offsets for the right and the left hand side + // separately to check if every possible indexed expression is a valid + // string literal. They might have different offsets for different string + // literals in the end. + StringLiteralCheckType Left; + if (!CheckLeft) + Left = SLCT_UncheckedLiteral; + else { + Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, + HasVAListArg, format_idx, firstDataArg, + Type, CallType, InFunctionCall, + CheckedVarArgs, UncoveredArg, Offset, + IgnoreStringsWithoutSpecifiers); + if (Left == SLCT_NotALiteral || !CheckRight) { + return Left; + } + } + + StringLiteralCheckType Right = checkFormatStringExpr( + S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, + Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, + IgnoreStringsWithoutSpecifiers); + + return (CheckLeft && Left < Right) ? Left : Right; + } + + case Stmt::ImplicitCastExprClass: + E = cast(E)->getSubExpr(); + goto tryAgain; + + case Stmt::OpaqueValueExprClass: + if (const Expr *src = cast(E)->getSourceExpr()) { + E = src; + goto tryAgain; + } + return SLCT_NotALiteral; + + case Stmt::PredefinedExprClass: + // While __func__, etc., are technically not string literals, they + // cannot contain format specifiers and thus are not a security + // liability. + return SLCT_UncheckedLiteral; + + case Stmt::DeclRefExprClass: { + const DeclRefExpr *DR = cast(E); + + // As an exception, do not flag errors for variables binding to + // const string literals. + if (const VarDecl *VD = dyn_cast(DR->getDecl())) { + bool isConstant = false; + QualType T = DR->getType(); + + if (const ArrayType *AT = S.Context.getAsArrayType(T)) { + isConstant = AT->getElementType().isConstant(S.Context); + } else if (const PointerType *PT = T->getAs()) { + isConstant = T.isConstant(S.Context) && + PT->getPointeeType().isConstant(S.Context); + } else if (T->isObjCObjectPointerType()) { + // In ObjC, there is usually no "const ObjectPointer" type, + // so don't check if the pointee type is constant. + isConstant = T.isConstant(S.Context); + } + + if (isConstant) { + if (const Expr *Init = VD->getAnyInitializer()) { + // Look through initializers like const char c[] = { "foo" } + if (const InitListExpr *InitList = dyn_cast(Init)) { + if (InitList->isStringLiteralInit()) + Init = InitList->getInit(0)->IgnoreParenImpCasts(); + } + return checkFormatStringExpr(S, Init, Args, + HasVAListArg, format_idx, + firstDataArg, Type, CallType, + /*InFunctionCall*/ false, CheckedVarArgs, + UncoveredArg, Offset); + } + } + + // For vprintf* functions (i.e., HasVAListArg==true), we add a + // special check to see if the format string is a function parameter + // of the function calling the printf function. If the function + // has an attribute indicating it is a printf-like function, then we + // should suppress warnings concerning non-literals being used in a call + // to a vprintf function. For example: + // + // void + // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ + // va_list ap; + // va_start(ap, fmt); + // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". + // ... + // } + if (HasVAListArg) { + if (const ParmVarDecl *PV = dyn_cast(VD)) { + if (const NamedDecl *ND = dyn_cast(PV->getDeclContext())) { + int PVIndex = PV->getFunctionScopeIndex() + 1; + for (const auto *PVFormat : ND->specific_attrs()) { + // adjust for implicit parameter + if (const CXXMethodDecl *MD = dyn_cast(ND)) + if (MD->isInstance()) + ++PVIndex; + // We also check if the formats are compatible. + // We can't pass a 'scanf' string to a 'printf' function. + if (PVIndex == PVFormat->getFormatIdx() && + Type == S.GetFormatStringType(PVFormat)) + return SLCT_UncheckedLiteral; + } + } + } + } + } + + return SLCT_NotALiteral; + } + + case Stmt::CallExprClass: + case Stmt::CXXMemberCallExprClass: { + const CallExpr *CE = cast(E); + if (const NamedDecl *ND = dyn_cast_or_null(CE->getCalleeDecl())) { + bool IsFirst = true; + StringLiteralCheckType CommonResult; + for (const auto *FA : ND->specific_attrs()) { + const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); + StringLiteralCheckType Result = checkFormatStringExpr( + S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, + CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, + IgnoreStringsWithoutSpecifiers); + if (IsFirst) { + CommonResult = Result; + IsFirst = false; + } + } + if (!IsFirst) + return CommonResult; + + if (const auto *FD = dyn_cast(ND)) { + unsigned BuiltinID = FD->getBuiltinID(); + if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || + BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { + const Expr *Arg = CE->getArg(0); + return checkFormatStringExpr(S, Arg, Args, + HasVAListArg, format_idx, + firstDataArg, Type, CallType, + InFunctionCall, CheckedVarArgs, + UncoveredArg, Offset, + IgnoreStringsWithoutSpecifiers); + } + } + } + + return SLCT_NotALiteral; + } + case Stmt::ObjCMessageExprClass: { + const auto *ME = cast(E); + if (const auto *MD = ME->getMethodDecl()) { + if (const auto *FA = MD->getAttr()) { + // As a special case heuristic, if we're using the method -[NSBundle + // localizedStringForKey:value:table:], ignore any key strings that lack + // format specifiers. The idea is that if the key doesn't have any + // format specifiers then its probably just a key to map to the + // localized strings. If it does have format specifiers though, then its + // likely that the text of the key is the format string in the + // programmer's language, and should be checked. + const ObjCInterfaceDecl *IFace; + if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && + IFace->getIdentifier()->isStr("NSBundle") && + MD->getSelector().isKeywordSelector( + {"localizedStringForKey", "value", "table"})) { + IgnoreStringsWithoutSpecifiers = true; + } + + const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); + return checkFormatStringExpr( + S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, + CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, + IgnoreStringsWithoutSpecifiers); + } + } + + return SLCT_NotALiteral; + } + case Stmt::ObjCStringLiteralClass: + case Stmt::StringLiteralClass: { + const StringLiteral *StrE = nullptr; + + if (const ObjCStringLiteral *ObjCFExpr = dyn_cast(E)) + StrE = ObjCFExpr->getString(); + else + StrE = cast(E); + + if (StrE) { + if (Offset.isNegative() || Offset > StrE->getLength()) { + // TODO: It would be better to have an explicit warning for out of + // bounds literals. + return SLCT_NotALiteral; + } + FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); + CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, + firstDataArg, Type, InFunctionCall, CallType, + CheckedVarArgs, UncoveredArg, + IgnoreStringsWithoutSpecifiers); + return SLCT_CheckedLiteral; + } + + return SLCT_NotALiteral; + } + case Stmt::BinaryOperatorClass: { + const BinaryOperator *BinOp = cast(E); + + // A string literal + an int offset is still a string literal. + if (BinOp->isAdditiveOp()) { + Expr::EvalResult LResult, RResult; + + bool LIsInt = BinOp->getLHS()->EvaluateAsInt( + LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); + bool RIsInt = BinOp->getRHS()->EvaluateAsInt( + RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); + + if (LIsInt != RIsInt) { + BinaryOperatorKind BinOpKind = BinOp->getOpcode(); + + if (LIsInt) { + if (BinOpKind == BO_Add) { + sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); + E = BinOp->getRHS(); + goto tryAgain; + } + } else { + sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); + E = BinOp->getLHS(); + goto tryAgain; + } + } + } + + return SLCT_NotALiteral; + } + case Stmt::UnaryOperatorClass: { + const UnaryOperator *UnaOp = cast(E); + auto ASE = dyn_cast(UnaOp->getSubExpr()); + if (UnaOp->getOpcode() == UO_AddrOf && ASE) { + Expr::EvalResult IndexResult; + if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, + Expr::SE_NoSideEffects, + S.isConstantEvaluated())) { + sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, + /*RHS is int*/ true); + E = ASE->getBase(); + goto tryAgain; + } + } + + return SLCT_NotALiteral; + } + + default: + return SLCT_NotALiteral; + } + } + + Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { + return llvm::StringSwitch(Format->getType()->getName()) + .Case("scanf", FST_Scanf) + .Cases("printf", "printf0", FST_Printf) + .Cases("NSString", "CFString", FST_NSString) + .Case("strftime", FST_Strftime) + .Case("strfmon", FST_Strfmon) + .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) + .Case("freebsd_kprintf", FST_FreeBSDKPrintf) + .Case("os_trace", FST_OSLog) + .Case("os_log", FST_OSLog) + .Default(FST_Unknown); + } + + /// CheckFormatArguments - Check calls to printf and scanf (and similar + /// functions) for correct use of format strings. + /// Returns true if a format string has been fully checked. + bool Sema::CheckFormatArguments(const FormatAttr *Format, + ArrayRef Args, + bool IsCXXMember, + VariadicCallType CallType, + SourceLocation Loc, SourceRange Range, + llvm::SmallBitVector &CheckedVarArgs) { + FormatStringInfo FSI; + if (getFormatStringInfo(Format, IsCXXMember, &FSI)) + return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, + FSI.FirstDataArg, GetFormatStringType(Format), + CallType, Loc, Range, CheckedVarArgs); + return false; + } + + bool Sema::CheckFormatArguments(ArrayRef Args, + bool HasVAListArg, unsigned format_idx, + unsigned firstDataArg, FormatStringType Type, + VariadicCallType CallType, + SourceLocation Loc, SourceRange Range, + llvm::SmallBitVector &CheckedVarArgs) { + // CHECK: printf/scanf-like function is called with no format string. + if (format_idx >= Args.size()) { + Diag(Loc, diag::warn_missing_format_string) << Range; + return false; + } + + const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); + + // CHECK: format string is not a string literal. + // + // Dynamically generated format strings are difficult to + // automatically vet at compile time. Requiring that format strings + // are string literals: (1) permits the checking of format strings by + // the compiler and thereby (2) can practically remove the source of + // many format string exploits. + + // Format string can be either ObjC string (e.g. @"%d") or + // C string (e.g. "%d") + // ObjC string uses the same format specifiers as C string, so we can use + // the same format string checking logic for both ObjC and C strings. + UncoveredArgHandler UncoveredArg; + StringLiteralCheckType CT = + checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, + format_idx, firstDataArg, Type, CallType, + /*IsFunctionCall*/ true, CheckedVarArgs, + UncoveredArg, + /*no string offset*/ llvm::APSInt(64, false) = 0); + + // Generate a diagnostic where an uncovered argument is detected. + if (UncoveredArg.hasUncoveredArg()) { + unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; + assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); + UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); + } + + if (CT != SLCT_NotALiteral) + // Literal format string found, check done! + return CT == SLCT_CheckedLiteral; + + // Strftime is particular as it always uses a single 'time' argument, + // so it is safe to pass a non-literal string. + if (Type == FST_Strftime) + return false; + + // Do not emit diag when the string param is a macro expansion and the + // format is either NSString or CFString. This is a hack to prevent + // diag when using the NSLocalizedString and CFCopyLocalizedString macros + // which are usually used in place of NS and CF string literals. + SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); + if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) + return false; + + // If there are no arguments specified, warn with -Wformat-security, otherwise + // warn only with -Wformat-nonliteral. + if (Args.size() == firstDataArg) { + Diag(FormatLoc, diag::warn_format_nonliteral_noargs) + << OrigFormatExpr->getSourceRange(); + switch (Type) { + default: + break; + case FST_Kprintf: + case FST_FreeBSDKPrintf: + case FST_Printf: + Diag(FormatLoc, diag::note_format_security_fixit) + << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); + break; + case FST_NSString: + Diag(FormatLoc, diag::note_format_security_fixit) + << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); + break; + } + } else { + Diag(FormatLoc, diag::warn_format_nonliteral) + << OrigFormatExpr->getSourceRange(); + } + return false; + } + + namespace { + + class CheckFormatHandler : public analyze_format_string::FormatStringHandler { + protected: + Sema &S; + const FormatStringLiteral *FExpr; + const Expr *OrigFormatExpr; + const Sema::FormatStringType FSType; + const unsigned FirstDataArg; + const unsigned NumDataArgs; + const char *Beg; // Start of format string. + const bool HasVAListArg; + ArrayRef Args; + unsigned FormatIdx; + llvm::SmallBitVector CoveredArgs; + bool usesPositionalArgs = false; + bool atFirstArg = true; + bool inFunctionCall; + Sema::VariadicCallType CallType; + llvm::SmallBitVector &CheckedVarArgs; + UncoveredArgHandler &UncoveredArg; + + public: + CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, + const Expr *origFormatExpr, + const Sema::FormatStringType type, unsigned firstDataArg, + unsigned numDataArgs, const char *beg, bool hasVAListArg, + ArrayRef Args, unsigned formatIdx, + bool inFunctionCall, Sema::VariadicCallType callType, + llvm::SmallBitVector &CheckedVarArgs, + UncoveredArgHandler &UncoveredArg) + : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), + FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), + HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), + inFunctionCall(inFunctionCall), CallType(callType), + CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { + CoveredArgs.resize(numDataArgs); + CoveredArgs.reset(); + } + + void DoneProcessing(); + + void HandleIncompleteSpecifier(const char *startSpecifier, + unsigned specifierLen) override; + + void HandleInvalidLengthModifier( + const analyze_format_string::FormatSpecifier &FS, + const analyze_format_string::ConversionSpecifier &CS, + const char *startSpecifier, unsigned specifierLen, + unsigned DiagID); + + void HandleNonStandardLengthModifier( + const analyze_format_string::FormatSpecifier &FS, + const char *startSpecifier, unsigned specifierLen); + + void HandleNonStandardConversionSpecifier( + const analyze_format_string::ConversionSpecifier &CS, + const char *startSpecifier, unsigned specifierLen); + + void HandlePosition(const char *startPos, unsigned posLen) override; + + void HandleInvalidPosition(const char *startSpecifier, + unsigned specifierLen, + analyze_format_string::PositionContext p) override; + + void HandleZeroPosition(const char *startPos, unsigned posLen) override; + + void HandleNullChar(const char *nullCharacter) override; + + template + static void + EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, + const PartialDiagnostic &PDiag, SourceLocation StringLoc, + bool IsStringLocation, Range StringRange, + ArrayRef Fixit = None); + + protected: + bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, + const char *startSpec, + unsigned specifierLen, + const char *csStart, unsigned csLen); + + void HandlePositionalNonpositionalArgs(SourceLocation Loc, + const char *startSpec, + unsigned specifierLen); + + SourceRange getFormatStringRange(); + CharSourceRange getSpecifierRange(const char *startSpecifier, + unsigned specifierLen); + SourceLocation getLocationOfByte(const char *x); + + const Expr *getDataArg(unsigned i) const; + + bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, + const analyze_format_string::ConversionSpecifier &CS, + const char *startSpecifier, unsigned specifierLen, + unsigned argIndex); + + template + void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, + bool IsStringLocation, Range StringRange, + ArrayRef Fixit = None); + }; + + } // namespace + + SourceRange CheckFormatHandler::getFormatStringRange() { + return OrigFormatExpr->getSourceRange(); + } + + CharSourceRange CheckFormatHandler:: + getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { + SourceLocation Start = getLocationOfByte(startSpecifier); + SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); + + // Advance the end SourceLocation by one due to half-open ranges. + End = End.getLocWithOffset(1); + + return CharSourceRange::getCharRange(Start, End); + } + + SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { + return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), + S.getLangOpts(), S.Context.getTargetInfo()); + } + + void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, + unsigned specifierLen){ + EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), + getLocationOfByte(startSpecifier), + /*IsStringLocation*/true, + getSpecifierRange(startSpecifier, specifierLen)); + } + + void CheckFormatHandler::HandleInvalidLengthModifier( + const analyze_format_string::FormatSpecifier &FS, + const analyze_format_string::ConversionSpecifier &CS, + const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { + using namespace analyze_format_string; + + const LengthModifier &LM = FS.getLengthModifier(); + CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); + + // See if we know how to fix this length modifier. + Optional FixedLM = FS.getCorrectedLengthModifier(); + if (FixedLM) { + EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), + getLocationOfByte(LM.getStart()), + /*IsStringLocation*/true, + getSpecifierRange(startSpecifier, specifierLen)); + + S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) + << FixedLM->toString() + << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); + + } else { + FixItHint Hint; + if (DiagID == diag::warn_format_nonsensical_length) + Hint = FixItHint::CreateRemoval(LMRange); + + EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), + getLocationOfByte(LM.getStart()), + /*IsStringLocation*/true, + getSpecifierRange(startSpecifier, specifierLen), + Hint); + } + } + + void CheckFormatHandler::HandleNonStandardLengthModifier( + const analyze_format_string::FormatSpecifier &FS, + const char *startSpecifier, unsigned specifierLen) { + using namespace analyze_format_string; + + const LengthModifier &LM = FS.getLengthModifier(); + CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); + + // See if we know how to fix this length modifier. + Optional FixedLM = FS.getCorrectedLengthModifier(); + if (FixedLM) { + EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) + << LM.toString() << 0, + getLocationOfByte(LM.getStart()), + /*IsStringLocation*/true, + getSpecifierRange(startSpecifier, specifierLen)); + + S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) + << FixedLM->toString() + << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); + + } else { + EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) + << LM.toString() << 0, + getLocationOfByte(LM.getStart()), + /*IsStringLocation*/true, + getSpecifierRange(startSpecifier, specifierLen)); + } + } + + void CheckFormatHandler::HandleNonStandardConversionSpecifier( + const analyze_format_string::ConversionSpecifier &CS, + const char *startSpecifier, unsigned specifierLen) { + using namespace analyze_format_string; + + // See if we know how to fix this conversion specifier. + Optional FixedCS = CS.getStandardSpecifier(); + if (FixedCS) { + EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) + << CS.toString() << /*conversion specifier*/1, + getLocationOfByte(CS.getStart()), + /*IsStringLocation*/true, + getSpecifierRange(startSpecifier, specifierLen)); + + CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); + S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) + << FixedCS->toString() + << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); + } else { + EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) + << CS.toString() << /*conversion specifier*/1, + getLocationOfByte(CS.getStart()), + /*IsStringLocation*/true, + getSpecifierRange(startSpecifier, specifierLen)); + } + } + + void CheckFormatHandler::HandlePosition(const char *startPos, + unsigned posLen) { + EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), + getLocationOfByte(startPos), + /*IsStringLocation*/true, + getSpecifierRange(startPos, posLen)); + } + + void + CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, + analyze_format_string::PositionContext p) { + EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) + << (unsigned) p, + getLocationOfByte(startPos), /*IsStringLocation*/true, + getSpecifierRange(startPos, posLen)); + } + + void CheckFormatHandler::HandleZeroPosition(const char *startPos, + unsigned posLen) { + EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), + getLocationOfByte(startPos), + /*IsStringLocation*/true, + getSpecifierRange(startPos, posLen)); + } + + void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { + if (!isa(OrigFormatExpr)) { + // The presence of a null character is likely an error. + EmitFormatDiagnostic( + S.PDiag(diag::warn_printf_format_string_contains_null_char), + getLocationOfByte(nullCharacter), /*IsStringLocation*/true, + getFormatStringRange()); + } + } + + // Note that this may return NULL if there was an error parsing or building + // one of the argument expressions. + const Expr *CheckFormatHandler::getDataArg(unsigned i) const { + return Args[FirstDataArg + i]; + } + + void CheckFormatHandler::DoneProcessing() { + // Does the number of data arguments exceed the number of + // format conversions in the format string? + if (!HasVAListArg) { + // Find any arguments that weren't covered. + CoveredArgs.flip(); + signed notCoveredArg = CoveredArgs.find_first(); + if (notCoveredArg >= 0) { + assert((unsigned)notCoveredArg < NumDataArgs); + UncoveredArg.Update(notCoveredArg, OrigFormatExpr); + } else { + UncoveredArg.setAllCovered(); + } + } + } + + void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, + const Expr *ArgExpr) { + assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && + "Invalid state"); + + if (!ArgExpr) + return; + + SourceLocation Loc = ArgExpr->getBeginLoc(); + + if (S.getSourceManager().isInSystemMacro(Loc)) + return; + + PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); + for (auto E : DiagnosticExprs) + PDiag << E->getSourceRange(); + + CheckFormatHandler::EmitFormatDiagnostic( + S, IsFunctionCall, DiagnosticExprs[0], + PDiag, Loc, /*IsStringLocation*/false, + DiagnosticExprs[0]->getSourceRange()); + } + + bool + CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, + SourceLocation Loc, + const char *startSpec, + unsigned specifierLen, + const char *csStart, + unsigned csLen) { + bool keepGoing = true; + if (argIndex < NumDataArgs) { + // Consider the argument coverered, even though the specifier doesn't + // make sense. + CoveredArgs.set(argIndex); + } + else { + // If argIndex exceeds the number of data arguments we + // don't issue a warning because that is just a cascade of warnings (and + // they may have intended '%%' anyway). We don't want to continue processing + // the format string after this point, however, as we will like just get + // gibberish when trying to match arguments. + keepGoing = false; + } + + StringRef Specifier(csStart, csLen); + + // If the specifier in non-printable, it could be the first byte of a UTF-8 + // sequence. In that case, print the UTF-8 code point. If not, print the byte + // hex value. + std::string CodePointStr; + if (!llvm::sys::locale::isPrint(*csStart)) { + llvm::UTF32 CodePoint; + const llvm::UTF8 **B = reinterpret_cast(&csStart); + const llvm::UTF8 *E = + reinterpret_cast(csStart + csLen); + llvm::ConversionResult Result = + llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); + + if (Result != llvm::conversionOK) { + unsigned char FirstChar = *csStart; + CodePoint = (llvm::UTF32)FirstChar; + } + + llvm::raw_string_ostream OS(CodePointStr); + if (CodePoint < 256) + OS << "\\x" << llvm::format("%02x", CodePoint); + else if (CodePoint <= 0xFFFF) + OS << "\\u" << llvm::format("%04x", CodePoint); + else + OS << "\\U" << llvm::format("%08x", CodePoint); + OS.flush(); + Specifier = CodePointStr; + } + + EmitFormatDiagnostic( + S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, + /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); + + return keepGoing; + } + + void + CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, + const char *startSpec, + unsigned specifierLen) { + EmitFormatDiagnostic( + S.PDiag(diag::warn_format_mix_positional_nonpositional_args), + Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); + } + + bool + CheckFormatHandler::CheckNumArgs( + const analyze_format_string::FormatSpecifier &FS, + const analyze_format_string::ConversionSpecifier &CS, + const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { + + if (argIndex >= NumDataArgs) { + PartialDiagnostic PDiag = FS.usesPositionalArg() + ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) + << (argIndex+1) << NumDataArgs) + : S.PDiag(diag::warn_printf_insufficient_data_args); + EmitFormatDiagnostic( + PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, + getSpecifierRange(startSpecifier, specifierLen)); + + // Since more arguments than conversion tokens are given, by extension + // all arguments are covered, so mark this as so. + UncoveredArg.setAllCovered(); + return false; + } + return true; + } + + template + void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, + SourceLocation Loc, + bool IsStringLocation, + Range StringRange, + ArrayRef FixIt) { + EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, + Loc, IsStringLocation, StringRange, FixIt); + } + + /// If the format string is not within the function call, emit a note + /// so that the function call and string are in diagnostic messages. + /// + /// \param InFunctionCall if true, the format string is within the function + /// call and only one diagnostic message will be produced. Otherwise, an + /// extra note will be emitted pointing to location of the format string. + /// + /// \param ArgumentExpr the expression that is passed as the format string + /// argument in the function call. Used for getting locations when two + /// diagnostics are emitted. + /// + /// \param PDiag the callee should already have provided any strings for the + /// diagnostic message. This function only adds locations and fixits + /// to diagnostics. + /// + /// \param Loc primary location for diagnostic. If two diagnostics are + /// required, one will be at Loc and a new SourceLocation will be created for + /// the other one. + /// + /// \param IsStringLocation if true, Loc points to the format string should be + /// used for the note. Otherwise, Loc points to the argument list and will + /// be used with PDiag. + /// + /// \param StringRange some or all of the string to highlight. This is + /// templated so it can accept either a CharSourceRange or a SourceRange. + /// + /// \param FixIt optional fix it hint for the format string. + template + void CheckFormatHandler::EmitFormatDiagnostic( + Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, + const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, + Range StringRange, ArrayRef FixIt) { + if (InFunctionCall) { + const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); + D << StringRange; + D << FixIt; + } else { + S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) + << ArgumentExpr->getSourceRange(); + + const Sema::SemaDiagnosticBuilder &Note = + S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), + diag::note_format_string_defined); + + Note << StringRange; + Note << FixIt; + } + } + + //===--- CHECK: Printf format string checking ------------------------------===// + + namespace { + + class CheckPrintfHandler : public CheckFormatHandler { + public: + CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, + const Expr *origFormatExpr, + const Sema::FormatStringType type, unsigned firstDataArg, + unsigned numDataArgs, bool isObjC, const char *beg, + bool hasVAListArg, ArrayRef Args, + unsigned formatIdx, bool inFunctionCall, + Sema::VariadicCallType CallType, + llvm::SmallBitVector &CheckedVarArgs, + UncoveredArgHandler &UncoveredArg) + : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, + numDataArgs, beg, hasVAListArg, Args, formatIdx, + inFunctionCall, CallType, CheckedVarArgs, + UncoveredArg) {} + + bool isObjCContext() const { return FSType == Sema::FST_NSString; } + + /// Returns true if '%@' specifiers are allowed in the format string. + bool allowsObjCArg() const { + return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || + FSType == Sema::FST_OSTrace; + } + + bool HandleInvalidPrintfConversionSpecifier( + const analyze_printf::PrintfSpecifier &FS, + const char *startSpecifier, + unsigned specifierLen) override; + + void handleInvalidMaskType(StringRef MaskType) override; + + bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, + const char *startSpecifier, + unsigned specifierLen) override; + bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, + const char *StartSpecifier, + unsigned SpecifierLen, + const Expr *E); + + bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, + const char *startSpecifier, unsigned specifierLen); + void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, + const analyze_printf::OptionalAmount &Amt, + unsigned type, + const char *startSpecifier, unsigned specifierLen); + void HandleFlag(const analyze_printf::PrintfSpecifier &FS, + const analyze_printf::OptionalFlag &flag, + const char *startSpecifier, unsigned specifierLen); + void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, + const analyze_printf::OptionalFlag &ignoredFlag, + const analyze_printf::OptionalFlag &flag, + const char *startSpecifier, unsigned specifierLen); + bool checkForCStrMembers(const analyze_printf::ArgType &AT, + const Expr *E); + + void HandleEmptyObjCModifierFlag(const char *startFlag, + unsigned flagLen) override; + + void HandleInvalidObjCModifierFlag(const char *startFlag, + unsigned flagLen) override; + + void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, + const char *flagsEnd, + const char *conversionPosition) + override; + }; + + } // namespace + + bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( + const analyze_printf::PrintfSpecifier &FS, + const char *startSpecifier, + unsigned specifierLen) { + const analyze_printf::PrintfConversionSpecifier &CS = + FS.getConversionSpecifier(); + + return HandleInvalidConversionSpecifier(FS.getArgIndex(), + getLocationOfByte(CS.getStart()), + startSpecifier, specifierLen, + CS.getStart(), CS.getLength()); + } + + void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { + S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); + } + + bool CheckPrintfHandler::HandleAmount( + const analyze_format_string::OptionalAmount &Amt, + unsigned k, const char *startSpecifier, + unsigned specifierLen) { + if (Amt.hasDataArgument()) { + if (!HasVAListArg) { + unsigned argIndex = Amt.getArgIndex(); + if (argIndex >= NumDataArgs) { + EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) + << k, + getLocationOfByte(Amt.getStart()), + /*IsStringLocation*/true, + getSpecifierRange(startSpecifier, specifierLen)); + // Don't do any more checking. We will just emit + // spurious errors. + return false; + } + + // Type check the data argument. It should be an 'int'. + // Although not in conformance with C99, we also allow the argument to be + // an 'unsigned int' as that is a reasonably safe case. GCC also + // doesn't emit a warning for that case. + CoveredArgs.set(argIndex); + const Expr *Arg = getDataArg(argIndex); + if (!Arg) + return false; + + QualType T = Arg->getType(); + + const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); + assert(AT.isValid()); + + if (!AT.matchesType(S.Context, T)) { + EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) + << k << AT.getRepresentativeTypeName(S.Context) + << T << Arg->getSourceRange(), + getLocationOfByte(Amt.getStart()), + /*IsStringLocation*/true, + getSpecifierRange(startSpecifier, specifierLen)); + // Don't do any more checking. We will just emit + // spurious errors. + return false; + } + } + } + return true; + } + + void CheckPrintfHandler::HandleInvalidAmount( + const analyze_printf::PrintfSpecifier &FS, + const analyze_printf::OptionalAmount &Amt, + unsigned type, + const char *startSpecifier, + unsigned specifierLen) { + const analyze_printf::PrintfConversionSpecifier &CS = + FS.getConversionSpecifier(); + + FixItHint fixit = + Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant + ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), + Amt.getConstantLength())) + : FixItHint(); + + EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) + << type << CS.toString(), + getLocationOfByte(Amt.getStart()), + /*IsStringLocation*/true, + getSpecifierRange(startSpecifier, specifierLen), + fixit); + } + + void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, + const analyze_printf::OptionalFlag &flag, + const char *startSpecifier, + unsigned specifierLen) { + // Warn about pointless flag with a fixit removal. + const analyze_printf::PrintfConversionSpecifier &CS = + FS.getConversionSpecifier(); + EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) + << flag.toString() << CS.toString(), + getLocationOfByte(flag.getPosition()), + /*IsStringLocation*/true, + getSpecifierRange(startSpecifier, specifierLen), + FixItHint::CreateRemoval( + getSpecifierRange(flag.getPosition(), 1))); + } + + void CheckPrintfHandler::HandleIgnoredFlag( + const analyze_printf::PrintfSpecifier &FS, + const analyze_printf::OptionalFlag &ignoredFlag, + const analyze_printf::OptionalFlag &flag, + const char *startSpecifier, + unsigned specifierLen) { + // Warn about ignored flag with a fixit removal. + EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) + << ignoredFlag.toString() << flag.toString(), + getLocationOfByte(ignoredFlag.getPosition()), + /*IsStringLocation*/true, + getSpecifierRange(startSpecifier, specifierLen), + FixItHint::CreateRemoval( + getSpecifierRange(ignoredFlag.getPosition(), 1))); + } + + void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, + unsigned flagLen) { + // Warn about an empty flag. + EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), + getLocationOfByte(startFlag), + /*IsStringLocation*/true, + getSpecifierRange(startFlag, flagLen)); + } + + void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, + unsigned flagLen) { + // Warn about an invalid flag. + auto Range = getSpecifierRange(startFlag, flagLen); + StringRef flag(startFlag, flagLen); + EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, + getLocationOfByte(startFlag), + /*IsStringLocation*/true, + Range, FixItHint::CreateRemoval(Range)); + } + + void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( + const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { + // Warn about using '[...]' without a '@' conversion. + auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); + auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; + EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), + getLocationOfByte(conversionPosition), + /*IsStringLocation*/true, + Range, FixItHint::CreateRemoval(Range)); + } + + // Determines if the specified is a C++ class or struct containing + // a member with the specified name and kind (e.g. a CXXMethodDecl named + // "c_str()"). + template + static llvm::SmallPtrSet + CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { + const RecordType *RT = Ty->getAs(); + llvm::SmallPtrSet Results; + + if (!RT) + return Results; + const CXXRecordDecl *RD = dyn_cast(RT->getDecl()); + if (!RD || !RD->getDefinition()) + return Results; + + LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), + Sema::LookupMemberName); + R.suppressDiagnostics(); + + // We just need to include all members of the right kind turned up by the + // filter, at this point. + if (S.LookupQualifiedName(R, RT->getDecl())) + for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { + NamedDecl *decl = (*I)->getUnderlyingDecl(); + if (MemberKind *FK = dyn_cast(decl)) + Results.insert(FK); + } + return Results; + } + + /// Check if we could call '.c_str()' on an object. + /// + /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't + /// allow the call, or if it would be ambiguous). + bool Sema::hasCStrMethod(const Expr *E) { + using MethodSet = llvm::SmallPtrSet; + + MethodSet Results = + CXXRecordMembersNamed("c_str", *this, E->getType()); + for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); + MI != ME; ++MI) + if ((*MI)->getMinRequiredArguments() == 0) + return true; + return false; + } + + // Check if a (w)string was passed when a (w)char* was needed, and offer a + // better diagnostic if so. AT is assumed to be valid. + // Returns true when a c_str() conversion method is found. + bool CheckPrintfHandler::checkForCStrMembers( + const analyze_printf::ArgType &AT, const Expr *E) { + using MethodSet = llvm::SmallPtrSet; + + MethodSet Results = + CXXRecordMembersNamed("c_str", S, E->getType()); + + for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); + MI != ME; ++MI) { + const CXXMethodDecl *Method = *MI; + if (Method->getMinRequiredArguments() == 0 && + AT.matchesType(S.Context, Method->getReturnType())) { + // FIXME: Suggest parens if the expression needs them. + SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); + S.Diag(E->getBeginLoc(), diag::note_printf_c_str) + << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); + return true; + } + } + + return false; + } + + bool + CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier + &FS, + const char *startSpecifier, + unsigned specifierLen) { + using namespace analyze_format_string; + using namespace analyze_printf; + + const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); + + if (FS.consumesDataArgument()) { + if (atFirstArg) { + atFirstArg = false; + usesPositionalArgs = FS.usesPositionalArg(); + } + else if (usesPositionalArgs != FS.usesPositionalArg()) { + HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), + startSpecifier, specifierLen); + return false; + } + } + + // First check if the field width, precision, and conversion specifier + // have matching data arguments. + if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, + startSpecifier, specifierLen)) { + return false; + } + + if (!HandleAmount(FS.getPrecision(), /* precision */ 1, + startSpecifier, specifierLen)) { + return false; + } + + if (!CS.consumesDataArgument()) { + // FIXME: Technically specifying a precision or field width here + // makes no sense. Worth issuing a warning at some point. + return true; + } + + // Consume the argument. + unsigned argIndex = FS.getArgIndex(); + if (argIndex < NumDataArgs) { + // The check to see if the argIndex is valid will come later. + // We set the bit here because we may exit early from this + // function if we encounter some other error. + CoveredArgs.set(argIndex); + } + + // FreeBSD kernel extensions. + if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || + CS.getKind() == ConversionSpecifier::FreeBSDDArg) { + // We need at least two arguments. + if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) + return false; + + // Claim the second argument. + CoveredArgs.set(argIndex + 1); + + // Type check the first argument (int for %b, pointer for %D) + const Expr *Ex = getDataArg(argIndex); + const analyze_printf::ArgType &AT = + (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? + ArgType(S.Context.IntTy) : ArgType::CPointerTy; + if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) + EmitFormatDiagnostic( + S.PDiag(diag::warn_format_conversion_argument_type_mismatch) + << AT.getRepresentativeTypeName(S.Context) << Ex->getType() + << false << Ex->getSourceRange(), + Ex->getBeginLoc(), /*IsStringLocation*/ false, + getSpecifierRange(startSpecifier, specifierLen)); + + // Type check the second argument (char * for both %b and %D) + Ex = getDataArg(argIndex + 1); + const analyze_printf::ArgType &AT2 = ArgType::CStrTy; + if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) + EmitFormatDiagnostic( + S.PDiag(diag::warn_format_conversion_argument_type_mismatch) + << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() + << false << Ex->getSourceRange(), + Ex->getBeginLoc(), /*IsStringLocation*/ false, + getSpecifierRange(startSpecifier, specifierLen)); + + return true; + } + + // Check for using an Objective-C specific conversion specifier + // in a non-ObjC literal. + if (!allowsObjCArg() && CS.isObjCArg()) { + return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, + specifierLen); + } + + // %P can only be used with os_log. + if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { + return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, + specifierLen); + } + + // %n is not allowed with os_log. + if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { + EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), + getLocationOfByte(CS.getStart()), + /*IsStringLocation*/ false, + getSpecifierRange(startSpecifier, specifierLen)); + + return true; + } + + // Only scalars are allowed for os_trace. + if (FSType == Sema::FST_OSTrace && + (CS.getKind() == ConversionSpecifier::PArg || + CS.getKind() == ConversionSpecifier::sArg || + CS.getKind() == ConversionSpecifier::ObjCObjArg)) { + return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, + specifierLen); + } + + // Check for use of public/private annotation outside of os_log(). + if (FSType != Sema::FST_OSLog) { + if (FS.isPublic().isSet()) { + EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) + << "public", + getLocationOfByte(FS.isPublic().getPosition()), + /*IsStringLocation*/ false, + getSpecifierRange(startSpecifier, specifierLen)); + } + if (FS.isPrivate().isSet()) { + EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) + << "private", + getLocationOfByte(FS.isPrivate().getPosition()), + /*IsStringLocation*/ false, + getSpecifierRange(startSpecifier, specifierLen)); + } + } + + // Check for invalid use of field width + if (!FS.hasValidFieldWidth()) { + HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, + startSpecifier, specifierLen); + } + + // Check for invalid use of precision + if (!FS.hasValidPrecision()) { + HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, + startSpecifier, specifierLen); + } + + // Precision is mandatory for %P specifier. + if (CS.getKind() == ConversionSpecifier::PArg && + FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { + EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), + getLocationOfByte(startSpecifier), + /*IsStringLocation*/ false, + getSpecifierRange(startSpecifier, specifierLen)); + } + + // Check each flag does not conflict with any other component. + if (!FS.hasValidThousandsGroupingPrefix()) + HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); + if (!FS.hasValidLeadingZeros()) + HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); + if (!FS.hasValidPlusPrefix()) + HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); + if (!FS.hasValidSpacePrefix()) + HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); + if (!FS.hasValidAlternativeForm()) + HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); + if (!FS.hasValidLeftJustified()) + HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); + + // Check that flags are not ignored by another flag + if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' + HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), + startSpecifier, specifierLen); + if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' + HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), + startSpecifier, specifierLen); + + // Check the length modifier is valid with the given conversion specifier. + if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), + S.getLangOpts())) + HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, + diag::warn_format_nonsensical_length); + else if (!FS.hasStandardLengthModifier()) + HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); + else if (!FS.hasStandardLengthConversionCombination()) + HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, + diag::warn_format_non_standard_conversion_spec); + + if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) + HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); + + // The remaining checks depend on the data arguments. + if (HasVAListArg) + return true; + + if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) + return false; + + const Expr *Arg = getDataArg(argIndex); + if (!Arg) + return true; + + return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); + } + + static bool requiresParensToAddCast(const Expr *E) { + // FIXME: We should have a general way to reason about operator + // precedence and whether parens are actually needed here. + // Take care of a few common cases where they aren't. + const Expr *Inside = E->IgnoreImpCasts(); + if (const PseudoObjectExpr *POE = dyn_cast(Inside)) + Inside = POE->getSyntacticForm()->IgnoreImpCasts(); + + switch (Inside->getStmtClass()) { + case Stmt::ArraySubscriptExprClass: + case Stmt::CallExprClass: + case Stmt::CharacterLiteralClass: + case Stmt::CXXBoolLiteralExprClass: + case Stmt::DeclRefExprClass: + case Stmt::FloatingLiteralClass: + case Stmt::IntegerLiteralClass: + case Stmt::MemberExprClass: + case Stmt::ObjCArrayLiteralClass: + case Stmt::ObjCBoolLiteralExprClass: + case Stmt::ObjCBoxedExprClass: + case Stmt::ObjCDictionaryLiteralClass: + case Stmt::ObjCEncodeExprClass: + case Stmt::ObjCIvarRefExprClass: + case Stmt::ObjCMessageExprClass: + case Stmt::ObjCPropertyRefExprClass: + case Stmt::ObjCStringLiteralClass: + case Stmt::ObjCSubscriptRefExprClass: + case Stmt::ParenExprClass: + case Stmt::StringLiteralClass: + case Stmt::UnaryOperatorClass: + return false; + default: + return true; + } + } + + static std::pair + shouldNotPrintDirectly(const ASTContext &Context, + QualType IntendedTy, + const Expr *E) { + // Use a 'while' to peel off layers of typedefs. + QualType TyTy = IntendedTy; + while (const TypedefType *UserTy = TyTy->getAs()) { + StringRef Name = UserTy->getDecl()->getName(); + QualType CastTy = llvm::StringSwitch(Name) + .Case("CFIndex", Context.getNSIntegerType()) + .Case("NSInteger", Context.getNSIntegerType()) + .Case("NSUInteger", Context.getNSUIntegerType()) + .Case("SInt32", Context.IntTy) + .Case("UInt32", Context.UnsignedIntTy) + .Default(QualType()); + + if (!CastTy.isNull()) + return std::make_pair(CastTy, Name); + + TyTy = UserTy->desugar(); + } + + // Strip parens if necessary. + if (const ParenExpr *PE = dyn_cast(E)) + return shouldNotPrintDirectly(Context, + PE->getSubExpr()->getType(), + PE->getSubExpr()); + + // If this is a conditional expression, then its result type is constructed + // via usual arithmetic conversions and thus there might be no necessary + // typedef sugar there. Recurse to operands to check for NSInteger & + // Co. usage condition. + if (const ConditionalOperator *CO = dyn_cast(E)) { + QualType TrueTy, FalseTy; + StringRef TrueName, FalseName; + + std::tie(TrueTy, TrueName) = + shouldNotPrintDirectly(Context, + CO->getTrueExpr()->getType(), + CO->getTrueExpr()); + std::tie(FalseTy, FalseName) = + shouldNotPrintDirectly(Context, + CO->getFalseExpr()->getType(), + CO->getFalseExpr()); + + if (TrueTy == FalseTy) + return std::make_pair(TrueTy, TrueName); + else if (TrueTy.isNull()) + return std::make_pair(FalseTy, FalseName); + else if (FalseTy.isNull()) + return std::make_pair(TrueTy, TrueName); + } + + return std::make_pair(QualType(), StringRef()); + } + + /// Return true if \p ICE is an implicit argument promotion of an arithmetic + /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked + /// type do not count. + static bool + isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { + QualType From = ICE->getSubExpr()->getType(); + QualType To = ICE->getType(); + // It's an integer promotion if the destination type is the promoted + // source type. + if (ICE->getCastKind() == CK_IntegralCast && + From->isPromotableIntegerType() && + S.Context.getPromotedIntegerType(From) == To) + return true; + // Look through vector types, since we do default argument promotion for + // those in OpenCL. + if (const auto *VecTy = From->getAs()) + From = VecTy->getElementType(); + if (const auto *VecTy = To->getAs()) + To = VecTy->getElementType(); + // It's a floating promotion if the source type is a lower rank. + return ICE->getCastKind() == CK_FloatingCast && + S.Context.getFloatingTypeOrder(From, To) < 0; + } + + bool + CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, + const char *StartSpecifier, + unsigned SpecifierLen, + const Expr *E) { + using namespace analyze_format_string; + using namespace analyze_printf; + + // Now type check the data expression that matches the + // format specifier. + const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); + if (!AT.isValid()) + return true; + + QualType ExprTy = E->getType(); + while (const TypeOfExprType *TET = dyn_cast(ExprTy)) { + ExprTy = TET->getUnderlyingExpr()->getType(); + } + + // Diagnose attempts to print a boolean value as a character. Unlike other + // -Wformat diagnostics, this is fine from a type perspective, but it still + // doesn't make sense. + if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && + E->isKnownToHaveBooleanValue()) { + const CharSourceRange &CSR = + getSpecifierRange(StartSpecifier, SpecifierLen); + SmallString<4> FSString; + llvm::raw_svector_ostream os(FSString); + FS.toString(os); + EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) + << FSString, + E->getExprLoc(), false, CSR); + return true; + } + + analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); + if (Match == analyze_printf::ArgType::Match) + return true; + + // Look through argument promotions for our error message's reported type. + // This includes the integral and floating promotions, but excludes array + // and function pointer decay (seeing that an argument intended to be a + // string has type 'char [6]' is probably more confusing than 'char *') and + // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). + if (const ImplicitCastExpr *ICE = dyn_cast(E)) { + if (isArithmeticArgumentPromotion(S, ICE)) { + E = ICE->getSubExpr(); + ExprTy = E->getType(); + + // Check if we didn't match because of an implicit cast from a 'char' + // or 'short' to an 'int'. This is done because printf is a varargs + // function. + if (ICE->getType() == S.Context.IntTy || + ICE->getType() == S.Context.UnsignedIntTy) { + // All further checking is done on the subexpression + const analyze_printf::ArgType::MatchKind ImplicitMatch = + AT.matchesType(S.Context, ExprTy); + if (ImplicitMatch == analyze_printf::ArgType::Match) + return true; + if (ImplicitMatch == ArgType::NoMatchPedantic || + ImplicitMatch == ArgType::NoMatchTypeConfusion) + Match = ImplicitMatch; + } + } + } else if (const CharacterLiteral *CL = dyn_cast(E)) { + // Special case for 'a', which has type 'int' in C. + // Note, however, that we do /not/ want to treat multibyte constants like + // 'MooV' as characters! This form is deprecated but still exists. In + // addition, don't treat expressions as of type 'char' if one byte length + // modifier is provided. + if (ExprTy == S.Context.IntTy && + FS.getLengthModifier().getKind() != LengthModifier::AsChar) + if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) + ExprTy = S.Context.CharTy; + } + + // Look through enums to their underlying type. + bool IsEnum = false; + if (auto EnumTy = ExprTy->getAs()) { + ExprTy = EnumTy->getDecl()->getIntegerType(); + IsEnum = true; + } + + // %C in an Objective-C context prints a unichar, not a wchar_t. + // If the argument is an integer of some kind, believe the %C and suggest + // a cast instead of changing the conversion specifier. + QualType IntendedTy = ExprTy; + if (isObjCContext() && + FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { + if (ExprTy->isIntegralOrUnscopedEnumerationType() && + !ExprTy->isCharType()) { + // 'unichar' is defined as a typedef of unsigned short, but we should + // prefer using the typedef if it is visible. + IntendedTy = S.Context.UnsignedShortTy; + + // While we are here, check if the value is an IntegerLiteral that happens + // to be within the valid range. + if (const IntegerLiteral *IL = dyn_cast(E)) { + const llvm::APInt &V = IL->getValue(); + if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) + return true; + } + + LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), + Sema::LookupOrdinaryName); + if (S.LookupName(Result, S.getCurScope())) { + NamedDecl *ND = Result.getFoundDecl(); + if (TypedefNameDecl *TD = dyn_cast(ND)) + if (TD->getUnderlyingType() == IntendedTy) + IntendedTy = S.Context.getTypedefType(TD); + } + } + } + + // Special-case some of Darwin's platform-independence types by suggesting + // casts to primitive types that are known to be large enough. + bool ShouldNotPrintDirectly = false; StringRef CastTyName; + if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { + QualType CastTy; + std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); + if (!CastTy.isNull()) { + // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int + // (long in ASTContext). Only complain to pedants. + if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && + (AT.isSizeT() || AT.isPtrdiffT()) && + AT.matchesType(S.Context, CastTy)) + Match = ArgType::NoMatchPedantic; + IntendedTy = CastTy; + ShouldNotPrintDirectly = true; + } + } + + // We may be able to offer a FixItHint if it is a supported type. + PrintfSpecifier fixedFS = FS; + bool Success = + fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); + + if (Success) { + // Get the fix string from the fixed format specifier + SmallString<16> buf; + llvm::raw_svector_ostream os(buf); + fixedFS.toString(os); + + CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); + + if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { + unsigned Diag; + switch (Match) { + case ArgType::Match: llvm_unreachable("expected non-matching"); + case ArgType::NoMatchPedantic: + Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; + break; + case ArgType::NoMatchTypeConfusion: + Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; + break; + case ArgType::NoMatch: + Diag = diag::warn_format_conversion_argument_type_mismatch; + break; + } + + // In this case, the specifier is wrong and should be changed to match + // the argument. + EmitFormatDiagnostic(S.PDiag(Diag) + << AT.getRepresentativeTypeName(S.Context) + << IntendedTy << IsEnum << E->getSourceRange(), + E->getBeginLoc(), + /*IsStringLocation*/ false, SpecRange, + FixItHint::CreateReplacement(SpecRange, os.str())); + } else { + // The canonical type for formatting this value is different from the + // actual type of the expression. (This occurs, for example, with Darwin's + // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but + // should be printed as 'long' for 64-bit compatibility.) + // Rather than emitting a normal format/argument mismatch, we want to + // add a cast to the recommended type (and correct the format string + // if necessary). + SmallString<16> CastBuf; + llvm::raw_svector_ostream CastFix(CastBuf); + CastFix << "("; + IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); + CastFix << ")"; + + SmallVector Hints; + if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) + Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); + + if (const CStyleCastExpr *CCast = dyn_cast(E)) { + // If there's already a cast present, just replace it. + SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); + Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); + + } else if (!requiresParensToAddCast(E)) { + // If the expression has high enough precedence, + // just write the C-style cast. + Hints.push_back( + FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); + } else { + // Otherwise, add parens around the expression as well as the cast. + CastFix << "("; + Hints.push_back( + FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); + + SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); + Hints.push_back(FixItHint::CreateInsertion(After, ")")); + } + + if (ShouldNotPrintDirectly) { + // The expression has a type that should not be printed directly. + // We extract the name from the typedef because we don't want to show + // the underlying type in the diagnostic. + StringRef Name; + if (const TypedefType *TypedefTy = dyn_cast(ExprTy)) + Name = TypedefTy->getDecl()->getName(); + else + Name = CastTyName; + unsigned Diag = Match == ArgType::NoMatchPedantic + ? diag::warn_format_argument_needs_cast_pedantic + : diag::warn_format_argument_needs_cast; + EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum + << E->getSourceRange(), + E->getBeginLoc(), /*IsStringLocation=*/false, + SpecRange, Hints); + } else { + // In this case, the expression could be printed using a different + // specifier, but we've decided that the specifier is probably correct + // and we should cast instead. Just use the normal warning message. + EmitFormatDiagnostic( + S.PDiag(diag::warn_format_conversion_argument_type_mismatch) + << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum + << E->getSourceRange(), + E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); + } + } + } else { + const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, + SpecifierLen); + // Since the warning for passing non-POD types to variadic functions + // was deferred until now, we emit a warning for non-POD + // arguments here. + switch (S.isValidVarArgType(ExprTy)) { + case Sema::VAK_Valid: + case Sema::VAK_ValidInCXX11: { + unsigned Diag; + switch (Match) { + case ArgType::Match: llvm_unreachable("expected non-matching"); + case ArgType::NoMatchPedantic: + Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; + break; + case ArgType::NoMatchTypeConfusion: + Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; + break; + case ArgType::NoMatch: + Diag = diag::warn_format_conversion_argument_type_mismatch; + break; + } + + EmitFormatDiagnostic( + S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy + << IsEnum << CSR << E->getSourceRange(), + E->getBeginLoc(), /*IsStringLocation*/ false, CSR); + break; + } + case Sema::VAK_Undefined: + case Sema::VAK_MSVCUndefined: + EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) + << S.getLangOpts().CPlusPlus11 << ExprTy + << CallType + << AT.getRepresentativeTypeName(S.Context) << CSR + << E->getSourceRange(), + E->getBeginLoc(), /*IsStringLocation*/ false, CSR); + checkForCStrMembers(AT, E); + break; + + case Sema::VAK_Invalid: + if (ExprTy->isObjCObjectType()) + EmitFormatDiagnostic( + S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) + << S.getLangOpts().CPlusPlus11 << ExprTy << CallType + << AT.getRepresentativeTypeName(S.Context) << CSR + << E->getSourceRange(), + E->getBeginLoc(), /*IsStringLocation*/ false, CSR); + else + // FIXME: If this is an initializer list, suggest removing the braces + // or inserting a cast to the target type. + S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) + << isa(E) << ExprTy << CallType + << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); + break; + } + + assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && + "format string specifier index out of range"); + CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; + } + + return true; + } + + //===--- CHECK: Scanf format string checking ------------------------------===// + + namespace { + + class CheckScanfHandler : public CheckFormatHandler { + public: + CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, + const Expr *origFormatExpr, Sema::FormatStringType type, + unsigned firstDataArg, unsigned numDataArgs, + const char *beg, bool hasVAListArg, + ArrayRef Args, unsigned formatIdx, + bool inFunctionCall, Sema::VariadicCallType CallType, + llvm::SmallBitVector &CheckedVarArgs, + UncoveredArgHandler &UncoveredArg) + : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, + numDataArgs, beg, hasVAListArg, Args, formatIdx, + inFunctionCall, CallType, CheckedVarArgs, + UncoveredArg) {} + + bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, + const char *startSpecifier, + unsigned specifierLen) override; + + bool HandleInvalidScanfConversionSpecifier( + const analyze_scanf::ScanfSpecifier &FS, + const char *startSpecifier, + unsigned specifierLen) override; + + void HandleIncompleteScanList(const char *start, const char *end) override; + }; + + } // namespace + + void CheckScanfHandler::HandleIncompleteScanList(const char *start, + const char *end) { + EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), + getLocationOfByte(end), /*IsStringLocation*/true, + getSpecifierRange(start, end - start)); + } + + bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( + const analyze_scanf::ScanfSpecifier &FS, + const char *startSpecifier, + unsigned specifierLen) { + const analyze_scanf::ScanfConversionSpecifier &CS = + FS.getConversionSpecifier(); + + return HandleInvalidConversionSpecifier(FS.getArgIndex(), + getLocationOfByte(CS.getStart()), + startSpecifier, specifierLen, + CS.getStart(), CS.getLength()); + } + + bool CheckScanfHandler::HandleScanfSpecifier( + const analyze_scanf::ScanfSpecifier &FS, + const char *startSpecifier, + unsigned specifierLen) { + using namespace analyze_scanf; + using namespace analyze_format_string; + + const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); + + // Handle case where '%' and '*' don't consume an argument. These shouldn't + // be used to decide if we are using positional arguments consistently. + if (FS.consumesDataArgument()) { + if (atFirstArg) { + atFirstArg = false; + usesPositionalArgs = FS.usesPositionalArg(); + } + else if (usesPositionalArgs != FS.usesPositionalArg()) { + HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), + startSpecifier, specifierLen); + return false; + } + } + + // Check if the field with is non-zero. + const OptionalAmount &Amt = FS.getFieldWidth(); + if (Amt.getHowSpecified() == OptionalAmount::Constant) { + if (Amt.getConstantAmount() == 0) { + const CharSourceRange &R = getSpecifierRange(Amt.getStart(), + Amt.getConstantLength()); + EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), + getLocationOfByte(Amt.getStart()), + /*IsStringLocation*/true, R, + FixItHint::CreateRemoval(R)); + } + } + + if (!FS.consumesDataArgument()) { + // FIXME: Technically specifying a precision or field width here + // makes no sense. Worth issuing a warning at some point. + return true; + } + + // Consume the argument. + unsigned argIndex = FS.getArgIndex(); + if (argIndex < NumDataArgs) { + // The check to see if the argIndex is valid will come later. + // We set the bit here because we may exit early from this + // function if we encounter some other error. + CoveredArgs.set(argIndex); + } + + // Check the length modifier is valid with the given conversion specifier. + if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), + S.getLangOpts())) + HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, + diag::warn_format_nonsensical_length); + else if (!FS.hasStandardLengthModifier()) + HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); + else if (!FS.hasStandardLengthConversionCombination()) + HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, + diag::warn_format_non_standard_conversion_spec); + + if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) + HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); + + // The remaining checks depend on the data arguments. + if (HasVAListArg) + return true; + + if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) + return false; + + // Check that the argument type matches the format specifier. + const Expr *Ex = getDataArg(argIndex); + if (!Ex) + return true; + + const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); + + if (!AT.isValid()) { + return true; + } + + analyze_format_string::ArgType::MatchKind Match = + AT.matchesType(S.Context, Ex->getType()); + bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; + if (Match == analyze_format_string::ArgType::Match) + return true; + + ScanfSpecifier fixedFS = FS; + bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), + S.getLangOpts(), S.Context); + + unsigned Diag = + Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic + : diag::warn_format_conversion_argument_type_mismatch; + + if (Success) { + // Get the fix string from the fixed format specifier. + SmallString<128> buf; + llvm::raw_svector_ostream os(buf); + fixedFS.toString(os); + + EmitFormatDiagnostic( + S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) + << Ex->getType() << false << Ex->getSourceRange(), + Ex->getBeginLoc(), + /*IsStringLocation*/ false, + getSpecifierRange(startSpecifier, specifierLen), + FixItHint::CreateReplacement( + getSpecifierRange(startSpecifier, specifierLen), os.str())); + } else { + EmitFormatDiagnostic(S.PDiag(Diag) + << AT.getRepresentativeTypeName(S.Context) + << Ex->getType() << false << Ex->getSourceRange(), + Ex->getBeginLoc(), + /*IsStringLocation*/ false, + getSpecifierRange(startSpecifier, specifierLen)); + } + + return true; + } + + static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, + const Expr *OrigFormatExpr, + ArrayRef Args, + bool HasVAListArg, unsigned format_idx, + unsigned firstDataArg, + Sema::FormatStringType Type, + bool inFunctionCall, + Sema::VariadicCallType CallType, + llvm::SmallBitVector &CheckedVarArgs, + UncoveredArgHandler &UncoveredArg, + bool IgnoreStringsWithoutSpecifiers) { + // CHECK: is the format string a wide literal? + if (!FExpr->isAscii() && !FExpr->isUTF8()) { + CheckFormatHandler::EmitFormatDiagnostic( + S, inFunctionCall, Args[format_idx], + S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), + /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); + return; + } + + // Str - The format string. NOTE: this is NOT null-terminated! + StringRef StrRef = FExpr->getString(); + const char *Str = StrRef.data(); + // Account for cases where the string literal is truncated in a declaration. + const ConstantArrayType *T = + S.Context.getAsConstantArrayType(FExpr->getType()); + assert(T && "String literal not of constant array type!"); + size_t TypeSize = T->getSize().getZExtValue(); + size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); + const unsigned numDataArgs = Args.size() - firstDataArg; + + if (IgnoreStringsWithoutSpecifiers && + !analyze_format_string::parseFormatStringHasFormattingSpecifiers( + Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) + return; + + // Emit a warning if the string literal is truncated and does not contain an + // embedded null character. + if (TypeSize <= StrRef.size() && + StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { + CheckFormatHandler::EmitFormatDiagnostic( + S, inFunctionCall, Args[format_idx], + S.PDiag(diag::warn_printf_format_string_not_null_terminated), + FExpr->getBeginLoc(), + /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); + return; + } + + // CHECK: empty format string? + if (StrLen == 0 && numDataArgs > 0) { + CheckFormatHandler::EmitFormatDiagnostic( + S, inFunctionCall, Args[format_idx], + S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), + /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); + return; + } + + if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || + Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || + Type == Sema::FST_OSTrace) { + CheckPrintfHandler H( + S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, + (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, + HasVAListArg, Args, format_idx, inFunctionCall, CallType, + CheckedVarArgs, UncoveredArg); + + if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, + S.getLangOpts(), + S.Context.getTargetInfo(), + Type == Sema::FST_FreeBSDKPrintf)) + H.DoneProcessing(); + } else if (Type == Sema::FST_Scanf) { + CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, + numDataArgs, Str, HasVAListArg, Args, format_idx, + inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); + + if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, + S.getLangOpts(), + S.Context.getTargetInfo())) + H.DoneProcessing(); + } // TODO: handle other formats + } + + bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { + // Str - The format string. NOTE: this is NOT null-terminated! + StringRef StrRef = FExpr->getString(); + const char *Str = StrRef.data(); + // Account for cases where the string literal is truncated in a declaration. + const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); + assert(T && "String literal not of constant array type!"); + size_t TypeSize = T->getSize().getZExtValue(); + size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); + return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, + getLangOpts(), + Context.getTargetInfo()); + } + + //===--- CHECK: Warn on use of wrong absolute value function. -------------===// + + // Returns the related absolute value function that is larger, of 0 if one + // does not exist. + static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { + switch (AbsFunction) { + default: + return 0; + + case Builtin::BI__builtin_abs: + return Builtin::BI__builtin_labs; + case Builtin::BI__builtin_labs: + return Builtin::BI__builtin_llabs; + case Builtin::BI__builtin_llabs: + return 0; + + case Builtin::BI__builtin_fabsf: + return Builtin::BI__builtin_fabs; + case Builtin::BI__builtin_fabs: + return Builtin::BI__builtin_fabsl; + case Builtin::BI__builtin_fabsl: + return 0; + + case Builtin::BI__builtin_cabsf: + return Builtin::BI__builtin_cabs; + case Builtin::BI__builtin_cabs: + return Builtin::BI__builtin_cabsl; + case Builtin::BI__builtin_cabsl: + return 0; + + case Builtin::BIabs: + return Builtin::BIlabs; + case Builtin::BIlabs: + return Builtin::BIllabs; + case Builtin::BIllabs: + return 0; + + case Builtin::BIfabsf: + return Builtin::BIfabs; + case Builtin::BIfabs: + return Builtin::BIfabsl; + case Builtin::BIfabsl: + return 0; + + case Builtin::BIcabsf: + return Builtin::BIcabs; + case Builtin::BIcabs: + return Builtin::BIcabsl; + case Builtin::BIcabsl: + return 0; + } + } + + // Returns the argument type of the absolute value function. + static QualType getAbsoluteValueArgumentType(ASTContext &Context, + unsigned AbsType) { + if (AbsType == 0) + return QualType(); + + ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; + QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); + if (Error != ASTContext::GE_None) + return QualType(); + + const FunctionProtoType *FT = BuiltinType->getAs(); + if (!FT) + return QualType(); + + if (FT->getNumParams() != 1) + return QualType(); + + return FT->getParamType(0); + } + + // Returns the best absolute value function, or zero, based on type and + // current absolute value function. + static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, + unsigned AbsFunctionKind) { + unsigned BestKind = 0; + uint64_t ArgSize = Context.getTypeSize(ArgType); + for (unsigned Kind = AbsFunctionKind; Kind != 0; + Kind = getLargerAbsoluteValueFunction(Kind)) { + QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); + if (Context.getTypeSize(ParamType) >= ArgSize) { + if (BestKind == 0) + BestKind = Kind; + else if (Context.hasSameType(ParamType, ArgType)) { + BestKind = Kind; + break; + } + } + } + return BestKind; + } + + enum AbsoluteValueKind { + AVK_Integer, + AVK_Floating, + AVK_Complex + }; + + static AbsoluteValueKind getAbsoluteValueKind(QualType T) { + if (T->isIntegralOrEnumerationType()) + return AVK_Integer; + if (T->isRealFloatingType()) + return AVK_Floating; + if (T->isAnyComplexType()) + return AVK_Complex; + + llvm_unreachable("Type not integer, floating, or complex"); + } + + // Changes the absolute value function to a different type. Preserves whether + // the function is a builtin. + static unsigned changeAbsFunction(unsigned AbsKind, + AbsoluteValueKind ValueKind) { + switch (ValueKind) { + case AVK_Integer: + switch (AbsKind) { + default: + return 0; + case Builtin::BI__builtin_fabsf: + case Builtin::BI__builtin_fabs: + case Builtin::BI__builtin_fabsl: + case Builtin::BI__builtin_cabsf: + case Builtin::BI__builtin_cabs: + case Builtin::BI__builtin_cabsl: + return Builtin::BI__builtin_abs; + case Builtin::BIfabsf: + case Builtin::BIfabs: + case Builtin::BIfabsl: + case Builtin::BIcabsf: + case Builtin::BIcabs: + case Builtin::BIcabsl: + return Builtin::BIabs; + } + case AVK_Floating: + switch (AbsKind) { + default: + return 0; + case Builtin::BI__builtin_abs: + case Builtin::BI__builtin_labs: + case Builtin::BI__builtin_llabs: + case Builtin::BI__builtin_cabsf: + case Builtin::BI__builtin_cabs: + case Builtin::BI__builtin_cabsl: + return Builtin::BI__builtin_fabsf; + case Builtin::BIabs: + case Builtin::BIlabs: + case Builtin::BIllabs: + case Builtin::BIcabsf: + case Builtin::BIcabs: + case Builtin::BIcabsl: + return Builtin::BIfabsf; + } + case AVK_Complex: + switch (AbsKind) { + default: + return 0; + case Builtin::BI__builtin_abs: + case Builtin::BI__builtin_labs: + case Builtin::BI__builtin_llabs: + case Builtin::BI__builtin_fabsf: + case Builtin::BI__builtin_fabs: + case Builtin::BI__builtin_fabsl: + return Builtin::BI__builtin_cabsf; + case Builtin::BIabs: + case Builtin::BIlabs: + case Builtin::BIllabs: + case Builtin::BIfabsf: + case Builtin::BIfabs: + case Builtin::BIfabsl: + return Builtin::BIcabsf; + } + } + llvm_unreachable("Unable to convert function"); + } + + static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { + const IdentifierInfo *FnInfo = FDecl->getIdentifier(); + if (!FnInfo) + return 0; + + switch (FDecl->getBuiltinID()) { + default: + return 0; + case Builtin::BI__builtin_abs: + case Builtin::BI__builtin_fabs: + case Builtin::BI__builtin_fabsf: + case Builtin::BI__builtin_fabsl: + case Builtin::BI__builtin_labs: + case Builtin::BI__builtin_llabs: + case Builtin::BI__builtin_cabs: + case Builtin::BI__builtin_cabsf: + case Builtin::BI__builtin_cabsl: + case Builtin::BIabs: + case Builtin::BIlabs: + case Builtin::BIllabs: + case Builtin::BIfabs: + case Builtin::BIfabsf: + case Builtin::BIfabsl: + case Builtin::BIcabs: + case Builtin::BIcabsf: + case Builtin::BIcabsl: + return FDecl->getBuiltinID(); + } + llvm_unreachable("Unknown Builtin type"); + } + + // If the replacement is valid, emit a note with replacement function. + // Additionally, suggest including the proper header if not already included. + static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, + unsigned AbsKind, QualType ArgType) { + bool EmitHeaderHint = true; + const char *HeaderName = nullptr; + const char *FunctionName = nullptr; + if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { + FunctionName = "std::abs"; + if (ArgType->isIntegralOrEnumerationType()) { + HeaderName = "cstdlib"; + } else if (ArgType->isRealFloatingType()) { + HeaderName = "cmath"; + } else { + llvm_unreachable("Invalid Type"); + } + + // Lookup all std::abs + if (NamespaceDecl *Std = S.getStdNamespace()) { + LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); + R.suppressDiagnostics(); + S.LookupQualifiedName(R, Std); + + for (const auto *I : R) { + const FunctionDecl *FDecl = nullptr; + if (const UsingShadowDecl *UsingD = dyn_cast(I)) { + FDecl = dyn_cast(UsingD->getTargetDecl()); + } else { + FDecl = dyn_cast(I); + } + if (!FDecl) + continue; + + // Found std::abs(), check that they are the right ones. + if (FDecl->getNumParams() != 1) + continue; + + // Check that the parameter type can handle the argument. + QualType ParamType = FDecl->getParamDecl(0)->getType(); + if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && + S.Context.getTypeSize(ArgType) <= + S.Context.getTypeSize(ParamType)) { + // Found a function, don't need the header hint. + EmitHeaderHint = false; + break; + } + } + } + } else { + FunctionName = S.Context.BuiltinInfo.getName(AbsKind); + HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); + + if (HeaderName) { + DeclarationName DN(&S.Context.Idents.get(FunctionName)); + LookupResult R(S, DN, Loc, Sema::LookupAnyName); + R.suppressDiagnostics(); + S.LookupName(R, S.getCurScope()); + + if (R.isSingleResult()) { + FunctionDecl *FD = dyn_cast(R.getFoundDecl()); + if (FD && FD->getBuiltinID() == AbsKind) { + EmitHeaderHint = false; + } else { + return; + } + } else if (!R.empty()) { + return; + } + } + } + + S.Diag(Loc, diag::note_replace_abs_function) + << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); + + if (!HeaderName) + return; + + if (!EmitHeaderHint) + return; + + S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName + << FunctionName; + } + + template + static bool IsStdFunction(const FunctionDecl *FDecl, + const char (&Str)[StrLen]) { + if (!FDecl) + return false; + if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) + return false; + if (!FDecl->isInStdNamespace()) + return false; + + return true; + } + + // Warn when using the wrong abs() function. + void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, + const FunctionDecl *FDecl) { + if (Call->getNumArgs() != 1) + return; + + unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); + bool IsStdAbs = IsStdFunction(FDecl, "abs"); + if (AbsKind == 0 && !IsStdAbs) + return; + + QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); + QualType ParamType = Call->getArg(0)->getType(); + + // Unsigned types cannot be negative. Suggest removing the absolute value + // function call. + if (ArgType->isUnsignedIntegerType()) { + const char *FunctionName = + IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); + Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; + Diag(Call->getExprLoc(), diag::note_remove_abs) + << FunctionName + << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); + return; + } + + // Taking the absolute value of a pointer is very suspicious, they probably + // wanted to index into an array, dereference a pointer, call a function, etc. + if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { + unsigned DiagType = 0; + if (ArgType->isFunctionType()) + DiagType = 1; + else if (ArgType->isArrayType()) + DiagType = 2; + + Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; + return; + } + + // std::abs has overloads which prevent most of the absolute value problems + // from occurring. + if (IsStdAbs) + return; + + AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); + AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); + + // The argument and parameter are the same kind. Check if they are the right + // size. + if (ArgValueKind == ParamValueKind) { + if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) + return; + + unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); + Diag(Call->getExprLoc(), diag::warn_abs_too_small) + << FDecl << ArgType << ParamType; + + if (NewAbsKind == 0) + return; + + emitReplacement(*this, Call->getExprLoc(), + Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); + return; + } + + // ArgValueKind != ParamValueKind + // The wrong type of absolute value function was used. Attempt to find the + // proper one. + unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); + NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); + if (NewAbsKind == 0) + return; + + Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) + << FDecl << ParamValueKind << ArgValueKind; + + emitReplacement(*this, Call->getExprLoc(), + Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); + } + + //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// + void Sema::CheckMaxUnsignedZero(const CallExpr *Call, + const FunctionDecl *FDecl) { + if (!Call || !FDecl) return; + + // Ignore template specializations and macros. + if (inTemplateInstantiation()) return; + if (Call->getExprLoc().isMacroID()) return; + + // Only care about the one template argument, two function parameter std::max + if (Call->getNumArgs() != 2) return; + if (!IsStdFunction(FDecl, "max")) return; + const auto * ArgList = FDecl->getTemplateSpecializationArgs(); + if (!ArgList) return; + if (ArgList->size() != 1) return; + + // Check that template type argument is unsigned integer. + const auto& TA = ArgList->get(0); + if (TA.getKind() != TemplateArgument::Type) return; + QualType ArgType = TA.getAsType(); + if (!ArgType->isUnsignedIntegerType()) return; + + // See if either argument is a literal zero. + auto IsLiteralZeroArg = [](const Expr* E) -> bool { + const auto *MTE = dyn_cast(E); + if (!MTE) return false; + const auto *Num = dyn_cast(MTE->getSubExpr()); + if (!Num) return false; + if (Num->getValue() != 0) return false; + return true; + }; + + const Expr *FirstArg = Call->getArg(0); + const Expr *SecondArg = Call->getArg(1); + const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); + const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); + + // Only warn when exactly one argument is zero. + if (IsFirstArgZero == IsSecondArgZero) return; + + SourceRange FirstRange = FirstArg->getSourceRange(); + SourceRange SecondRange = SecondArg->getSourceRange(); + + SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; + + Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) + << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; + + // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". + SourceRange RemovalRange; + if (IsFirstArgZero) { + RemovalRange = SourceRange(FirstRange.getBegin(), + SecondRange.getBegin().getLocWithOffset(-1)); + } else { + RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), + SecondRange.getEnd()); + } + + Diag(Call->getExprLoc(), diag::note_remove_max_call) + << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) + << FixItHint::CreateRemoval(RemovalRange); + } + + //===--- CHECK: Standard memory functions ---------------------------------===// + + /// Takes the expression passed to the size_t parameter of functions + /// such as memcmp, strncat, etc and warns if it's a comparison. + /// + /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. + static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, + IdentifierInfo *FnName, + SourceLocation FnLoc, + SourceLocation RParenLoc) { + const BinaryOperator *Size = dyn_cast(E); + if (!Size) + return false; + + // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: + if (!Size->isComparisonOp() && !Size->isLogicalOp()) + return false; + + SourceRange SizeRange = Size->getSourceRange(); + S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) + << SizeRange << FnName; + S.Diag(FnLoc, diag::note_memsize_comparison_paren) + << FnName + << FixItHint::CreateInsertion( + S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") + << FixItHint::CreateRemoval(RParenLoc); + S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) + << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") + << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), + ")"); + + return true; + } + + /// Determine whether the given type is or contains a dynamic class type + /// (e.g., whether it has a vtable). + static const CXXRecordDecl *getContainedDynamicClass(QualType T, + bool &IsContained) { + // Look through array types while ignoring qualifiers. + const Type *Ty = T->getBaseElementTypeUnsafe(); + IsContained = false; + + const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); + RD = RD ? RD->getDefinition() : nullptr; + if (!RD || RD->isInvalidDecl()) + return nullptr; + + if (RD->isDynamicClass()) + return RD; + + // Check all the fields. If any bases were dynamic, the class is dynamic. + // It's impossible for a class to transitively contain itself by value, so + // infinite recursion is impossible. + for (auto *FD : RD->fields()) { + bool SubContained; + if (const CXXRecordDecl *ContainedRD = + getContainedDynamicClass(FD->getType(), SubContained)) { + IsContained = true; + return ContainedRD; + } + } + + return nullptr; + } + + static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { + if (const auto *Unary = dyn_cast(E)) + if (Unary->getKind() == UETT_SizeOf) + return Unary; + return nullptr; + } + + /// If E is a sizeof expression, returns its argument expression, + /// otherwise returns NULL. + static const Expr *getSizeOfExprArg(const Expr *E) { + if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) + if (!SizeOf->isArgumentType()) + return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); + return nullptr; + } + + /// If E is a sizeof expression, returns its argument type. + static QualType getSizeOfArgType(const Expr *E) { + if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) + return SizeOf->getTypeOfArgument(); + return QualType(); + } + + namespace { + + struct SearchNonTrivialToInitializeField + : DefaultInitializedTypeVisitor { + using Super = + DefaultInitializedTypeVisitor; + + SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} + + void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, + SourceLocation SL) { + if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { + asDerived().visitArray(PDIK, AT, SL); + return; + } + + Super::visitWithKind(PDIK, FT, SL); + } + + void visitARCStrong(QualType FT, SourceLocation SL) { + S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); + } + void visitARCWeak(QualType FT, SourceLocation SL) { + S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); + } + void visitStruct(QualType FT, SourceLocation SL) { + for (const FieldDecl *FD : FT->castAs()->getDecl()->fields()) + visit(FD->getType(), FD->getLocation()); + } + void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, + const ArrayType *AT, SourceLocation SL) { + visit(getContext().getBaseElementType(AT), SL); + } + void visitTrivial(QualType FT, SourceLocation SL) {} + + static void diag(QualType RT, const Expr *E, Sema &S) { + SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); + } + + ASTContext &getContext() { return S.getASTContext(); } + + const Expr *E; + Sema &S; + }; + + struct SearchNonTrivialToCopyField + : CopiedTypeVisitor { + using Super = CopiedTypeVisitor; + + SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} + + void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, + SourceLocation SL) { + if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { + asDerived().visitArray(PCK, AT, SL); + return; + } + + Super::visitWithKind(PCK, FT, SL); + } + + void visitARCStrong(QualType FT, SourceLocation SL) { + S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); + } + void visitARCWeak(QualType FT, SourceLocation SL) { + S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); + } + void visitStruct(QualType FT, SourceLocation SL) { + for (const FieldDecl *FD : FT->castAs()->getDecl()->fields()) + visit(FD->getType(), FD->getLocation()); + } + void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, + SourceLocation SL) { + visit(getContext().getBaseElementType(AT), SL); + } + void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, + SourceLocation SL) {} + void visitTrivial(QualType FT, SourceLocation SL) {} + void visitVolatileTrivial(QualType FT, SourceLocation SL) {} + + static void diag(QualType RT, const Expr *E, Sema &S) { + SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); + } + + ASTContext &getContext() { return S.getASTContext(); } + + const Expr *E; + Sema &S; + }; + + } + + /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. + static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { + SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); + + if (const auto *BO = dyn_cast(SizeofExpr)) { + if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) + return false; + + return doesExprLikelyComputeSize(BO->getLHS()) || + doesExprLikelyComputeSize(BO->getRHS()); + } + + return getAsSizeOfExpr(SizeofExpr) != nullptr; + } + + /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. + /// + /// \code + /// #define MACRO 0 + /// foo(MACRO); + /// foo(0); + /// \endcode + /// + /// This should return true for the first call to foo, but not for the second + /// (regardless of whether foo is a macro or function). + static bool isArgumentExpandedFromMacro(SourceManager &SM, + SourceLocation CallLoc, + SourceLocation ArgLoc) { + if (!CallLoc.isMacroID()) + return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); + + return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != + SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); + } + + /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the + /// last two arguments transposed. + static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { + if (BId != Builtin::BImemset && BId != Builtin::BIbzero) + return; + + const Expr *SizeArg = + Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); + + auto isLiteralZero = [](const Expr *E) { + return isa(E) && cast(E)->getValue() == 0; + }; + + // If we're memsetting or bzeroing 0 bytes, then this is likely an error. + SourceLocation CallLoc = Call->getRParenLoc(); + SourceManager &SM = S.getSourceManager(); + if (isLiteralZero(SizeArg) && + !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { + + SourceLocation DiagLoc = SizeArg->getExprLoc(); + + // Some platforms #define bzero to __builtin_memset. See if this is the + // case, and if so, emit a better diagnostic. + if (BId == Builtin::BIbzero || + (CallLoc.isMacroID() && Lexer::getImmediateMacroName( + CallLoc, SM, S.getLangOpts()) == "bzero")) { + S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); + S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); + } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { + S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; + S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; + } + return; + } + + // If the second argument to a memset is a sizeof expression and the third + // isn't, this is also likely an error. This should catch + // 'memset(buf, sizeof(buf), 0xff)'. + if (BId == Builtin::BImemset && + doesExprLikelyComputeSize(Call->getArg(1)) && + !doesExprLikelyComputeSize(Call->getArg(2))) { + SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); + S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; + S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; + return; + } + } + + /// Check for dangerous or invalid arguments to memset(). + /// + /// This issues warnings on known problematic, dangerous or unspecified + /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' + /// function calls. + /// + /// \param Call The call expression to diagnose. + void Sema::CheckMemaccessArguments(const CallExpr *Call, + unsigned BId, + IdentifierInfo *FnName) { + assert(BId != 0); + + // It is possible to have a non-standard definition of memset. Validate + // we have enough arguments, and if not, abort further checking. + unsigned ExpectedNumArgs = + (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); + if (Call->getNumArgs() < ExpectedNumArgs) + return; + + unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || + BId == Builtin::BIstrndup ? 1 : 2); + unsigned LenArg = + (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); + const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); + + if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, + Call->getBeginLoc(), Call->getRParenLoc())) + return; + + // Catch cases like 'memset(buf, sizeof(buf), 0)'. + CheckMemaccessSize(*this, BId, Call); + + // We have special checking when the length is a sizeof expression. + QualType SizeOfArgTy = getSizeOfArgType(LenExpr); + const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); + llvm::FoldingSetNodeID SizeOfArgID; + + // Although widely used, 'bzero' is not a standard function. Be more strict + // with the argument types before allowing diagnostics and only allow the + // form bzero(ptr, sizeof(...)). + QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); + if (BId == Builtin::BIbzero && !FirstArgTy->getAs()) + return; + + for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { + const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); + SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); + + QualType DestTy = Dest->getType(); + QualType PointeeTy; + if (const PointerType *DestPtrTy = DestTy->getAs()) { + PointeeTy = DestPtrTy->getPointeeType(); + + // Never warn about void type pointers. This can be used to suppress + // false positives. + if (PointeeTy->isVoidType()) + continue; + + // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by + // actually comparing the expressions for equality. Because computing the + // expression IDs can be expensive, we only do this if the diagnostic is + // enabled. + if (SizeOfArg && + !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, + SizeOfArg->getExprLoc())) { + // We only compute IDs for expressions if the warning is enabled, and + // cache the sizeof arg's ID. + if (SizeOfArgID == llvm::FoldingSetNodeID()) + SizeOfArg->Profile(SizeOfArgID, Context, true); + llvm::FoldingSetNodeID DestID; + Dest->Profile(DestID, Context, true); + if (DestID == SizeOfArgID) { + // TODO: For strncpy() and friends, this could suggest sizeof(dst) + // over sizeof(src) as well. + unsigned ActionIdx = 0; // Default is to suggest dereferencing. + StringRef ReadableName = FnName->getName(); + + if (const UnaryOperator *UnaryOp = dyn_cast(Dest)) + if (UnaryOp->getOpcode() == UO_AddrOf) + ActionIdx = 1; // If its an address-of operator, just remove it. + if (!PointeeTy->isIncompleteType() && + (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) + ActionIdx = 2; // If the pointee's size is sizeof(char), + // suggest an explicit length. + + // If the function is defined as a builtin macro, do not show macro + // expansion. + SourceLocation SL = SizeOfArg->getExprLoc(); + SourceRange DSR = Dest->getSourceRange(); + SourceRange SSR = SizeOfArg->getSourceRange(); + SourceManager &SM = getSourceManager(); + + if (SM.isMacroArgExpansion(SL)) { + ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); + SL = SM.getSpellingLoc(SL); + DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), + SM.getSpellingLoc(DSR.getEnd())); + SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), + SM.getSpellingLoc(SSR.getEnd())); + } + + DiagRuntimeBehavior(SL, SizeOfArg, + PDiag(diag::warn_sizeof_pointer_expr_memaccess) + << ReadableName + << PointeeTy + << DestTy + << DSR + << SSR); + DiagRuntimeBehavior(SL, SizeOfArg, + PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) + << ActionIdx + << SSR); + + break; + } + } + + // Also check for cases where the sizeof argument is the exact same + // type as the memory argument, and where it points to a user-defined + // record type. + if (SizeOfArgTy != QualType()) { + if (PointeeTy->isRecordType() && + Context.typesAreCompatible(SizeOfArgTy, DestTy)) { + DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, + PDiag(diag::warn_sizeof_pointer_type_memaccess) + << FnName << SizeOfArgTy << ArgIdx + << PointeeTy << Dest->getSourceRange() + << LenExpr->getSourceRange()); + break; + } + } + } else if (DestTy->isArrayType()) { + PointeeTy = DestTy; + } + + if (PointeeTy == QualType()) + continue; + + // Always complain about dynamic classes. + bool IsContained; + if (const CXXRecordDecl *ContainedRD = + getContainedDynamicClass(PointeeTy, IsContained)) { + + unsigned OperationType = 0; + const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; + // "overwritten" if we're warning about the destination for any call + // but memcmp; otherwise a verb appropriate to the call. + if (ArgIdx != 0 || IsCmp) { + if (BId == Builtin::BImemcpy) + OperationType = 1; + else if(BId == Builtin::BImemmove) + OperationType = 2; + else if (IsCmp) + OperationType = 3; + } + + DiagRuntimeBehavior(Dest->getExprLoc(), Dest, + PDiag(diag::warn_dyn_class_memaccess) + << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName + << IsContained << ContainedRD << OperationType + << Call->getCallee()->getSourceRange()); + } else if (PointeeTy.hasNonTrivialObjCLifetime() && + BId != Builtin::BImemset) + DiagRuntimeBehavior( + Dest->getExprLoc(), Dest, + PDiag(diag::warn_arc_object_memaccess) + << ArgIdx << FnName << PointeeTy + << Call->getCallee()->getSourceRange()); + else if (const auto *RT = PointeeTy->getAs()) { + if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && + RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { + DiagRuntimeBehavior(Dest->getExprLoc(), Dest, + PDiag(diag::warn_cstruct_memaccess) + << ArgIdx << FnName << PointeeTy << 0); + SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); + } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && + RT->getDecl()->isNonTrivialToPrimitiveCopy()) { + DiagRuntimeBehavior(Dest->getExprLoc(), Dest, + PDiag(diag::warn_cstruct_memaccess) + << ArgIdx << FnName << PointeeTy << 1); + SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); + } else { + continue; + } + } else + continue; + + DiagRuntimeBehavior( + Dest->getExprLoc(), Dest, + PDiag(diag::note_bad_memaccess_silence) + << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); + break; + } + } + + // A little helper routine: ignore addition and subtraction of integer literals. + // This intentionally does not ignore all integer constant expressions because + // we don't want to remove sizeof(). + static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { + Ex = Ex->IgnoreParenCasts(); + + while (true) { + const BinaryOperator * BO = dyn_cast(Ex); + if (!BO || !BO->isAdditiveOp()) + break; + + const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); + const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); + + if (isa(RHS)) + Ex = LHS; + else if (isa(LHS)) + Ex = RHS; + else + break; + } + + return Ex; + } + + static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, + ASTContext &Context) { + // Only handle constant-sized or VLAs, but not flexible members. + if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { + // Only issue the FIXIT for arrays of size > 1. + if (CAT->getSize().getSExtValue() <= 1) + return false; + } else if (!Ty->isVariableArrayType()) { + return false; + } + return true; + } + + // Warn if the user has made the 'size' argument to strlcpy or strlcat + // be the size of the source, instead of the destination. + void Sema::CheckStrlcpycatArguments(const CallExpr *Call, + IdentifierInfo *FnName) { + + // Don't crash if the user has the wrong number of arguments + unsigned NumArgs = Call->getNumArgs(); + if ((NumArgs != 3) && (NumArgs != 4)) + return; + + const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); + const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); + const Expr *CompareWithSrc = nullptr; + + if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, + Call->getBeginLoc(), Call->getRParenLoc())) + return; + + // Look for 'strlcpy(dst, x, sizeof(x))' + if (const Expr *Ex = getSizeOfExprArg(SizeArg)) + CompareWithSrc = Ex; + else { + // Look for 'strlcpy(dst, x, strlen(x))' + if (const CallExpr *SizeCall = dyn_cast(SizeArg)) { + if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && + SizeCall->getNumArgs() == 1) + CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); + } + } + + if (!CompareWithSrc) + return; + + // Determine if the argument to sizeof/strlen is equal to the source + // argument. In principle there's all kinds of things you could do + // here, for instance creating an == expression and evaluating it with + // EvaluateAsBooleanCondition, but this uses a more direct technique: + const DeclRefExpr *SrcArgDRE = dyn_cast(SrcArg); + if (!SrcArgDRE) + return; + + const DeclRefExpr *CompareWithSrcDRE = dyn_cast(CompareWithSrc); + if (!CompareWithSrcDRE || + SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) + return; + + const Expr *OriginalSizeArg = Call->getArg(2); + Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) + << OriginalSizeArg->getSourceRange() << FnName; + + // Output a FIXIT hint if the destination is an array (rather than a + // pointer to an array). This could be enhanced to handle some + // pointers if we know the actual size, like if DstArg is 'array+2' + // we could say 'sizeof(array)-2'. + const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); + if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) + return; + + SmallString<128> sizeString; + llvm::raw_svector_ostream OS(sizeString); + OS << "sizeof("; + DstArg->printPretty(OS, nullptr, getPrintingPolicy()); + OS << ")"; + + Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) + << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), + OS.str()); + } + + /// Check if two expressions refer to the same declaration. + static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { + if (const DeclRefExpr *D1 = dyn_cast_or_null(E1)) + if (const DeclRefExpr *D2 = dyn_cast_or_null(E2)) + return D1->getDecl() == D2->getDecl(); + return false; + } + + static const Expr *getStrlenExprArg(const Expr *E) { + if (const CallExpr *CE = dyn_cast(E)) { + const FunctionDecl *FD = CE->getDirectCallee(); + if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) + return nullptr; + return CE->getArg(0)->IgnoreParenCasts(); + } + return nullptr; + } + + // Warn on anti-patterns as the 'size' argument to strncat. + // The correct size argument should look like following: + // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); + void Sema::CheckStrncatArguments(const CallExpr *CE, + IdentifierInfo *FnName) { + // Don't crash if the user has the wrong number of arguments. + if (CE->getNumArgs() < 3) + return; + const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); + const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); + const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); + + if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), + CE->getRParenLoc())) + return; + + // Identify common expressions, which are wrongly used as the size argument + // to strncat and may lead to buffer overflows. + unsigned PatternType = 0; + if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { + // - sizeof(dst) + if (referToTheSameDecl(SizeOfArg, DstArg)) + PatternType = 1; + // - sizeof(src) + else if (referToTheSameDecl(SizeOfArg, SrcArg)) + PatternType = 2; + } else if (const BinaryOperator *BE = dyn_cast(LenArg)) { + if (BE->getOpcode() == BO_Sub) { + const Expr *L = BE->getLHS()->IgnoreParenCasts(); + const Expr *R = BE->getRHS()->IgnoreParenCasts(); + // - sizeof(dst) - strlen(dst) + if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && + referToTheSameDecl(DstArg, getStrlenExprArg(R))) + PatternType = 1; + // - sizeof(src) - (anything) + else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) + PatternType = 2; + } + } + + if (PatternType == 0) + return; + + // Generate the diagnostic. + SourceLocation SL = LenArg->getBeginLoc(); + SourceRange SR = LenArg->getSourceRange(); + SourceManager &SM = getSourceManager(); + + // If the function is defined as a builtin macro, do not show macro expansion. + if (SM.isMacroArgExpansion(SL)) { + SL = SM.getSpellingLoc(SL); + SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), + SM.getSpellingLoc(SR.getEnd())); + } + + // Check if the destination is an array (rather than a pointer to an array). + QualType DstTy = DstArg->getType(); + bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, + Context); + if (!isKnownSizeArray) { + if (PatternType == 1) + Diag(SL, diag::warn_strncat_wrong_size) << SR; + else + Diag(SL, diag::warn_strncat_src_size) << SR; + return; + } + + if (PatternType == 1) + Diag(SL, diag::warn_strncat_large_size) << SR; + else + Diag(SL, diag::warn_strncat_src_size) << SR; + + SmallString<128> sizeString; + llvm::raw_svector_ostream OS(sizeString); + OS << "sizeof("; + DstArg->printPretty(OS, nullptr, getPrintingPolicy()); + OS << ") - "; + OS << "strlen("; + DstArg->printPretty(OS, nullptr, getPrintingPolicy()); + OS << ") - 1"; + + Diag(SL, diag::note_strncat_wrong_size) + << FixItHint::CreateReplacement(SR, OS.str()); + } + + namespace { + void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, + const UnaryOperator *UnaryExpr, const Decl *D) { + if (isa(D)) { + S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) + << CalleeName << 0 /*object: */ << cast(D); + return; + } + } + + void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, + const UnaryOperator *UnaryExpr) { + if (const auto *Lvalue = dyn_cast(UnaryExpr->getSubExpr())) { + const Decl *D = Lvalue->getDecl(); + if (isa(D)) + if (!dyn_cast(D)->getType()->isReferenceType()) + return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); + } + + if (const auto *Lvalue = dyn_cast(UnaryExpr->getSubExpr())) + return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, + Lvalue->getMemberDecl()); + } + + void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, + const UnaryOperator *UnaryExpr) { + const auto *Lambda = dyn_cast( + UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); + if (!Lambda) + return; + + S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) + << CalleeName << 2 /*object: lambda expression*/; + } + + void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, + const DeclRefExpr *Lvalue) { + const auto *Var = dyn_cast(Lvalue->getDecl()); + if (Var == nullptr) + return; + + S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) + << CalleeName << 0 /*object: */ << Var; + } + + void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, + const CastExpr *Cast) { + SmallString<128> SizeString; + llvm::raw_svector_ostream OS(SizeString); + + clang::CastKind Kind = Cast->getCastKind(); + if (Kind == clang::CK_BitCast && + !Cast->getSubExpr()->getType()->isFunctionPointerType()) + return; + if (Kind == clang::CK_IntegralToPointer && + !isa( + Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) + return; + + switch (Cast->getCastKind()) { + case clang::CK_BitCast: + case clang::CK_IntegralToPointer: + case clang::CK_FunctionToPointerDecay: + OS << '\''; + Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); + OS << '\''; + break; + default: + return; + } + + S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) + << CalleeName << 0 /*object: */ << OS.str(); + } + } // namespace + + /// Alerts the user that they are attempting to free a non-malloc'd object. + void Sema::CheckFreeArguments(const CallExpr *E) { + const std::string CalleeName = + dyn_cast(E->getCalleeDecl())->getQualifiedNameAsString(); + + { // Prefer something that doesn't involve a cast to make things simpler. + const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); + if (const auto *UnaryExpr = dyn_cast(Arg)) + switch (UnaryExpr->getOpcode()) { + case UnaryOperator::Opcode::UO_AddrOf: + return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); + case UnaryOperator::Opcode::UO_Plus: + return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); + default: + break; + } + + if (const auto *Lvalue = dyn_cast(Arg)) + if (Lvalue->getType()->isArrayType()) + return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); + + if (const auto *Label = dyn_cast(Arg)) { + Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) + << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); + return; + } + + if (isa(Arg)) { + Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) + << CalleeName << 1 /*object: block*/; + return; + } + } + // Maybe the cast was important, check after the other cases. + if (const auto *Cast = dyn_cast(E->getArg(0))) + return CheckFreeArgumentsCast(*this, CalleeName, Cast); + } + + void + Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, + SourceLocation ReturnLoc, + bool isObjCMethod, + const AttrVec *Attrs, + const FunctionDecl *FD) { + // Check if the return value is null but should not be. + if (((Attrs && hasSpecificAttr(*Attrs)) || + (!isObjCMethod && isNonNullType(Context, lhsType))) && + CheckNonNullExpr(*this, RetValExp)) + Diag(ReturnLoc, diag::warn_null_ret) + << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); + + // C++11 [basic.stc.dynamic.allocation]p4: + // If an allocation function declared with a non-throwing + // exception-specification fails to allocate storage, it shall return + // a null pointer. Any other allocation function that fails to allocate + // storage shall indicate failure only by throwing an exception [...] + if (FD) { + OverloadedOperatorKind Op = FD->getOverloadedOperator(); + if (Op == OO_New || Op == OO_Array_New) { + const FunctionProtoType *Proto + = FD->getType()->castAs(); + if (!Proto->isNothrow(/*ResultIfDependent*/true) && + CheckNonNullExpr(*this, RetValExp)) + Diag(ReturnLoc, diag::warn_operator_new_returns_null) + << FD << getLangOpts().CPlusPlus11; + } + } + + // PPC MMA non-pointer types are not allowed as return type. Checking the type + // here prevent the user from using a PPC MMA type as trailing return type. + if (Context.getTargetInfo().getTriple().isPPC64()) + CheckPPCMMAType(RetValExp->getType(), ReturnLoc); + } + + //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// + + /// Check for comparisons of floating point operands using != and ==. + /// Issue a warning if these are no self-comparisons, as they are not likely + /// to do what the programmer intended. + void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { + Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); + Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); + + // Special case: check for x == x (which is OK). + // Do not emit warnings for such cases. + if (DeclRefExpr* DRL = dyn_cast(LeftExprSansParen)) + if (DeclRefExpr* DRR = dyn_cast(RightExprSansParen)) + if (DRL->getDecl() == DRR->getDecl()) + return; + + // Special case: check for comparisons against literals that can be exactly + // represented by APFloat. In such cases, do not emit a warning. This + // is a heuristic: often comparison against such literals are used to + // detect if a value in a variable has not changed. This clearly can + // lead to false negatives. + if (FloatingLiteral* FLL = dyn_cast(LeftExprSansParen)) { + if (FLL->isExact()) + return; + } else + if (FloatingLiteral* FLR = dyn_cast(RightExprSansParen)) + if (FLR->isExact()) + return; + + // Check for comparisons with builtin types. + if (CallExpr* CL = dyn_cast(LeftExprSansParen)) + if (CL->getBuiltinCallee()) + return; + + if (CallExpr* CR = dyn_cast(RightExprSansParen)) + if (CR->getBuiltinCallee()) + return; + + // Emit the diagnostic. + Diag(Loc, diag::warn_floatingpoint_eq) + << LHS->getSourceRange() << RHS->getSourceRange(); + } + + //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// + //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// + + namespace { + + /// Structure recording the 'active' range of an integer-valued + /// expression. + struct IntRange { + /// The number of bits active in the int. Note that this includes exactly one + /// sign bit if !NonNegative. + unsigned Width; + + /// True if the int is known not to have negative values. If so, all leading + /// bits before Width are known zero, otherwise they are known to be the + /// same as the MSB within Width. + bool NonNegative; + + IntRange(unsigned Width, bool NonNegative) + : Width(Width), NonNegative(NonNegative) {} + + /// Number of bits excluding the sign bit. + unsigned valueBits() const { + return NonNegative ? Width : Width - 1; + } + + /// Returns the range of the bool type. + static IntRange forBoolType() { + return IntRange(1, true); + } + + /// Returns the range of an opaque value of the given integral type. + static IntRange forValueOfType(ASTContext &C, QualType T) { + return forValueOfCanonicalType(C, + T->getCanonicalTypeInternal().getTypePtr()); + } + + /// Returns the range of an opaque value of a canonical integral type. + static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { + assert(T->isCanonicalUnqualified()); + + if (const VectorType *VT = dyn_cast(T)) + T = VT->getElementType().getTypePtr(); + if (const ComplexType *CT = dyn_cast(T)) + T = CT->getElementType().getTypePtr(); + if (const AtomicType *AT = dyn_cast(T)) + T = AT->getValueType().getTypePtr(); + + if (!C.getLangOpts().CPlusPlus) { + // For enum types in C code, use the underlying datatype. + if (const EnumType *ET = dyn_cast(T)) + T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); + } else if (const EnumType *ET = dyn_cast(T)) { + // For enum types in C++, use the known bit width of the enumerators. + EnumDecl *Enum = ET->getDecl(); + // In C++11, enums can have a fixed underlying type. Use this type to + // compute the range. + if (Enum->isFixed()) { + return IntRange(C.getIntWidth(QualType(T, 0)), + !ET->isSignedIntegerOrEnumerationType()); + } + + unsigned NumPositive = Enum->getNumPositiveBits(); + unsigned NumNegative = Enum->getNumNegativeBits(); + + if (NumNegative == 0) + return IntRange(NumPositive, true/*NonNegative*/); + else + return IntRange(std::max(NumPositive + 1, NumNegative), + false/*NonNegative*/); + } + + if (const auto *EIT = dyn_cast(T)) + return IntRange(EIT->getNumBits(), EIT->isUnsigned()); + + const BuiltinType *BT = cast(T); + assert(BT->isInteger()); + + return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); + } + + /// Returns the "target" range of a canonical integral type, i.e. + /// the range of values expressible in the type. + /// + /// This matches forValueOfCanonicalType except that enums have the + /// full range of their type, not the range of their enumerators. + static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { + assert(T->isCanonicalUnqualified()); + + if (const VectorType *VT = dyn_cast(T)) + T = VT->getElementType().getTypePtr(); + if (const ComplexType *CT = dyn_cast(T)) + T = CT->getElementType().getTypePtr(); + if (const AtomicType *AT = dyn_cast(T)) + T = AT->getValueType().getTypePtr(); + if (const EnumType *ET = dyn_cast(T)) + T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); + + if (const auto *EIT = dyn_cast(T)) + return IntRange(EIT->getNumBits(), EIT->isUnsigned()); + + const BuiltinType *BT = cast(T); + assert(BT->isInteger()); + + return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); + } + + /// Returns the supremum of two ranges: i.e. their conservative merge. + static IntRange join(IntRange L, IntRange R) { + bool Unsigned = L.NonNegative && R.NonNegative; + return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, + L.NonNegative && R.NonNegative); + } + + /// Return the range of a bitwise-AND of the two ranges. + static IntRange bit_and(IntRange L, IntRange R) { + unsigned Bits = std::max(L.Width, R.Width); + bool NonNegative = false; + if (L.NonNegative) { + Bits = std::min(Bits, L.Width); + NonNegative = true; + } + if (R.NonNegative) { + Bits = std::min(Bits, R.Width); + NonNegative = true; + } + return IntRange(Bits, NonNegative); + } + + /// Return the range of a sum of the two ranges. + static IntRange sum(IntRange L, IntRange R) { + bool Unsigned = L.NonNegative && R.NonNegative; + return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, + Unsigned); + } + + /// Return the range of a difference of the two ranges. + static IntRange difference(IntRange L, IntRange R) { + // We need a 1-bit-wider range if: + // 1) LHS can be negative: least value can be reduced. + // 2) RHS can be negative: greatest value can be increased. + bool CanWiden = !L.NonNegative || !R.NonNegative; + bool Unsigned = L.NonNegative && R.Width == 0; + return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + + !Unsigned, + Unsigned); + } + + /// Return the range of a product of the two ranges. + static IntRange product(IntRange L, IntRange R) { + // If both LHS and RHS can be negative, we can form + // -2^L * -2^R = 2^(L + R) + // which requires L + R + 1 value bits to represent. + bool CanWiden = !L.NonNegative && !R.NonNegative; + bool Unsigned = L.NonNegative && R.NonNegative; + return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, + Unsigned); + } + + /// Return the range of a remainder operation between the two ranges. + static IntRange rem(IntRange L, IntRange R) { + // The result of a remainder can't be larger than the result of + // either side. The sign of the result is the sign of the LHS. + bool Unsigned = L.NonNegative; + return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, + Unsigned); + } + }; + + } // namespace + + static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, + unsigned MaxWidth) { + if (value.isSigned() && value.isNegative()) + return IntRange(value.getMinSignedBits(), false); + + if (value.getBitWidth() > MaxWidth) + value = value.trunc(MaxWidth); + + // isNonNegative() just checks the sign bit without considering + // signedness. + return IntRange(value.getActiveBits(), true); + } + + static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, + unsigned MaxWidth) { + if (result.isInt()) + return GetValueRange(C, result.getInt(), MaxWidth); + + if (result.isVector()) { + IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); + for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { + IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); + R = IntRange::join(R, El); + } + return R; + } + + if (result.isComplexInt()) { + IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); + IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); + return IntRange::join(R, I); + } + + // This can happen with lossless casts to intptr_t of "based" lvalues. + // Assume it might use arbitrary bits. + // FIXME: The only reason we need to pass the type in here is to get + // the sign right on this one case. It would be nice if APValue + // preserved this. + assert(result.isLValue() || result.isAddrLabelDiff()); + return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); + } + + static QualType GetExprType(const Expr *E) { + QualType Ty = E->getType(); + if (const AtomicType *AtomicRHS = Ty->getAs()) + Ty = AtomicRHS->getValueType(); + return Ty; + } + + /// Pseudo-evaluate the given integer expression, estimating the + /// range of values it might take. + /// + /// \param MaxWidth The width to which the value will be truncated. + /// \param Approximate If \c true, return a likely range for the result: in + /// particular, assume that arithmetic on narrower types doesn't leave + /// those types. If \c false, return a range including all possible + /// result values. + static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, + bool InConstantContext, bool Approximate) { + E = E->IgnoreParens(); + + // Try a full evaluation first. + Expr::EvalResult result; + if (E->EvaluateAsRValue(result, C, InConstantContext)) + return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); + + // I think we only want to look through implicit casts here; if the + // user has an explicit widening cast, we should treat the value as + // being of the new, wider type. + if (const auto *CE = dyn_cast(E)) { + if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) + return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, + Approximate); + + IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); + + bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || + CE->getCastKind() == CK_BooleanToSignedIntegral; + + // Assume that non-integer casts can span the full range of the type. + if (!isIntegerCast) + return OutputTypeRange; + + IntRange SubRange = GetExprRange(C, CE->getSubExpr(), + std::min(MaxWidth, OutputTypeRange.Width), + InConstantContext, Approximate); + + // Bail out if the subexpr's range is as wide as the cast type. + if (SubRange.Width >= OutputTypeRange.Width) + return OutputTypeRange; + + // Otherwise, we take the smaller width, and we're non-negative if + // either the output type or the subexpr is. + return IntRange(SubRange.Width, + SubRange.NonNegative || OutputTypeRange.NonNegative); + } + + if (const auto *CO = dyn_cast(E)) { + // If we can fold the condition, just take that operand. + bool CondResult; + if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) + return GetExprRange(C, + CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), + MaxWidth, InConstantContext, Approximate); + + // Otherwise, conservatively merge. + // GetExprRange requires an integer expression, but a throw expression + // results in a void type. + Expr *E = CO->getTrueExpr(); + IntRange L = E->getType()->isVoidType() + ? IntRange{0, true} + : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); + E = CO->getFalseExpr(); + IntRange R = E->getType()->isVoidType() + ? IntRange{0, true} + : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); + return IntRange::join(L, R); + } + + if (const auto *BO = dyn_cast(E)) { + IntRange (*Combine)(IntRange, IntRange) = IntRange::join; + + switch (BO->getOpcode()) { + case BO_Cmp: + llvm_unreachable("builtin <=> should have class type"); + + // Boolean-valued operations are single-bit and positive. + case BO_LAnd: + case BO_LOr: + case BO_LT: + case BO_GT: + case BO_LE: + case BO_GE: + case BO_EQ: + case BO_NE: + return IntRange::forBoolType(); + + // The type of the assignments is the type of the LHS, so the RHS + // is not necessarily the same type. + case BO_MulAssign: + case BO_DivAssign: + case BO_RemAssign: + case BO_AddAssign: + case BO_SubAssign: + case BO_XorAssign: + case BO_OrAssign: + // TODO: bitfields? + return IntRange::forValueOfType(C, GetExprType(E)); + + // Simple assignments just pass through the RHS, which will have + // been coerced to the LHS type. + case BO_Assign: + // TODO: bitfields? + return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, + Approximate); + + // Operations with opaque sources are black-listed. + case BO_PtrMemD: + case BO_PtrMemI: + return IntRange::forValueOfType(C, GetExprType(E)); + + // Bitwise-and uses the *infinum* of the two source ranges. + case BO_And: + case BO_AndAssign: + Combine = IntRange::bit_and; + break; + + // Left shift gets black-listed based on a judgement call. + case BO_Shl: + // ...except that we want to treat '1 << (blah)' as logically + // positive. It's an important idiom. + if (IntegerLiteral *I + = dyn_cast(BO->getLHS()->IgnoreParenCasts())) { + if (I->getValue() == 1) { + IntRange R = IntRange::forValueOfType(C, GetExprType(E)); + return IntRange(R.Width, /*NonNegative*/ true); + } + } + LLVM_FALLTHROUGH; + + case BO_ShlAssign: + return IntRange::forValueOfType(C, GetExprType(E)); + + // Right shift by a constant can narrow its left argument. + case BO_Shr: + case BO_ShrAssign: { + IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, + Approximate); + + // If the shift amount is a positive constant, drop the width by + // that much. + if (Optional shift = + BO->getRHS()->getIntegerConstantExpr(C)) { + if (shift->isNonNegative()) { + unsigned zext = shift->getZExtValue(); + if (zext >= L.Width) + L.Width = (L.NonNegative ? 0 : 1); + else + L.Width -= zext; + } + } + + return L; + } + + // Comma acts as its right operand. + case BO_Comma: + return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, + Approximate); + + case BO_Add: + if (!Approximate) + Combine = IntRange::sum; + break; + + case BO_Sub: + if (BO->getLHS()->getType()->isPointerType()) + return IntRange::forValueOfType(C, GetExprType(E)); + if (!Approximate) + Combine = IntRange::difference; + break; + + case BO_Mul: + if (!Approximate) + Combine = IntRange::product; + break; + + // The width of a division result is mostly determined by the size + // of the LHS. + case BO_Div: { + // Don't 'pre-truncate' the operands. + unsigned opWidth = C.getIntWidth(GetExprType(E)); + IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, + Approximate); + + // If the divisor is constant, use that. + if (Optional divisor = + BO->getRHS()->getIntegerConstantExpr(C)) { + unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) + if (log2 >= L.Width) + L.Width = (L.NonNegative ? 0 : 1); + else + L.Width = std::min(L.Width - log2, MaxWidth); + return L; + } + + // Otherwise, just use the LHS's width. + // FIXME: This is wrong if the LHS could be its minimal value and the RHS + // could be -1. + IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, + Approximate); + return IntRange(L.Width, L.NonNegative && R.NonNegative); + } + + case BO_Rem: + Combine = IntRange::rem; + break; + + // The default behavior is okay for these. + case BO_Xor: + case BO_Or: + break; + } + + // Combine the two ranges, but limit the result to the type in which we + // performed the computation. + QualType T = GetExprType(E); + unsigned opWidth = C.getIntWidth(T); + IntRange L = + GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); + IntRange R = + GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); + IntRange C = Combine(L, R); + C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); + C.Width = std::min(C.Width, MaxWidth); + return C; + } + + if (const auto *UO = dyn_cast(E)) { + switch (UO->getOpcode()) { + // Boolean-valued operations are white-listed. + case UO_LNot: + return IntRange::forBoolType(); + + // Operations with opaque sources are black-listed. + case UO_Deref: + case UO_AddrOf: // should be impossible + return IntRange::forValueOfType(C, GetExprType(E)); + + default: + return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, + Approximate); + } + } + + if (const auto *OVE = dyn_cast(E)) + return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, + Approximate); + + if (const auto *BitField = E->getSourceBitField()) + return IntRange(BitField->getBitWidthValue(C), + BitField->getType()->isUnsignedIntegerOrEnumerationType()); + + return IntRange::forValueOfType(C, GetExprType(E)); + } + + static IntRange GetExprRange(ASTContext &C, const Expr *E, + bool InConstantContext, bool Approximate) { + return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, + Approximate); + } + + /// Checks whether the given value, which currently has the given + /// source semantics, has the same value when coerced through the + /// target semantics. + static bool IsSameFloatAfterCast(const llvm::APFloat &value, + const llvm::fltSemantics &Src, + const llvm::fltSemantics &Tgt) { + llvm::APFloat truncated = value; + + bool ignored; + truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); + truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); + + return truncated.bitwiseIsEqual(value); + } + + /// Checks whether the given value, which currently has the given + /// source semantics, has the same value when coerced through the + /// target semantics. + /// + /// The value might be a vector of floats (or a complex number). + static bool IsSameFloatAfterCast(const APValue &value, + const llvm::fltSemantics &Src, + const llvm::fltSemantics &Tgt) { + if (value.isFloat()) + return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); + + if (value.isVector()) { + for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) + if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) + return false; + return true; + } + + assert(value.isComplexFloat()); + return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && + IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); + } + + static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, + bool IsListInit = false); + + static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { + // Suppress cases where we are comparing against an enum constant. + if (const DeclRefExpr *DR = + dyn_cast(E->IgnoreParenImpCasts())) + if (isa(DR->getDecl())) + return true; + + // Suppress cases where the value is expanded from a macro, unless that macro + // is how a language represents a boolean literal. This is the case in both C + // and Objective-C. + SourceLocation BeginLoc = E->getBeginLoc(); + if (BeginLoc.isMacroID()) { + StringRef MacroName = Lexer::getImmediateMacroName( + BeginLoc, S.getSourceManager(), S.getLangOpts()); + return MacroName != "YES" && MacroName != "NO" && + MacroName != "true" && MacroName != "false"; + } + + return false; + } + + static bool isKnownToHaveUnsignedValue(Expr *E) { + return E->getType()->isIntegerType() && + (!E->getType()->isSignedIntegerType() || + !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); + } + + namespace { + /// The promoted range of values of a type. In general this has the + /// following structure: + /// + /// |-----------| . . . |-----------| + /// ^ ^ ^ ^ + /// Min HoleMin HoleMax Max + /// + /// ... where there is only a hole if a signed type is promoted to unsigned + /// (in which case Min and Max are the smallest and largest representable + /// values). + struct PromotedRange { + // Min, or HoleMax if there is a hole. + llvm::APSInt PromotedMin; + // Max, or HoleMin if there is a hole. + llvm::APSInt PromotedMax; + + PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { + if (R.Width == 0) + PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); + else if (R.Width >= BitWidth && !Unsigned) { + // Promotion made the type *narrower*. This happens when promoting + // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. + // Treat all values of 'signed int' as being in range for now. + PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); + PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); + } else { + PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) + .extOrTrunc(BitWidth); + PromotedMin.setIsUnsigned(Unsigned); + + PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) + .extOrTrunc(BitWidth); + PromotedMax.setIsUnsigned(Unsigned); + } + } + + // Determine whether this range is contiguous (has no hole). + bool isContiguous() const { return PromotedMin <= PromotedMax; } + + // Where a constant value is within the range. + enum ComparisonResult { + LT = 0x1, + LE = 0x2, + GT = 0x4, + GE = 0x8, + EQ = 0x10, + NE = 0x20, + InRangeFlag = 0x40, + + Less = LE | LT | NE, + Min = LE | InRangeFlag, + InRange = InRangeFlag, + Max = GE | InRangeFlag, + Greater = GE | GT | NE, + + OnlyValue = LE | GE | EQ | InRangeFlag, + InHole = NE + }; + + ComparisonResult compare(const llvm::APSInt &Value) const { + assert(Value.getBitWidth() == PromotedMin.getBitWidth() && + Value.isUnsigned() == PromotedMin.isUnsigned()); + if (!isContiguous()) { + assert(Value.isUnsigned() && "discontiguous range for signed compare"); + if (Value.isMinValue()) return Min; + if (Value.isMaxValue()) return Max; + if (Value >= PromotedMin) return InRange; + if (Value <= PromotedMax) return InRange; + return InHole; + } + + switch (llvm::APSInt::compareValues(Value, PromotedMin)) { + case -1: return Less; + case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; + case 1: + switch (llvm::APSInt::compareValues(Value, PromotedMax)) { + case -1: return InRange; + case 0: return Max; + case 1: return Greater; + } + } + + llvm_unreachable("impossible compare result"); + } + + static llvm::Optional + constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { + if (Op == BO_Cmp) { + ComparisonResult LTFlag = LT, GTFlag = GT; + if (ConstantOnRHS) std::swap(LTFlag, GTFlag); + + if (R & EQ) return StringRef("'std::strong_ordering::equal'"); + if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); + if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); + return llvm::None; + } + + ComparisonResult TrueFlag, FalseFlag; + if (Op == BO_EQ) { + TrueFlag = EQ; + FalseFlag = NE; + } else if (Op == BO_NE) { + TrueFlag = NE; + FalseFlag = EQ; + } else { + if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { + TrueFlag = LT; + FalseFlag = GE; + } else { + TrueFlag = GT; + FalseFlag = LE; + } + if (Op == BO_GE || Op == BO_LE) + std::swap(TrueFlag, FalseFlag); + } + if (R & TrueFlag) + return StringRef("true"); + if (R & FalseFlag) + return StringRef("false"); + return llvm::None; + } + }; + } + + static bool HasEnumType(Expr *E) { + // Strip off implicit integral promotions. + while (ImplicitCastExpr *ICE = dyn_cast(E)) { + if (ICE->getCastKind() != CK_IntegralCast && + ICE->getCastKind() != CK_NoOp) + break; + E = ICE->getSubExpr(); + } + + return E->getType()->isEnumeralType(); + } + + static int classifyConstantValue(Expr *Constant) { + // The values of this enumeration are used in the diagnostics + // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. + enum ConstantValueKind { + Miscellaneous = 0, + LiteralTrue, + LiteralFalse + }; + if (auto *BL = dyn_cast(Constant)) + return BL->getValue() ? ConstantValueKind::LiteralTrue + : ConstantValueKind::LiteralFalse; + return ConstantValueKind::Miscellaneous; + } + + static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, + Expr *Constant, Expr *Other, + const llvm::APSInt &Value, + bool RhsConstant) { + if (S.inTemplateInstantiation()) + return false; + + Expr *OriginalOther = Other; + + Constant = Constant->IgnoreParenImpCasts(); + Other = Other->IgnoreParenImpCasts(); + + // Suppress warnings on tautological comparisons between values of the same + // enumeration type. There are only two ways we could warn on this: + // - If the constant is outside the range of representable values of + // the enumeration. In such a case, we should warn about the cast + // to enumeration type, not about the comparison. + // - If the constant is the maximum / minimum in-range value. For an + // enumeratin type, such comparisons can be meaningful and useful. + if (Constant->getType()->isEnumeralType() && + S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) + return false; + + IntRange OtherValueRange = GetExprRange( + S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); + + QualType OtherT = Other->getType(); + if (const auto *AT = OtherT->getAs()) + OtherT = AT->getValueType(); + IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); + + // Special case for ObjC BOOL on targets where its a typedef for a signed char + // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. + bool IsObjCSignedCharBool = S.getLangOpts().ObjC && + S.NSAPIObj->isObjCBOOLType(OtherT) && + OtherT->isSpecificBuiltinType(BuiltinType::SChar); + + // Whether we're treating Other as being a bool because of the form of + // expression despite it having another type (typically 'int' in C). + bool OtherIsBooleanDespiteType = + !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); + if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) + OtherTypeRange = OtherValueRange = IntRange::forBoolType(); + + // Check if all values in the range of possible values of this expression + // lead to the same comparison outcome. + PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), + Value.isUnsigned()); + auto Cmp = OtherPromotedValueRange.compare(Value); + auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); + if (!Result) + return false; + + // Also consider the range determined by the type alone. This allows us to + // classify the warning under the proper diagnostic group. + bool TautologicalTypeCompare = false; + { + PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), + Value.isUnsigned()); + auto TypeCmp = OtherPromotedTypeRange.compare(Value); + if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, + RhsConstant)) { + TautologicalTypeCompare = true; + Cmp = TypeCmp; + Result = TypeResult; + } + } + + // Don't warn if the non-constant operand actually always evaluates to the + // same value. + if (!TautologicalTypeCompare && OtherValueRange.Width == 0) + return false; + + // Suppress the diagnostic for an in-range comparison if the constant comes + // from a macro or enumerator. We don't want to diagnose + // + // some_long_value <= INT_MAX + // + // when sizeof(int) == sizeof(long). + bool InRange = Cmp & PromotedRange::InRangeFlag; + if (InRange && IsEnumConstOrFromMacro(S, Constant)) + return false; + + // A comparison of an unsigned bit-field against 0 is really a type problem, + // even though at the type level the bit-field might promote to 'signed int'. + if (Other->refersToBitField() && InRange && Value == 0 && + Other->getType()->isUnsignedIntegerOrEnumerationType()) + TautologicalTypeCompare = true; + + // If this is a comparison to an enum constant, include that + // constant in the diagnostic. + const EnumConstantDecl *ED = nullptr; + if (const DeclRefExpr *DR = dyn_cast(Constant)) + ED = dyn_cast(DR->getDecl()); + + // Should be enough for uint128 (39 decimal digits) + SmallString<64> PrettySourceValue; + llvm::raw_svector_ostream OS(PrettySourceValue); + if (ED) { + OS << '\'' << *ED << "' (" << Value << ")"; + } else if (auto *BL = dyn_cast( + Constant->IgnoreParenImpCasts())) { + OS << (BL->getValue() ? "YES" : "NO"); + } else { + OS << Value; + } + + if (!TautologicalTypeCompare) { + S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) + << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative + << E->getOpcodeStr() << OS.str() << *Result + << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); + return true; + } + + if (IsObjCSignedCharBool) { + S.DiagRuntimeBehavior(E->getOperatorLoc(), E, + S.PDiag(diag::warn_tautological_compare_objc_bool) + << OS.str() << *Result); + return true; + } + + // FIXME: We use a somewhat different formatting for the in-range cases and + // cases involving boolean values for historical reasons. We should pick a + // consistent way of presenting these diagnostics. + if (!InRange || Other->isKnownToHaveBooleanValue()) { + + S.DiagRuntimeBehavior( + E->getOperatorLoc(), E, + S.PDiag(!InRange ? diag::warn_out_of_range_compare + : diag::warn_tautological_bool_compare) + << OS.str() << classifyConstantValue(Constant) << OtherT + << OtherIsBooleanDespiteType << *Result + << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); + } else { + bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; + unsigned Diag = + (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) + ? (HasEnumType(OriginalOther) + ? diag::warn_unsigned_enum_always_true_comparison + : IsCharTy ? diag::warn_unsigned_char_always_true_comparison + : diag::warn_unsigned_always_true_comparison) + : diag::warn_tautological_constant_compare; + + S.Diag(E->getOperatorLoc(), Diag) + << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result + << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); + } + + return true; + } + + /// Analyze the operands of the given comparison. Implements the + /// fallback case from AnalyzeComparison. + static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { + AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); + AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); + } + + /// Implements -Wsign-compare. + /// + /// \param E the binary operator to check for warnings + static void AnalyzeComparison(Sema &S, BinaryOperator *E) { + // The type the comparison is being performed in. + QualType T = E->getLHS()->getType(); + + // Only analyze comparison operators where both sides have been converted to + // the same type. + if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) + return AnalyzeImpConvsInComparison(S, E); + + // Don't analyze value-dependent comparisons directly. + if (E->isValueDependent()) + return AnalyzeImpConvsInComparison(S, E); + + Expr *LHS = E->getLHS(); + Expr *RHS = E->getRHS(); + + if (T->isIntegralType(S.Context)) { + Optional RHSValue = RHS->getIntegerConstantExpr(S.Context); + Optional LHSValue = LHS->getIntegerConstantExpr(S.Context); + + // We don't care about expressions whose result is a constant. + if (RHSValue && LHSValue) + return AnalyzeImpConvsInComparison(S, E); + + // We only care about expressions where just one side is literal + if ((bool)RHSValue ^ (bool)LHSValue) { + // Is the constant on the RHS or LHS? + const bool RhsConstant = (bool)RHSValue; + Expr *Const = RhsConstant ? RHS : LHS; + Expr *Other = RhsConstant ? LHS : RHS; + const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; + + // Check whether an integer constant comparison results in a value + // of 'true' or 'false'. + if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) + return AnalyzeImpConvsInComparison(S, E); + } + } + + if (!T->hasUnsignedIntegerRepresentation()) { + // We don't do anything special if this isn't an unsigned integral + // comparison: we're only interested in integral comparisons, and + // signed comparisons only happen in cases we don't care to warn about. + return AnalyzeImpConvsInComparison(S, E); + } + + LHS = LHS->IgnoreParenImpCasts(); + RHS = RHS->IgnoreParenImpCasts(); + + if (!S.getLangOpts().CPlusPlus) { + // Avoid warning about comparison of integers with different signs when + // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of + // the type of `E`. + if (const auto *TET = dyn_cast(LHS->getType())) + LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); + if (const auto *TET = dyn_cast(RHS->getType())) + RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); + } + + // Check to see if one of the (unmodified) operands is of different + // signedness. + Expr *signedOperand, *unsignedOperand; + if (LHS->getType()->hasSignedIntegerRepresentation()) { + assert(!RHS->getType()->hasSignedIntegerRepresentation() && + "unsigned comparison between two signed integer expressions?"); + signedOperand = LHS; + unsignedOperand = RHS; + } else if (RHS->getType()->hasSignedIntegerRepresentation()) { + signedOperand = RHS; + unsignedOperand = LHS; + } else { + return AnalyzeImpConvsInComparison(S, E); + } + + // Otherwise, calculate the effective range of the signed operand. + IntRange signedRange = GetExprRange( + S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); + + // Go ahead and analyze implicit conversions in the operands. Note + // that we skip the implicit conversions on both sides. + AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); + AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); + + // If the signed range is non-negative, -Wsign-compare won't fire. + if (signedRange.NonNegative) + return; + + // For (in)equality comparisons, if the unsigned operand is a + // constant which cannot collide with a overflowed signed operand, + // then reinterpreting the signed operand as unsigned will not + // change the result of the comparison. + if (E->isEqualityOp()) { + unsigned comparisonWidth = S.Context.getIntWidth(T); + IntRange unsignedRange = + GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), + /*Approximate*/ true); + + // We should never be unable to prove that the unsigned operand is + // non-negative. + assert(unsignedRange.NonNegative && "unsigned range includes negative?"); + + if (unsignedRange.Width < comparisonWidth) + return; + } + + S.DiagRuntimeBehavior(E->getOperatorLoc(), E, + S.PDiag(diag::warn_mixed_sign_comparison) + << LHS->getType() << RHS->getType() + << LHS->getSourceRange() << RHS->getSourceRange()); + } + + /// Analyzes an attempt to assign the given value to a bitfield. + /// + /// Returns true if there was something fishy about the attempt. + static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, + SourceLocation InitLoc) { + assert(Bitfield->isBitField()); + if (Bitfield->isInvalidDecl()) + return false; + + // White-list bool bitfields. + QualType BitfieldType = Bitfield->getType(); + if (BitfieldType->isBooleanType()) + return false; + + if (BitfieldType->isEnumeralType()) { + EnumDecl *BitfieldEnumDecl = BitfieldType->castAs()->getDecl(); + // If the underlying enum type was not explicitly specified as an unsigned + // type and the enum contain only positive values, MSVC++ will cause an + // inconsistency by storing this as a signed type. + if (S.getLangOpts().CPlusPlus11 && + !BitfieldEnumDecl->getIntegerTypeSourceInfo() && + BitfieldEnumDecl->getNumPositiveBits() > 0 && + BitfieldEnumDecl->getNumNegativeBits() == 0) { + S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) + << BitfieldEnumDecl; + } + } + + if (Bitfield->getType()->isBooleanType()) + return false; + + // Ignore value- or type-dependent expressions. + if (Bitfield->getBitWidth()->isValueDependent() || + Bitfield->getBitWidth()->isTypeDependent() || + Init->isValueDependent() || + Init->isTypeDependent()) + return false; + + Expr *OriginalInit = Init->IgnoreParenImpCasts(); + unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); + + Expr::EvalResult Result; + if (!OriginalInit->EvaluateAsInt(Result, S.Context, + Expr::SE_AllowSideEffects)) { + // The RHS is not constant. If the RHS has an enum type, make sure the + // bitfield is wide enough to hold all the values of the enum without + // truncation. + if (const auto *EnumTy = OriginalInit->getType()->getAs()) { + EnumDecl *ED = EnumTy->getDecl(); + bool SignedBitfield = BitfieldType->isSignedIntegerType(); + + // Enum types are implicitly signed on Windows, so check if there are any + // negative enumerators to see if the enum was intended to be signed or + // not. + bool SignedEnum = ED->getNumNegativeBits() > 0; + + // Check for surprising sign changes when assigning enum values to a + // bitfield of different signedness. If the bitfield is signed and we + // have exactly the right number of bits to store this unsigned enum, + // suggest changing the enum to an unsigned type. This typically happens + // on Windows where unfixed enums always use an underlying type of 'int'. + unsigned DiagID = 0; + if (SignedEnum && !SignedBitfield) { + DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; + } else if (SignedBitfield && !SignedEnum && + ED->getNumPositiveBits() == FieldWidth) { + DiagID = diag::warn_signed_bitfield_enum_conversion; + } + + if (DiagID) { + S.Diag(InitLoc, DiagID) << Bitfield << ED; + TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); + SourceRange TypeRange = + TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); + S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) + << SignedEnum << TypeRange; + } + + // Compute the required bitwidth. If the enum has negative values, we need + // one more bit than the normal number of positive bits to represent the + // sign bit. + unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, + ED->getNumNegativeBits()) + : ED->getNumPositiveBits(); + + // Check the bitwidth. + if (BitsNeeded > FieldWidth) { + Expr *WidthExpr = Bitfield->getBitWidth(); + S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) + << Bitfield << ED; + S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) + << BitsNeeded << ED << WidthExpr->getSourceRange(); + } + } + + return false; + } + + llvm::APSInt Value = Result.Val.getInt(); + + unsigned OriginalWidth = Value.getBitWidth(); + + if (!Value.isSigned() || Value.isNegative()) + if (UnaryOperator *UO = dyn_cast(OriginalInit)) + if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) + OriginalWidth = Value.getMinSignedBits(); + + if (OriginalWidth <= FieldWidth) + return false; + + // Compute the value which the bitfield will contain. + llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); + TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); + + // Check whether the stored value is equal to the original value. + TruncatedValue = TruncatedValue.extend(OriginalWidth); + if (llvm::APSInt::isSameValue(Value, TruncatedValue)) + return false; + + // Special-case bitfields of width 1: booleans are naturally 0/1, and + // therefore don't strictly fit into a signed bitfield of width 1. + if (FieldWidth == 1 && Value == 1) + return false; + + std::string PrettyValue = toString(Value, 10); + std::string PrettyTrunc = toString(TruncatedValue, 10); + + S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) + << PrettyValue << PrettyTrunc << OriginalInit->getType() + << Init->getSourceRange(); + + return true; + } + + /// Analyze the given simple or compound assignment for warning-worthy + /// operations. + static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { + // Just recurse on the LHS. + AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); + + // We want to recurse on the RHS as normal unless we're assigning to + // a bitfield. + if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { + if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), + E->getOperatorLoc())) { + // Recurse, ignoring any implicit conversions on the RHS. + return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), + E->getOperatorLoc()); + } + } + + AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); + + // Diagnose implicitly sequentially-consistent atomic assignment. + if (E->getLHS()->getType()->isAtomicType()) + S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); + } + + /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. + static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, + SourceLocation CContext, unsigned diag, + bool pruneControlFlow = false) { + if (pruneControlFlow) { + S.DiagRuntimeBehavior(E->getExprLoc(), E, + S.PDiag(diag) + << SourceType << T << E->getSourceRange() + << SourceRange(CContext)); + return; + } + S.Diag(E->getExprLoc(), diag) + << SourceType << T << E->getSourceRange() << SourceRange(CContext); + } + + /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. + static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, + SourceLocation CContext, + unsigned diag, bool pruneControlFlow = false) { + DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); + } + + static bool isObjCSignedCharBool(Sema &S, QualType Ty) { + return Ty->isSpecificBuiltinType(BuiltinType::SChar) && + S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); + } + + static void adornObjCBoolConversionDiagWithTernaryFixit( + Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { + Expr *Ignored = SourceExpr->IgnoreImplicit(); + if (const auto *OVE = dyn_cast(Ignored)) + Ignored = OVE->getSourceExpr(); + bool NeedsParens = isa(Ignored) || + isa(Ignored) || + isa(Ignored); + SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); + if (NeedsParens) + Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") + << FixItHint::CreateInsertion(EndLoc, ")"); + Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); + } + + /// Diagnose an implicit cast from a floating point value to an integer value. + static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, + SourceLocation CContext) { + const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); + const bool PruneWarnings = S.inTemplateInstantiation(); + + Expr *InnerE = E->IgnoreParenImpCasts(); + // We also want to warn on, e.g., "int i = -1.234" + if (UnaryOperator *UOp = dyn_cast(InnerE)) + if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) + InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); + + const bool IsLiteral = + isa(E) || isa(InnerE); + + llvm::APFloat Value(0.0); + bool IsConstant = + E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); + if (!IsConstant) { + if (isObjCSignedCharBool(S, T)) { + return adornObjCBoolConversionDiagWithTernaryFixit( + S, E, + S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) + << E->getType()); + } + + return DiagnoseImpCast(S, E, T, CContext, + diag::warn_impcast_float_integer, PruneWarnings); + } + + bool isExact = false; + + llvm::APSInt IntegerValue(S.Context.getIntWidth(T), + T->hasUnsignedIntegerRepresentation()); + llvm::APFloat::opStatus Result = Value.convertToInteger( + IntegerValue, llvm::APFloat::rmTowardZero, &isExact); + + // FIXME: Force the precision of the source value down so we don't print + // digits which are usually useless (we don't really care here if we + // truncate a digit by accident in edge cases). Ideally, APFloat::toString + // would automatically print the shortest representation, but it's a bit + // tricky to implement. + SmallString<16> PrettySourceValue; + unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); + precision = (precision * 59 + 195) / 196; + Value.toString(PrettySourceValue, precision); + + if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { + return adornObjCBoolConversionDiagWithTernaryFixit( + S, E, + S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) + << PrettySourceValue); + } + + if (Result == llvm::APFloat::opOK && isExact) { + if (IsLiteral) return; + return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, + PruneWarnings); + } + + // Conversion of a floating-point value to a non-bool integer where the + // integral part cannot be represented by the integer type is undefined. + if (!IsBool && Result == llvm::APFloat::opInvalidOp) + return DiagnoseImpCast( + S, E, T, CContext, + IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range + : diag::warn_impcast_float_to_integer_out_of_range, + PruneWarnings); + + unsigned DiagID = 0; + if (IsLiteral) { + // Warn on floating point literal to integer. + DiagID = diag::warn_impcast_literal_float_to_integer; + } else if (IntegerValue == 0) { + if (Value.isZero()) { // Skip -0.0 to 0 conversion. + return DiagnoseImpCast(S, E, T, CContext, + diag::warn_impcast_float_integer, PruneWarnings); + } + // Warn on non-zero to zero conversion. + DiagID = diag::warn_impcast_float_to_integer_zero; + } else { + if (IntegerValue.isUnsigned()) { + if (!IntegerValue.isMaxValue()) { + return DiagnoseImpCast(S, E, T, CContext, + diag::warn_impcast_float_integer, PruneWarnings); + } + } else { // IntegerValue.isSigned() + if (!IntegerValue.isMaxSignedValue() && + !IntegerValue.isMinSignedValue()) { + return DiagnoseImpCast(S, E, T, CContext, + diag::warn_impcast_float_integer, PruneWarnings); + } + } + // Warn on evaluatable floating point expression to integer conversion. + DiagID = diag::warn_impcast_float_to_integer; + } + + SmallString<16> PrettyTargetValue; + if (IsBool) + PrettyTargetValue = Value.isZero() ? "false" : "true"; + else + IntegerValue.toString(PrettyTargetValue); + + if (PruneWarnings) { + S.DiagRuntimeBehavior(E->getExprLoc(), E, + S.PDiag(DiagID) + << E->getType() << T.getUnqualifiedType() + << PrettySourceValue << PrettyTargetValue + << E->getSourceRange() << SourceRange(CContext)); + } else { + S.Diag(E->getExprLoc(), DiagID) + << E->getType() << T.getUnqualifiedType() << PrettySourceValue + << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); + } + } + + /// Analyze the given compound assignment for the possible losing of + /// floating-point precision. + static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { + assert(isa(E) && + "Must be compound assignment operation"); + // Recurse on the LHS and RHS in here + AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); + AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); + + if (E->getLHS()->getType()->isAtomicType()) + S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); + + // Now check the outermost expression + const auto *ResultBT = E->getLHS()->getType()->getAs(); + const auto *RBT = cast(E) + ->getComputationResultType() + ->getAs(); + + // The below checks assume source is floating point. + if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; + + // If source is floating point but target is an integer. + if (ResultBT->isInteger()) + return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), + E->getExprLoc(), diag::warn_impcast_float_integer); + + if (!ResultBT->isFloatingPoint()) + return; + + // If both source and target are floating points, warn about losing precision. + int Order = S.getASTContext().getFloatingTypeSemanticOrder( + QualType(ResultBT, 0), QualType(RBT, 0)); + if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) + // warn about dropping FP rank. + DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), + diag::warn_impcast_float_result_precision); + } + + static std::string PrettyPrintInRange(const llvm::APSInt &Value, + IntRange Range) { + if (!Range.Width) return "0"; + + llvm::APSInt ValueInRange = Value; + ValueInRange.setIsSigned(!Range.NonNegative); + ValueInRange = ValueInRange.trunc(Range.Width); + return toString(ValueInRange, 10); + } + + static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { + if (!isa(Ex)) + return false; + + Expr *InnerE = Ex->IgnoreParenImpCasts(); + const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); + const Type *Source = + S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); + if (Target->isDependentType()) + return false; + + const BuiltinType *FloatCandidateBT = + dyn_cast(ToBool ? Source : Target); + const Type *BoolCandidateType = ToBool ? Target : Source; + + return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && + FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); + } + + static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, + SourceLocation CC) { + unsigned NumArgs = TheCall->getNumArgs(); + for (unsigned i = 0; i < NumArgs; ++i) { + Expr *CurrA = TheCall->getArg(i); + if (!IsImplicitBoolFloatConversion(S, CurrA, true)) + continue; + + bool IsSwapped = ((i > 0) && + IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); + IsSwapped |= ((i < (NumArgs - 1)) && + IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); + if (IsSwapped) { + // Warn on this floating-point to bool conversion. + DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), + CurrA->getType(), CC, + diag::warn_impcast_floating_point_to_bool); + } + } + } + + static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, + SourceLocation CC) { + if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, + E->getExprLoc())) + return; + + // Don't warn on functions which have return type nullptr_t. + if (isa(E)) + return; + + // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). + const Expr::NullPointerConstantKind NullKind = + E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); + if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) + return; + + // Return if target type is a safe conversion. + if (T->isAnyPointerType() || T->isBlockPointerType() || + T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) + return; + + SourceLocation Loc = E->getSourceRange().getBegin(); + + // Venture through the macro stacks to get to the source of macro arguments. + // The new location is a better location than the complete location that was + // passed in. + Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); + CC = S.SourceMgr.getTopMacroCallerLoc(CC); + + // __null is usually wrapped in a macro. Go up a macro if that is the case. + if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { + StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( + Loc, S.SourceMgr, S.getLangOpts()); + if (MacroName == "NULL") + Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); + } + + // Only warn if the null and context location are in the same macro expansion. + if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) + return; + + S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) + << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) + << FixItHint::CreateReplacement(Loc, + S.getFixItZeroLiteralForType(T, Loc)); + } + + static void checkObjCArrayLiteral(Sema &S, QualType TargetType, + ObjCArrayLiteral *ArrayLiteral); + + static void + checkObjCDictionaryLiteral(Sema &S, QualType TargetType, + ObjCDictionaryLiteral *DictionaryLiteral); + + /// Check a single element within a collection literal against the + /// target element type. + static void checkObjCCollectionLiteralElement(Sema &S, + QualType TargetElementType, + Expr *Element, + unsigned ElementKind) { + // Skip a bitcast to 'id' or qualified 'id'. + if (auto ICE = dyn_cast(Element)) { + if (ICE->getCastKind() == CK_BitCast && + ICE->getSubExpr()->getType()->getAs()) + Element = ICE->getSubExpr(); + } + + QualType ElementType = Element->getType(); + ExprResult ElementResult(Element); + if (ElementType->getAs() && + S.CheckSingleAssignmentConstraints(TargetElementType, + ElementResult, + false, false) + != Sema::Compatible) { + S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) + << ElementType << ElementKind << TargetElementType + << Element->getSourceRange(); + } + + if (auto ArrayLiteral = dyn_cast(Element)) + checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); + else if (auto DictionaryLiteral = dyn_cast(Element)) + checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); + } + + /// Check an Objective-C array literal being converted to the given + /// target type. + static void checkObjCArrayLiteral(Sema &S, QualType TargetType, + ObjCArrayLiteral *ArrayLiteral) { + if (!S.NSArrayDecl) + return; + + const auto *TargetObjCPtr = TargetType->getAs(); + if (!TargetObjCPtr) + return; + + if (TargetObjCPtr->isUnspecialized() || + TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() + != S.NSArrayDecl->getCanonicalDecl()) + return; + + auto TypeArgs = TargetObjCPtr->getTypeArgs(); + if (TypeArgs.size() != 1) + return; + + QualType TargetElementType = TypeArgs[0]; + for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { + checkObjCCollectionLiteralElement(S, TargetElementType, + ArrayLiteral->getElement(I), + 0); + } + } + + /// Check an Objective-C dictionary literal being converted to the given + /// target type. + static void + checkObjCDictionaryLiteral(Sema &S, QualType TargetType, + ObjCDictionaryLiteral *DictionaryLiteral) { + if (!S.NSDictionaryDecl) + return; + + const auto *TargetObjCPtr = TargetType->getAs(); + if (!TargetObjCPtr) + return; + + if (TargetObjCPtr->isUnspecialized() || + TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() + != S.NSDictionaryDecl->getCanonicalDecl()) + return; + + auto TypeArgs = TargetObjCPtr->getTypeArgs(); + if (TypeArgs.size() != 2) + return; + + QualType TargetKeyType = TypeArgs[0]; + QualType TargetObjectType = TypeArgs[1]; + for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { + auto Element = DictionaryLiteral->getKeyValueElement(I); + checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); + checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); + } + } + + // Helper function to filter out cases for constant width constant conversion. + // Don't warn on char array initialization or for non-decimal values. + static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, + SourceLocation CC) { + // If initializing from a constant, and the constant starts with '0', + // then it is a binary, octal, or hexadecimal. Allow these constants + // to fill all the bits, even if there is a sign change. + if (auto *IntLit = dyn_cast(E->IgnoreParenImpCasts())) { + const char FirstLiteralCharacter = + S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; + if (FirstLiteralCharacter == '0') + return false; + } + + // If the CC location points to a '{', and the type is char, then assume + // assume it is an array initialization. + if (CC.isValid() && T->isCharType()) { + const char FirstContextCharacter = + S.getSourceManager().getCharacterData(CC)[0]; + if (FirstContextCharacter == '{') + return false; + } + + return true; + } + + static const IntegerLiteral *getIntegerLiteral(Expr *E) { + const auto *IL = dyn_cast(E); + if (!IL) { + if (auto *UO = dyn_cast(E)) { + if (UO->getOpcode() == UO_Minus) + return dyn_cast(UO->getSubExpr()); + } + } + + return IL; + } + + static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { + E = E->IgnoreParenImpCasts(); + SourceLocation ExprLoc = E->getExprLoc(); + + if (const auto *BO = dyn_cast(E)) { + BinaryOperator::Opcode Opc = BO->getOpcode(); + Expr::EvalResult Result; + // Do not diagnose unsigned shifts. + if (Opc == BO_Shl) { + const auto *LHS = getIntegerLiteral(BO->getLHS()); + const auto *RHS = getIntegerLiteral(BO->getRHS()); + if (LHS && LHS->getValue() == 0) + S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; + else if (!E->isValueDependent() && LHS && RHS && + RHS->getValue().isNonNegative() && + E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) + S.Diag(ExprLoc, diag::warn_left_shift_always) + << (Result.Val.getInt() != 0); + else if (E->getType()->isSignedIntegerType()) + S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; + } + } + + if (const auto *CO = dyn_cast(E)) { + const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); + const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); + if (!LHS || !RHS) + return; + if ((LHS->getValue() == 0 || LHS->getValue() == 1) && + (RHS->getValue() == 0 || RHS->getValue() == 1)) + // Do not diagnose common idioms. + return; + if (LHS->getValue() != 0 && RHS->getValue() != 0) + S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); + } + } + + static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, + SourceLocation CC, + bool *ICContext = nullptr, + bool IsListInit = false) { + if (E->isTypeDependent() || E->isValueDependent()) return; + + const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); + const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); + if (Source == Target) return; + if (Target->isDependentType()) return; + + // If the conversion context location is invalid don't complain. We also + // don't want to emit a warning if the issue occurs from the expansion of + // a system macro. The problem is that 'getSpellingLoc()' is slow, so we + // delay this check as long as possible. Once we detect we are in that + // scenario, we just return. + if (CC.isInvalid()) + return; + + if (Source->isAtomicType()) + S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); + + // Diagnose implicit casts to bool. + if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { + if (isa(E)) + // Warn on string literal to bool. Checks for string literals in logical + // and expressions, for instance, assert(0 && "error here"), are + // prevented by a check in AnalyzeImplicitConversions(). + return DiagnoseImpCast(S, E, T, CC, + diag::warn_impcast_string_literal_to_bool); + if (isa(E) || isa(E) || + isa(E) || isa(E)) { + // This covers the literal expressions that evaluate to Objective-C + // objects. + return DiagnoseImpCast(S, E, T, CC, + diag::warn_impcast_objective_c_literal_to_bool); + } + if (Source->isPointerType() || Source->canDecayToPointerType()) { + // Warn on pointer to bool conversion that is always true. + S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, + SourceRange(CC)); + } + } + + // If the we're converting a constant to an ObjC BOOL on a platform where BOOL + // is a typedef for signed char (macOS), then that constant value has to be 1 + // or 0. + if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { + Expr::EvalResult Result; + if (E->EvaluateAsInt(Result, S.getASTContext(), + Expr::SE_AllowSideEffects)) { + if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { + adornObjCBoolConversionDiagWithTernaryFixit( + S, E, + S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) + << toString(Result.Val.getInt(), 10)); + } + return; + } + } + + // Check implicit casts from Objective-C collection literals to specialized + // collection types, e.g., NSArray *. + if (auto *ArrayLiteral = dyn_cast(E)) + checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); + else if (auto *DictionaryLiteral = dyn_cast(E)) + checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); + + // Strip vector types. + if (isa(Source)) { + if (Target->isVLSTBuiltinType() && + (S.Context.areCompatibleSveTypes(QualType(Target, 0), + QualType(Source, 0)) || + S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), + QualType(Source, 0)))) + return; + + if (!isa(Target)) { + if (S.SourceMgr.isInSystemMacro(CC)) + return; + return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); + } + + // If the vector cast is cast between two vectors of the same size, it is + // a bitcast, not a conversion. + if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) + return; + + Source = cast(Source)->getElementType().getTypePtr(); + Target = cast(Target)->getElementType().getTypePtr(); + } + if (auto VecTy = dyn_cast(Target)) + Target = VecTy->getElementType().getTypePtr(); + + // Strip complex types. + if (isa(Source)) { + if (!isa(Target)) { + if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) + return; + + return DiagnoseImpCast(S, E, T, CC, + S.getLangOpts().CPlusPlus + ? diag::err_impcast_complex_scalar + : diag::warn_impcast_complex_scalar); + } + + Source = cast(Source)->getElementType().getTypePtr(); + Target = cast(Target)->getElementType().getTypePtr(); + } + + const BuiltinType *SourceBT = dyn_cast(Source); + const BuiltinType *TargetBT = dyn_cast(Target); + + // If the source is floating point... + if (SourceBT && SourceBT->isFloatingPoint()) { + // ...and the target is floating point... + if (TargetBT && TargetBT->isFloatingPoint()) { + // ...then warn if we're dropping FP rank. + + int Order = S.getASTContext().getFloatingTypeSemanticOrder( + QualType(SourceBT, 0), QualType(TargetBT, 0)); + if (Order > 0) { + // Don't warn about float constants that are precisely + // representable in the target type. + Expr::EvalResult result; + if (E->EvaluateAsRValue(result, S.Context)) { + // Value might be a float, a float vector, or a float complex. + if (IsSameFloatAfterCast(result.Val, + S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), + S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) + return; + } + + if (S.SourceMgr.isInSystemMacro(CC)) + return; + + DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); + } + // ... or possibly if we're increasing rank, too + else if (Order < 0) { + if (S.SourceMgr.isInSystemMacro(CC)) + return; + + DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); + } + return; + } + + // If the target is integral, always warn. + if (TargetBT && TargetBT->isInteger()) { + if (S.SourceMgr.isInSystemMacro(CC)) + return; + + DiagnoseFloatingImpCast(S, E, T, CC); + } + + // Detect the case where a call result is converted from floating-point to + // to bool, and the final argument to the call is converted from bool, to + // discover this typo: + // + // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" + // + // FIXME: This is an incredibly special case; is there some more general + // way to detect this class of misplaced-parentheses bug? + if (Target->isBooleanType() && isa(E)) { + // Check last argument of function call to see if it is an + // implicit cast from a type matching the type the result + // is being cast to. + CallExpr *CEx = cast(E); + if (unsigned NumArgs = CEx->getNumArgs()) { + Expr *LastA = CEx->getArg(NumArgs - 1); + Expr *InnerE = LastA->IgnoreParenImpCasts(); + if (isa(LastA) && + InnerE->getType()->isBooleanType()) { + // Warn on this floating-point to bool conversion + DiagnoseImpCast(S, E, T, CC, + diag::warn_impcast_floating_point_to_bool); + } + } + } + return; + } + + // Valid casts involving fixed point types should be accounted for here. + if (Source->isFixedPointType()) { + if (Target->isUnsaturatedFixedPointType()) { + Expr::EvalResult Result; + if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, + S.isConstantEvaluated())) { + llvm::APFixedPoint Value = Result.Val.getFixedPoint(); + llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); + llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); + if (Value > MaxVal || Value < MinVal) { + S.DiagRuntimeBehavior(E->getExprLoc(), E, + S.PDiag(diag::warn_impcast_fixed_point_range) + << Value.toString() << T + << E->getSourceRange() + << clang::SourceRange(CC)); + return; + } + } + } else if (Target->isIntegerType()) { + Expr::EvalResult Result; + if (!S.isConstantEvaluated() && + E->EvaluateAsFixedPoint(Result, S.Context, + Expr::SE_AllowSideEffects)) { + llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); + + bool Overflowed; + llvm::APSInt IntResult = FXResult.convertToInt( + S.Context.getIntWidth(T), + Target->isSignedIntegerOrEnumerationType(), &Overflowed); + + if (Overflowed) { + S.DiagRuntimeBehavior(E->getExprLoc(), E, + S.PDiag(diag::warn_impcast_fixed_point_range) + << FXResult.toString() << T + << E->getSourceRange() + << clang::SourceRange(CC)); + return; + } + } + } + } else if (Target->isUnsaturatedFixedPointType()) { + if (Source->isIntegerType()) { + Expr::EvalResult Result; + if (!S.isConstantEvaluated() && + E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { + llvm::APSInt Value = Result.Val.getInt(); + + bool Overflowed; + llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( + Value, S.Context.getFixedPointSemantics(T), &Overflowed); + + if (Overflowed) { + S.DiagRuntimeBehavior(E->getExprLoc(), E, + S.PDiag(diag::warn_impcast_fixed_point_range) + << toString(Value, /*Radix=*/10) << T + << E->getSourceRange() + << clang::SourceRange(CC)); + return; + } + } + } + } + + // If we are casting an integer type to a floating point type without + // initialization-list syntax, we might lose accuracy if the floating + // point type has a narrower significand than the integer type. + if (SourceBT && TargetBT && SourceBT->isIntegerType() && + TargetBT->isFloatingType() && !IsListInit) { + // Determine the number of precision bits in the source integer type. + IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), + /*Approximate*/ true); + unsigned int SourcePrecision = SourceRange.Width; + + // Determine the number of precision bits in the + // target floating point type. + unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( + S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); + + if (SourcePrecision > 0 && TargetPrecision > 0 && + SourcePrecision > TargetPrecision) { + + if (Optional SourceInt = + E->getIntegerConstantExpr(S.Context)) { + // If the source integer is a constant, convert it to the target + // floating point type. Issue a warning if the value changes + // during the whole conversion. + llvm::APFloat TargetFloatValue( + S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); + llvm::APFloat::opStatus ConversionStatus = + TargetFloatValue.convertFromAPInt( + *SourceInt, SourceBT->isSignedInteger(), + llvm::APFloat::rmNearestTiesToEven); + + if (ConversionStatus != llvm::APFloat::opOK) { + SmallString<32> PrettySourceValue; + SourceInt->toString(PrettySourceValue, 10); + SmallString<32> PrettyTargetValue; + TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); + + S.DiagRuntimeBehavior( + E->getExprLoc(), E, + S.PDiag(diag::warn_impcast_integer_float_precision_constant) + << PrettySourceValue << PrettyTargetValue << E->getType() << T + << E->getSourceRange() << clang::SourceRange(CC)); + } + } else { + // Otherwise, the implicit conversion may lose precision. + DiagnoseImpCast(S, E, T, CC, + diag::warn_impcast_integer_float_precision); + } + } + } + + DiagnoseNullConversion(S, E, T, CC); + + S.DiscardMisalignedMemberAddress(Target, E); + + if (Target->isBooleanType()) + DiagnoseIntInBoolContext(S, E); + + if (!Source->isIntegerType() || !Target->isIntegerType()) + return; + + // TODO: remove this early return once the false positives for constant->bool + // in templates, macros, etc, are reduced or removed. + if (Target->isSpecificBuiltinType(BuiltinType::Bool)) + return; + + if (isObjCSignedCharBool(S, T) && !Source->isCharType() && + !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { + return adornObjCBoolConversionDiagWithTernaryFixit( + S, E, + S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) + << E->getType()); + } + + IntRange SourceTypeRange = + IntRange::forTargetOfCanonicalType(S.Context, Source); + IntRange LikelySourceRange = + GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); + IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); + + if (LikelySourceRange.Width > TargetRange.Width) { + // If the source is a constant, use a default-on diagnostic. + // TODO: this should happen for bitfield stores, too. + Expr::EvalResult Result; + if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, + S.isConstantEvaluated())) { + llvm::APSInt Value(32); + Value = Result.Val.getInt(); + + if (S.SourceMgr.isInSystemMacro(CC)) + return; + + std::string PrettySourceValue = toString(Value, 10); + std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); + + S.DiagRuntimeBehavior( + E->getExprLoc(), E, + S.PDiag(diag::warn_impcast_integer_precision_constant) + << PrettySourceValue << PrettyTargetValue << E->getType() << T + << E->getSourceRange() << SourceRange(CC)); + return; + } + + // People want to build with -Wshorten-64-to-32 and not -Wconversion. + if (S.SourceMgr.isInSystemMacro(CC)) + return; + + if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) + return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, + /* pruneControlFlow */ true); + return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); + } + + if (TargetRange.Width > SourceTypeRange.Width) { + if (auto *UO = dyn_cast(E)) + if (UO->getOpcode() == UO_Minus) + if (Source->isUnsignedIntegerType()) { + if (Target->isUnsignedIntegerType()) + return DiagnoseImpCast(S, E, T, CC, + diag::warn_impcast_high_order_zero_bits); + if (Target->isSignedIntegerType()) + return DiagnoseImpCast(S, E, T, CC, + diag::warn_impcast_nonnegative_result); + } + } + + if (TargetRange.Width == LikelySourceRange.Width && + !TargetRange.NonNegative && LikelySourceRange.NonNegative && + Source->isSignedIntegerType()) { + // Warn when doing a signed to signed conversion, warn if the positive + // source value is exactly the width of the target type, which will + // cause a negative value to be stored. + + Expr::EvalResult Result; + if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && + !S.SourceMgr.isInSystemMacro(CC)) { + llvm::APSInt Value = Result.Val.getInt(); + if (isSameWidthConstantConversion(S, E, T, CC)) { + std::string PrettySourceValue = toString(Value, 10); + std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); + + S.DiagRuntimeBehavior( + E->getExprLoc(), E, + S.PDiag(diag::warn_impcast_integer_precision_constant) + << PrettySourceValue << PrettyTargetValue << E->getType() << T + << E->getSourceRange() << SourceRange(CC)); + return; + } + } + + // Fall through for non-constants to give a sign conversion warning. + } + + if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || + (!TargetRange.NonNegative && LikelySourceRange.NonNegative && + LikelySourceRange.Width == TargetRange.Width)) { + if (S.SourceMgr.isInSystemMacro(CC)) + return; + + unsigned DiagID = diag::warn_impcast_integer_sign; + + // Traditionally, gcc has warned about this under -Wsign-compare. + // We also want to warn about it in -Wconversion. + // So if -Wconversion is off, use a completely identical diagnostic + // in the sign-compare group. + // The conditional-checking code will + if (ICContext) { + DiagID = diag::warn_impcast_integer_sign_conditional; + *ICContext = true; + } + + return DiagnoseImpCast(S, E, T, CC, DiagID); + } + + // Diagnose conversions between different enumeration types. + // In C, we pretend that the type of an EnumConstantDecl is its enumeration + // type, to give us better diagnostics. + QualType SourceType = E->getType(); + if (!S.getLangOpts().CPlusPlus) { + if (DeclRefExpr *DRE = dyn_cast(E)) + if (EnumConstantDecl *ECD = dyn_cast(DRE->getDecl())) { + EnumDecl *Enum = cast(ECD->getDeclContext()); + SourceType = S.Context.getTypeDeclType(Enum); + Source = S.Context.getCanonicalType(SourceType).getTypePtr(); + } + } + + if (const EnumType *SourceEnum = Source->getAs()) + if (const EnumType *TargetEnum = Target->getAs()) + if (SourceEnum->getDecl()->hasNameForLinkage() && + TargetEnum->getDecl()->hasNameForLinkage() && + SourceEnum != TargetEnum) { + if (S.SourceMgr.isInSystemMacro(CC)) + return; + + return DiagnoseImpCast(S, E, SourceType, T, CC, + diag::warn_impcast_different_enum_types); + } + } + + static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, + SourceLocation CC, QualType T); + + static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, + SourceLocation CC, bool &ICContext) { + E = E->IgnoreParenImpCasts(); + + if (auto *CO = dyn_cast(E)) + return CheckConditionalOperator(S, CO, CC, T); + + AnalyzeImplicitConversions(S, E, CC); + if (E->getType() != T) + return CheckImplicitConversion(S, E, T, CC, &ICContext); + } + + static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, + SourceLocation CC, QualType T) { + AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); + + Expr *TrueExpr = E->getTrueExpr(); + if (auto *BCO = dyn_cast(E)) + TrueExpr = BCO->getCommon(); + + bool Suspicious = false; + CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); + CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); + + if (T->isBooleanType()) + DiagnoseIntInBoolContext(S, E); + + // If -Wconversion would have warned about either of the candidates + // for a signedness conversion to the context type... + if (!Suspicious) return; + + // ...but it's currently ignored... + if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) + return; + + // ...then check whether it would have warned about either of the + // candidates for a signedness conversion to the condition type. + if (E->getType() == T) return; + + Suspicious = false; + CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), + E->getType(), CC, &Suspicious); + if (!Suspicious) + CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), + E->getType(), CC, &Suspicious); + } + + /// Check conversion of given expression to boolean. + /// Input argument E is a logical expression. + static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { + if (S.getLangOpts().Bool) + return; + if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) + return; + CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); + } + + namespace { + struct AnalyzeImplicitConversionsWorkItem { + Expr *E; + SourceLocation CC; + bool IsListInit; + }; + } + + /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions + /// that should be visited are added to WorkList. + static void AnalyzeImplicitConversions( + Sema &S, AnalyzeImplicitConversionsWorkItem Item, + llvm::SmallVectorImpl &WorkList) { + Expr *OrigE = Item.E; + SourceLocation CC = Item.CC; + + QualType T = OrigE->getType(); + Expr *E = OrigE->IgnoreParenImpCasts(); + + // Propagate whether we are in a C++ list initialization expression. + // If so, we do not issue warnings for implicit int-float conversion + // precision loss, because C++11 narrowing already handles it. + bool IsListInit = Item.IsListInit || + (isa(OrigE) && S.getLangOpts().CPlusPlus); + + if (E->isTypeDependent() || E->isValueDependent()) + return; + + Expr *SourceExpr = E; + // Examine, but don't traverse into the source expression of an + // OpaqueValueExpr, since it may have multiple parents and we don't want to + // emit duplicate diagnostics. Its fine to examine the form or attempt to + // evaluate it in the context of checking the specific conversion to T though. + if (auto *OVE = dyn_cast(E)) + if (auto *Src = OVE->getSourceExpr()) + SourceExpr = Src; + + if (const auto *UO = dyn_cast(SourceExpr)) + if (UO->getOpcode() == UO_Not && + UO->getSubExpr()->isKnownToHaveBooleanValue()) + S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) + << OrigE->getSourceRange() << T->isBooleanType() + << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); + ++ if (const auto *BO = dyn_cast(SourceExpr)) ++ if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && ++ BO->getLHS()->isKnownToHaveBooleanValue() && ++ BO->getRHS()->isKnownToHaveBooleanValue() && ++ BO->getLHS()->HasSideEffects(S.Context) && ++ BO->getRHS()->HasSideEffects(S.Context)) ++ S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) ++ << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange() ++ << FixItHint::CreateReplacement( ++ BO->getOperatorLoc(), ++ (BO->getOpcode() == BO_And ? "&&" : "||")); ++ + // For conditional operators, we analyze the arguments as if they + // were being fed directly into the output. + if (auto *CO = dyn_cast(SourceExpr)) { + CheckConditionalOperator(S, CO, CC, T); + return; + } + + // Check implicit argument conversions for function calls. + if (CallExpr *Call = dyn_cast(SourceExpr)) + CheckImplicitArgumentConversions(S, Call, CC); + + // Go ahead and check any implicit conversions we might have skipped. + // The non-canonical typecheck is just an optimization; + // CheckImplicitConversion will filter out dead implicit conversions. + if (SourceExpr->getType() != T) + CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); + + // Now continue drilling into this expression. + + if (PseudoObjectExpr *POE = dyn_cast(E)) { + // The bound subexpressions in a PseudoObjectExpr are not reachable + // as transitive children. + // FIXME: Use a more uniform representation for this. + for (auto *SE : POE->semantics()) + if (auto *OVE = dyn_cast(SE)) + WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); + } + + // Skip past explicit casts. + if (auto *CE = dyn_cast(E)) { + E = CE->getSubExpr()->IgnoreParenImpCasts(); + if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) + S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); + WorkList.push_back({E, CC, IsListInit}); + return; + } + + if (BinaryOperator *BO = dyn_cast(E)) { + // Do a somewhat different check with comparison operators. + if (BO->isComparisonOp()) + return AnalyzeComparison(S, BO); + + // And with simple assignments. + if (BO->getOpcode() == BO_Assign) + return AnalyzeAssignment(S, BO); + // And with compound assignments. + if (BO->isAssignmentOp()) + return AnalyzeCompoundAssignment(S, BO); + } + + // These break the otherwise-useful invariant below. Fortunately, + // we don't really need to recurse into them, because any internal + // expressions should have been analyzed already when they were + // built into statements. + if (isa(E)) return; + + // Don't descend into unevaluated contexts. + if (isa(E)) return; + + // Now just recurse over the expression's children. + CC = E->getExprLoc(); + BinaryOperator *BO = dyn_cast(E); + bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; + for (Stmt *SubStmt : E->children()) { + Expr *ChildExpr = dyn_cast_or_null(SubStmt); + if (!ChildExpr) + continue; + + if (IsLogicalAndOperator && + isa(ChildExpr->IgnoreParenImpCasts())) + // Ignore checking string literals that are in logical and operators. + // This is a common pattern for asserts. + continue; + WorkList.push_back({ChildExpr, CC, IsListInit}); + } + + if (BO && BO->isLogicalOp()) { + Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); + if (!IsLogicalAndOperator || !isa(SubExpr)) + ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); + + SubExpr = BO->getRHS()->IgnoreParenImpCasts(); + if (!IsLogicalAndOperator || !isa(SubExpr)) + ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); + } + + if (const UnaryOperator *U = dyn_cast(E)) { + if (U->getOpcode() == UO_LNot) { + ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); + } else if (U->getOpcode() != UO_AddrOf) { + if (U->getSubExpr()->getType()->isAtomicType()) + S.Diag(U->getSubExpr()->getBeginLoc(), + diag::warn_atomic_implicit_seq_cst); + } + } + } + + /// AnalyzeImplicitConversions - Find and report any interesting + /// implicit conversions in the given expression. There are a couple + /// of competing diagnostics here, -Wconversion and -Wsign-compare. + static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, + bool IsListInit/*= false*/) { + llvm::SmallVector WorkList; + WorkList.push_back({OrigE, CC, IsListInit}); + while (!WorkList.empty()) + AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); + } + + /// Diagnose integer type and any valid implicit conversion to it. + static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { + // Taking into account implicit conversions, + // allow any integer. + if (!E->getType()->isIntegerType()) { + S.Diag(E->getBeginLoc(), + diag::err_opencl_enqueue_kernel_invalid_local_size_type); + return true; + } + // Potentially emit standard warnings for implicit conversions if enabled + // using -Wconversion. + CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); + return false; + } + + // Helper function for Sema::DiagnoseAlwaysNonNullPointer. + // Returns true when emitting a warning about taking the address of a reference. + static bool CheckForReference(Sema &SemaRef, const Expr *E, + const PartialDiagnostic &PD) { + E = E->IgnoreParenImpCasts(); + + const FunctionDecl *FD = nullptr; + + if (const DeclRefExpr *DRE = dyn_cast(E)) { + if (!DRE->getDecl()->getType()->isReferenceType()) + return false; + } else if (const MemberExpr *M = dyn_cast(E)) { + if (!M->getMemberDecl()->getType()->isReferenceType()) + return false; + } else if (const CallExpr *Call = dyn_cast(E)) { + if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) + return false; + FD = Call->getDirectCallee(); + } else { + return false; + } + + SemaRef.Diag(E->getExprLoc(), PD); + + // If possible, point to location of function. + if (FD) { + SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; + } + + return true; + } + + // Returns true if the SourceLocation is expanded from any macro body. + // Returns false if the SourceLocation is invalid, is from not in a macro + // expansion, or is from expanded from a top-level macro argument. + static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { + if (Loc.isInvalid()) + return false; + + while (Loc.isMacroID()) { + if (SM.isMacroBodyExpansion(Loc)) + return true; + Loc = SM.getImmediateMacroCallerLoc(Loc); + } + + return false; + } + + /// Diagnose pointers that are always non-null. + /// \param E the expression containing the pointer + /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is + /// compared to a null pointer + /// \param IsEqual True when the comparison is equal to a null pointer + /// \param Range Extra SourceRange to highlight in the diagnostic + void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, + Expr::NullPointerConstantKind NullKind, + bool IsEqual, SourceRange Range) { + if (!E) + return; + + // Don't warn inside macros. + if (E->getExprLoc().isMacroID()) { + const SourceManager &SM = getSourceManager(); + if (IsInAnyMacroBody(SM, E->getExprLoc()) || + IsInAnyMacroBody(SM, Range.getBegin())) + return; + } + E = E->IgnoreImpCasts(); + + const bool IsCompare = NullKind != Expr::NPCK_NotNull; + + if (isa(E)) { + unsigned DiagID = IsCompare ? diag::warn_this_null_compare + : diag::warn_this_bool_conversion; + Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; + return; + } + + bool IsAddressOf = false; + + if (UnaryOperator *UO = dyn_cast(E)) { + if (UO->getOpcode() != UO_AddrOf) + return; + IsAddressOf = true; + E = UO->getSubExpr(); + } + + if (IsAddressOf) { + unsigned DiagID = IsCompare + ? diag::warn_address_of_reference_null_compare + : diag::warn_address_of_reference_bool_conversion; + PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range + << IsEqual; + if (CheckForReference(*this, E, PD)) { + return; + } + } + + auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { + bool IsParam = isa(NonnullAttr); + std::string Str; + llvm::raw_string_ostream S(Str); + E->printPretty(S, nullptr, getPrintingPolicy()); + unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare + : diag::warn_cast_nonnull_to_bool; + Diag(E->getExprLoc(), DiagID) << IsParam << S.str() + << E->getSourceRange() << Range << IsEqual; + Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; + }; + + // If we have a CallExpr that is tagged with returns_nonnull, we can complain. + if (auto *Call = dyn_cast(E->IgnoreParenImpCasts())) { + if (auto *Callee = Call->getDirectCallee()) { + if (const Attr *A = Callee->getAttr()) { + ComplainAboutNonnullParamOrCall(A); + return; + } + } + } + + // Expect to find a single Decl. Skip anything more complicated. + ValueDecl *D = nullptr; + if (DeclRefExpr *R = dyn_cast(E)) { + D = R->getDecl(); + } else if (MemberExpr *M = dyn_cast(E)) { + D = M->getMemberDecl(); + } + + // Weak Decls can be null. + if (!D || D->isWeak()) + return; + + // Check for parameter decl with nonnull attribute + if (const auto* PV = dyn_cast(D)) { + if (getCurFunction() && + !getCurFunction()->ModifiedNonNullParams.count(PV)) { + if (const Attr *A = PV->getAttr()) { + ComplainAboutNonnullParamOrCall(A); + return; + } + + if (const auto *FD = dyn_cast(PV->getDeclContext())) { + // Skip function template not specialized yet. + if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) + return; + auto ParamIter = llvm::find(FD->parameters(), PV); + assert(ParamIter != FD->param_end()); + unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); + + for (const auto *NonNull : FD->specific_attrs()) { + if (!NonNull->args_size()) { + ComplainAboutNonnullParamOrCall(NonNull); + return; + } + + for (const ParamIdx &ArgNo : NonNull->args()) { + if (ArgNo.getASTIndex() == ParamNo) { + ComplainAboutNonnullParamOrCall(NonNull); + return; + } + } + } + } + } + } + + QualType T = D->getType(); + const bool IsArray = T->isArrayType(); + const bool IsFunction = T->isFunctionType(); + + // Address of function is used to silence the function warning. + if (IsAddressOf && IsFunction) { + return; + } + + // Found nothing. + if (!IsAddressOf && !IsFunction && !IsArray) + return; + + // Pretty print the expression for the diagnostic. + std::string Str; + llvm::raw_string_ostream S(Str); + E->printPretty(S, nullptr, getPrintingPolicy()); + + unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare + : diag::warn_impcast_pointer_to_bool; + enum { + AddressOf, + FunctionPointer, + ArrayPointer + } DiagType; + if (IsAddressOf) + DiagType = AddressOf; + else if (IsFunction) + DiagType = FunctionPointer; + else if (IsArray) + DiagType = ArrayPointer; + else + llvm_unreachable("Could not determine diagnostic."); + Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() + << Range << IsEqual; + + if (!IsFunction) + return; + + // Suggest '&' to silence the function warning. + Diag(E->getExprLoc(), diag::note_function_warning_silence) + << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); + + // Check to see if '()' fixit should be emitted. + QualType ReturnType; + UnresolvedSet<4> NonTemplateOverloads; + tryExprAsCall(*E, ReturnType, NonTemplateOverloads); + if (ReturnType.isNull()) + return; + + if (IsCompare) { + // There are two cases here. If there is null constant, the only suggest + // for a pointer return type. If the null is 0, then suggest if the return + // type is a pointer or an integer type. + if (!ReturnType->isPointerType()) { + if (NullKind == Expr::NPCK_ZeroExpression || + NullKind == Expr::NPCK_ZeroLiteral) { + if (!ReturnType->isIntegerType()) + return; + } else { + return; + } + } + } else { // !IsCompare + // For function to bool, only suggest if the function pointer has bool + // return type. + if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) + return; + } + Diag(E->getExprLoc(), diag::note_function_to_function_call) + << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); + } + + /// Diagnoses "dangerous" implicit conversions within the given + /// expression (which is a full expression). Implements -Wconversion + /// and -Wsign-compare. + /// + /// \param CC the "context" location of the implicit conversion, i.e. + /// the most location of the syntactic entity requiring the implicit + /// conversion + void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { + // Don't diagnose in unevaluated contexts. + if (isUnevaluatedContext()) + return; + + // Don't diagnose for value- or type-dependent expressions. + if (E->isTypeDependent() || E->isValueDependent()) + return; + + // Check for array bounds violations in cases where the check isn't triggered + // elsewhere for other Expr types (like BinaryOperators), e.g. when an + // ArraySubscriptExpr is on the RHS of a variable initialization. + CheckArrayAccess(E); + + // This is not the right CC for (e.g.) a variable initialization. + AnalyzeImplicitConversions(*this, E, CC); + } + + /// CheckBoolLikeConversion - Check conversion of given expression to boolean. + /// Input argument E is a logical expression. + void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { + ::CheckBoolLikeConversion(*this, E, CC); + } + + /// Diagnose when expression is an integer constant expression and its evaluation + /// results in integer overflow + void Sema::CheckForIntOverflow (Expr *E) { + // Use a work list to deal with nested struct initializers. + SmallVector Exprs(1, E); + + do { + Expr *OriginalE = Exprs.pop_back_val(); + Expr *E = OriginalE->IgnoreParenCasts(); + + if (isa(E)) { + E->EvaluateForOverflow(Context); + continue; + } + + if (auto InitList = dyn_cast(OriginalE)) + Exprs.append(InitList->inits().begin(), InitList->inits().end()); + else if (isa(OriginalE)) + E->EvaluateForOverflow(Context); + else if (auto Call = dyn_cast(E)) + Exprs.append(Call->arg_begin(), Call->arg_end()); + else if (auto Message = dyn_cast(E)) + Exprs.append(Message->arg_begin(), Message->arg_end()); + } while (!Exprs.empty()); + } + + namespace { + + /// Visitor for expressions which looks for unsequenced operations on the + /// same object. + class SequenceChecker : public ConstEvaluatedExprVisitor { + using Base = ConstEvaluatedExprVisitor; + + /// A tree of sequenced regions within an expression. Two regions are + /// unsequenced if one is an ancestor or a descendent of the other. When we + /// finish processing an expression with sequencing, such as a comma + /// expression, we fold its tree nodes into its parent, since they are + /// unsequenced with respect to nodes we will visit later. + class SequenceTree { + struct Value { + explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} + unsigned Parent : 31; + unsigned Merged : 1; + }; + SmallVector Values; + + public: + /// A region within an expression which may be sequenced with respect + /// to some other region. + class Seq { + friend class SequenceTree; + + unsigned Index; + + explicit Seq(unsigned N) : Index(N) {} + + public: + Seq() : Index(0) {} + }; + + SequenceTree() { Values.push_back(Value(0)); } + Seq root() const { return Seq(0); } + + /// Create a new sequence of operations, which is an unsequenced + /// subset of \p Parent. This sequence of operations is sequenced with + /// respect to other children of \p Parent. + Seq allocate(Seq Parent) { + Values.push_back(Value(Parent.Index)); + return Seq(Values.size() - 1); + } + + /// Merge a sequence of operations into its parent. + void merge(Seq S) { + Values[S.Index].Merged = true; + } + + /// Determine whether two operations are unsequenced. This operation + /// is asymmetric: \p Cur should be the more recent sequence, and \p Old + /// should have been merged into its parent as appropriate. + bool isUnsequenced(Seq Cur, Seq Old) { + unsigned C = representative(Cur.Index); + unsigned Target = representative(Old.Index); + while (C >= Target) { + if (C == Target) + return true; + C = Values[C].Parent; + } + return false; + } + + private: + /// Pick a representative for a sequence. + unsigned representative(unsigned K) { + if (Values[K].Merged) + // Perform path compression as we go. + return Values[K].Parent = representative(Values[K].Parent); + return K; + } + }; + + /// An object for which we can track unsequenced uses. + using Object = const NamedDecl *; + + /// Different flavors of object usage which we track. We only track the + /// least-sequenced usage of each kind. + enum UsageKind { + /// A read of an object. Multiple unsequenced reads are OK. + UK_Use, + + /// A modification of an object which is sequenced before the value + /// computation of the expression, such as ++n in C++. + UK_ModAsValue, + + /// A modification of an object which is not sequenced before the value + /// computation of the expression, such as n++. + UK_ModAsSideEffect, + + UK_Count = UK_ModAsSideEffect + 1 + }; + + /// Bundle together a sequencing region and the expression corresponding + /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. + struct Usage { + const Expr *UsageExpr; + SequenceTree::Seq Seq; + + Usage() : UsageExpr(nullptr), Seq() {} + }; + + struct UsageInfo { + Usage Uses[UK_Count]; + + /// Have we issued a diagnostic for this object already? + bool Diagnosed; + + UsageInfo() : Uses(), Diagnosed(false) {} + }; + using UsageInfoMap = llvm::SmallDenseMap; + + Sema &SemaRef; + + /// Sequenced regions within the expression. + SequenceTree Tree; + + /// Declaration modifications and references which we have seen. + UsageInfoMap UsageMap; + + /// The region we are currently within. + SequenceTree::Seq Region; + + /// Filled in with declarations which were modified as a side-effect + /// (that is, post-increment operations). + SmallVectorImpl> *ModAsSideEffect = nullptr; + + /// Expressions to check later. We defer checking these to reduce + /// stack usage. + SmallVectorImpl &WorkList; + + /// RAII object wrapping the visitation of a sequenced subexpression of an + /// expression. At the end of this process, the side-effects of the evaluation + /// become sequenced with respect to the value computation of the result, so + /// we downgrade any UK_ModAsSideEffect within the evaluation to + /// UK_ModAsValue. + struct SequencedSubexpression { + SequencedSubexpression(SequenceChecker &Self) + : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { + Self.ModAsSideEffect = &ModAsSideEffect; + } + + ~SequencedSubexpression() { + for (const std::pair &M : llvm::reverse(ModAsSideEffect)) { + // Add a new usage with usage kind UK_ModAsValue, and then restore + // the previous usage with UK_ModAsSideEffect (thus clearing it if + // the previous one was empty). + UsageInfo &UI = Self.UsageMap[M.first]; + auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; + Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); + SideEffectUsage = M.second; + } + Self.ModAsSideEffect = OldModAsSideEffect; + } + + SequenceChecker &Self; + SmallVector, 4> ModAsSideEffect; + SmallVectorImpl> *OldModAsSideEffect; + }; + + /// RAII object wrapping the visitation of a subexpression which we might + /// choose to evaluate as a constant. If any subexpression is evaluated and + /// found to be non-constant, this allows us to suppress the evaluation of + /// the outer expression. + class EvaluationTracker { + public: + EvaluationTracker(SequenceChecker &Self) + : Self(Self), Prev(Self.EvalTracker) { + Self.EvalTracker = this; + } + + ~EvaluationTracker() { + Self.EvalTracker = Prev; + if (Prev) + Prev->EvalOK &= EvalOK; + } + + bool evaluate(const Expr *E, bool &Result) { + if (!EvalOK || E->isValueDependent()) + return false; + EvalOK = E->EvaluateAsBooleanCondition( + Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); + return EvalOK; + } + + private: + SequenceChecker &Self; + EvaluationTracker *Prev; + bool EvalOK = true; + } *EvalTracker = nullptr; + + /// Find the object which is produced by the specified expression, + /// if any. + Object getObject(const Expr *E, bool Mod) const { + E = E->IgnoreParenCasts(); + if (const UnaryOperator *UO = dyn_cast(E)) { + if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) + return getObject(UO->getSubExpr(), Mod); + } else if (const BinaryOperator *BO = dyn_cast(E)) { + if (BO->getOpcode() == BO_Comma) + return getObject(BO->getRHS(), Mod); + if (Mod && BO->isAssignmentOp()) + return getObject(BO->getLHS(), Mod); + } else if (const MemberExpr *ME = dyn_cast(E)) { + // FIXME: Check for more interesting cases, like "x.n = ++x.n". + if (isa(ME->getBase()->IgnoreParenCasts())) + return ME->getMemberDecl(); + } else if (const DeclRefExpr *DRE = dyn_cast(E)) + // FIXME: If this is a reference, map through to its value. + return DRE->getDecl(); + return nullptr; + } + + /// Note that an object \p O was modified or used by an expression + /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for + /// the object \p O as obtained via the \p UsageMap. + void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { + // Get the old usage for the given object and usage kind. + Usage &U = UI.Uses[UK]; + if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { + // If we have a modification as side effect and are in a sequenced + // subexpression, save the old Usage so that we can restore it later + // in SequencedSubexpression::~SequencedSubexpression. + if (UK == UK_ModAsSideEffect && ModAsSideEffect) + ModAsSideEffect->push_back(std::make_pair(O, U)); + // Then record the new usage with the current sequencing region. + U.UsageExpr = UsageExpr; + U.Seq = Region; + } + } + + /// Check whether a modification or use of an object \p O in an expression + /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is + /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. + /// \p IsModMod is true when we are checking for a mod-mod unsequenced + /// usage and false we are checking for a mod-use unsequenced usage. + void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, + UsageKind OtherKind, bool IsModMod) { + if (UI.Diagnosed) + return; + + const Usage &U = UI.Uses[OtherKind]; + if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) + return; + + const Expr *Mod = U.UsageExpr; + const Expr *ModOrUse = UsageExpr; + if (OtherKind == UK_Use) + std::swap(Mod, ModOrUse); + + SemaRef.DiagRuntimeBehavior( + Mod->getExprLoc(), {Mod, ModOrUse}, + SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod + : diag::warn_unsequenced_mod_use) + << O << SourceRange(ModOrUse->getExprLoc())); + UI.Diagnosed = true; + } + + // A note on note{Pre, Post}{Use, Mod}: + // + // (It helps to follow the algorithm with an expression such as + // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced + // operations before C++17 and both are well-defined in C++17). + // + // When visiting a node which uses/modify an object we first call notePreUse + // or notePreMod before visiting its sub-expression(s). At this point the + // children of the current node have not yet been visited and so the eventual + // uses/modifications resulting from the children of the current node have not + // been recorded yet. + // + // We then visit the children of the current node. After that notePostUse or + // notePostMod is called. These will 1) detect an unsequenced modification + // as side effect (as in "k++ + k") and 2) add a new usage with the + // appropriate usage kind. + // + // We also have to be careful that some operation sequences modification as + // side effect as well (for example: || or ,). To account for this we wrap + // the visitation of such a sub-expression (for example: the LHS of || or ,) + // with SequencedSubexpression. SequencedSubexpression is an RAII object + // which record usages which are modifications as side effect, and then + // downgrade them (or more accurately restore the previous usage which was a + // modification as side effect) when exiting the scope of the sequenced + // subexpression. + + void notePreUse(Object O, const Expr *UseExpr) { + UsageInfo &UI = UsageMap[O]; + // Uses conflict with other modifications. + checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); + } + + void notePostUse(Object O, const Expr *UseExpr) { + UsageInfo &UI = UsageMap[O]; + checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, + /*IsModMod=*/false); + addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); + } + + void notePreMod(Object O, const Expr *ModExpr) { + UsageInfo &UI = UsageMap[O]; + // Modifications conflict with other modifications and with uses. + checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); + checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); + } + + void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { + UsageInfo &UI = UsageMap[O]; + checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, + /*IsModMod=*/true); + addUsage(O, UI, ModExpr, /*UsageKind=*/UK); + } + + public: + SequenceChecker(Sema &S, const Expr *E, + SmallVectorImpl &WorkList) + : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { + Visit(E); + // Silence a -Wunused-private-field since WorkList is now unused. + // TODO: Evaluate if it can be used, and if not remove it. + (void)this->WorkList; + } + + void VisitStmt(const Stmt *S) { + // Skip all statements which aren't expressions for now. + } + + void VisitExpr(const Expr *E) { + // By default, just recurse to evaluated subexpressions. + Base::VisitStmt(E); + } + + void VisitCastExpr(const CastExpr *E) { + Object O = Object(); + if (E->getCastKind() == CK_LValueToRValue) + O = getObject(E->getSubExpr(), false); + + if (O) + notePreUse(O, E); + VisitExpr(E); + if (O) + notePostUse(O, E); + } + + void VisitSequencedExpressions(const Expr *SequencedBefore, + const Expr *SequencedAfter) { + SequenceTree::Seq BeforeRegion = Tree.allocate(Region); + SequenceTree::Seq AfterRegion = Tree.allocate(Region); + SequenceTree::Seq OldRegion = Region; + + { + SequencedSubexpression SeqBefore(*this); + Region = BeforeRegion; + Visit(SequencedBefore); + } + + Region = AfterRegion; + Visit(SequencedAfter); + + Region = OldRegion; + + Tree.merge(BeforeRegion); + Tree.merge(AfterRegion); + } + + void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { + // C++17 [expr.sub]p1: + // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The + // expression E1 is sequenced before the expression E2. + if (SemaRef.getLangOpts().CPlusPlus17) + VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); + else { + Visit(ASE->getLHS()); + Visit(ASE->getRHS()); + } + } + + void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } + void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } + void VisitBinPtrMem(const BinaryOperator *BO) { + // C++17 [expr.mptr.oper]p4: + // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] + // the expression E1 is sequenced before the expression E2. + if (SemaRef.getLangOpts().CPlusPlus17) + VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); + else { + Visit(BO->getLHS()); + Visit(BO->getRHS()); + } + } + + void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } + void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } + void VisitBinShlShr(const BinaryOperator *BO) { + // C++17 [expr.shift]p4: + // The expression E1 is sequenced before the expression E2. + if (SemaRef.getLangOpts().CPlusPlus17) + VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); + else { + Visit(BO->getLHS()); + Visit(BO->getRHS()); + } + } + + void VisitBinComma(const BinaryOperator *BO) { + // C++11 [expr.comma]p1: + // Every value computation and side effect associated with the left + // expression is sequenced before every value computation and side + // effect associated with the right expression. + VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); + } + + void VisitBinAssign(const BinaryOperator *BO) { + SequenceTree::Seq RHSRegion; + SequenceTree::Seq LHSRegion; + if (SemaRef.getLangOpts().CPlusPlus17) { + RHSRegion = Tree.allocate(Region); + LHSRegion = Tree.allocate(Region); + } else { + RHSRegion = Region; + LHSRegion = Region; + } + SequenceTree::Seq OldRegion = Region; + + // C++11 [expr.ass]p1: + // [...] the assignment is sequenced after the value computation + // of the right and left operands, [...] + // + // so check it before inspecting the operands and update the + // map afterwards. + Object O = getObject(BO->getLHS(), /*Mod=*/true); + if (O) + notePreMod(O, BO); + + if (SemaRef.getLangOpts().CPlusPlus17) { + // C++17 [expr.ass]p1: + // [...] The right operand is sequenced before the left operand. [...] + { + SequencedSubexpression SeqBefore(*this); + Region = RHSRegion; + Visit(BO->getRHS()); + } + + Region = LHSRegion; + Visit(BO->getLHS()); + + if (O && isa(BO)) + notePostUse(O, BO); + + } else { + // C++11 does not specify any sequencing between the LHS and RHS. + Region = LHSRegion; + Visit(BO->getLHS()); + + if (O && isa(BO)) + notePostUse(O, BO); + + Region = RHSRegion; + Visit(BO->getRHS()); + } + + // C++11 [expr.ass]p1: + // the assignment is sequenced [...] before the value computation of the + // assignment expression. + // C11 6.5.16/3 has no such rule. + Region = OldRegion; + if (O) + notePostMod(O, BO, + SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue + : UK_ModAsSideEffect); + if (SemaRef.getLangOpts().CPlusPlus17) { + Tree.merge(RHSRegion); + Tree.merge(LHSRegion); + } + } + + void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { + VisitBinAssign(CAO); + } + + void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } + void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } + void VisitUnaryPreIncDec(const UnaryOperator *UO) { + Object O = getObject(UO->getSubExpr(), true); + if (!O) + return VisitExpr(UO); + + notePreMod(O, UO); + Visit(UO->getSubExpr()); + // C++11 [expr.pre.incr]p1: + // the expression ++x is equivalent to x+=1 + notePostMod(O, UO, + SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue + : UK_ModAsSideEffect); + } + + void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } + void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } + void VisitUnaryPostIncDec(const UnaryOperator *UO) { + Object O = getObject(UO->getSubExpr(), true); + if (!O) + return VisitExpr(UO); + + notePreMod(O, UO); + Visit(UO->getSubExpr()); + notePostMod(O, UO, UK_ModAsSideEffect); + } + + void VisitBinLOr(const BinaryOperator *BO) { + // C++11 [expr.log.or]p2: + // If the second expression is evaluated, every value computation and + // side effect associated with the first expression is sequenced before + // every value computation and side effect associated with the + // second expression. + SequenceTree::Seq LHSRegion = Tree.allocate(Region); + SequenceTree::Seq RHSRegion = Tree.allocate(Region); + SequenceTree::Seq OldRegion = Region; + + EvaluationTracker Eval(*this); + { + SequencedSubexpression Sequenced(*this); + Region = LHSRegion; + Visit(BO->getLHS()); + } + + // C++11 [expr.log.or]p1: + // [...] the second operand is not evaluated if the first operand + // evaluates to true. + bool EvalResult = false; + bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); + bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); + if (ShouldVisitRHS) { + Region = RHSRegion; + Visit(BO->getRHS()); + } + + Region = OldRegion; + Tree.merge(LHSRegion); + Tree.merge(RHSRegion); + } + + void VisitBinLAnd(const BinaryOperator *BO) { + // C++11 [expr.log.and]p2: + // If the second expression is evaluated, every value computation and + // side effect associated with the first expression is sequenced before + // every value computation and side effect associated with the + // second expression. + SequenceTree::Seq LHSRegion = Tree.allocate(Region); + SequenceTree::Seq RHSRegion = Tree.allocate(Region); + SequenceTree::Seq OldRegion = Region; + + EvaluationTracker Eval(*this); + { + SequencedSubexpression Sequenced(*this); + Region = LHSRegion; + Visit(BO->getLHS()); + } + + // C++11 [expr.log.and]p1: + // [...] the second operand is not evaluated if the first operand is false. + bool EvalResult = false; + bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); + bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); + if (ShouldVisitRHS) { + Region = RHSRegion; + Visit(BO->getRHS()); + } + + Region = OldRegion; + Tree.merge(LHSRegion); + Tree.merge(RHSRegion); + } + + void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { + // C++11 [expr.cond]p1: + // [...] Every value computation and side effect associated with the first + // expression is sequenced before every value computation and side effect + // associated with the second or third expression. + SequenceTree::Seq ConditionRegion = Tree.allocate(Region); + + // No sequencing is specified between the true and false expression. + // However since exactly one of both is going to be evaluated we can + // consider them to be sequenced. This is needed to avoid warning on + // something like "x ? y+= 1 : y += 2;" in the case where we will visit + // both the true and false expressions because we can't evaluate x. + // This will still allow us to detect an expression like (pre C++17) + // "(x ? y += 1 : y += 2) = y". + // + // We don't wrap the visitation of the true and false expression with + // SequencedSubexpression because we don't want to downgrade modifications + // as side effect in the true and false expressions after the visition + // is done. (for example in the expression "(x ? y++ : y++) + y" we should + // not warn between the two "y++", but we should warn between the "y++" + // and the "y". + SequenceTree::Seq TrueRegion = Tree.allocate(Region); + SequenceTree::Seq FalseRegion = Tree.allocate(Region); + SequenceTree::Seq OldRegion = Region; + + EvaluationTracker Eval(*this); + { + SequencedSubexpression Sequenced(*this); + Region = ConditionRegion; + Visit(CO->getCond()); + } + + // C++11 [expr.cond]p1: + // [...] The first expression is contextually converted to bool (Clause 4). + // It is evaluated and if it is true, the result of the conditional + // expression is the value of the second expression, otherwise that of the + // third expression. Only one of the second and third expressions is + // evaluated. [...] + bool EvalResult = false; + bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); + bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); + bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); + if (ShouldVisitTrueExpr) { + Region = TrueRegion; + Visit(CO->getTrueExpr()); + } + if (ShouldVisitFalseExpr) { + Region = FalseRegion; + Visit(CO->getFalseExpr()); + } + + Region = OldRegion; + Tree.merge(ConditionRegion); + Tree.merge(TrueRegion); + Tree.merge(FalseRegion); + } + + void VisitCallExpr(const CallExpr *CE) { + // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. + + if (CE->isUnevaluatedBuiltinCall(Context)) + return; + + // C++11 [intro.execution]p15: + // When calling a function [...], every value computation and side effect + // associated with any argument expression, or with the postfix expression + // designating the called function, is sequenced before execution of every + // expression or statement in the body of the function [and thus before + // the value computation of its result]. + SequencedSubexpression Sequenced(*this); + SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { + // C++17 [expr.call]p5 + // The postfix-expression is sequenced before each expression in the + // expression-list and any default argument. [...] + SequenceTree::Seq CalleeRegion; + SequenceTree::Seq OtherRegion; + if (SemaRef.getLangOpts().CPlusPlus17) { + CalleeRegion = Tree.allocate(Region); + OtherRegion = Tree.allocate(Region); + } else { + CalleeRegion = Region; + OtherRegion = Region; + } + SequenceTree::Seq OldRegion = Region; + + // Visit the callee expression first. + Region = CalleeRegion; + if (SemaRef.getLangOpts().CPlusPlus17) { + SequencedSubexpression Sequenced(*this); + Visit(CE->getCallee()); + } else { + Visit(CE->getCallee()); + } + + // Then visit the argument expressions. + Region = OtherRegion; + for (const Expr *Argument : CE->arguments()) + Visit(Argument); + + Region = OldRegion; + if (SemaRef.getLangOpts().CPlusPlus17) { + Tree.merge(CalleeRegion); + Tree.merge(OtherRegion); + } + }); + } + + void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { + // C++17 [over.match.oper]p2: + // [...] the operator notation is first transformed to the equivalent + // function-call notation as summarized in Table 12 (where @ denotes one + // of the operators covered in the specified subclause). However, the + // operands are sequenced in the order prescribed for the built-in + // operator (Clause 8). + // + // From the above only overloaded binary operators and overloaded call + // operators have sequencing rules in C++17 that we need to handle + // separately. + if (!SemaRef.getLangOpts().CPlusPlus17 || + (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) + return VisitCallExpr(CXXOCE); + + enum { + NoSequencing, + LHSBeforeRHS, + RHSBeforeLHS, + LHSBeforeRest + } SequencingKind; + switch (CXXOCE->getOperator()) { + case OO_Equal: + case OO_PlusEqual: + case OO_MinusEqual: + case OO_StarEqual: + case OO_SlashEqual: + case OO_PercentEqual: + case OO_CaretEqual: + case OO_AmpEqual: + case OO_PipeEqual: + case OO_LessLessEqual: + case OO_GreaterGreaterEqual: + SequencingKind = RHSBeforeLHS; + break; + + case OO_LessLess: + case OO_GreaterGreater: + case OO_AmpAmp: + case OO_PipePipe: + case OO_Comma: + case OO_ArrowStar: + case OO_Subscript: + SequencingKind = LHSBeforeRHS; + break; + + case OO_Call: + SequencingKind = LHSBeforeRest; + break; + + default: + SequencingKind = NoSequencing; + break; + } + + if (SequencingKind == NoSequencing) + return VisitCallExpr(CXXOCE); + + // This is a call, so all subexpressions are sequenced before the result. + SequencedSubexpression Sequenced(*this); + + SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { + assert(SemaRef.getLangOpts().CPlusPlus17 && + "Should only get there with C++17 and above!"); + assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && + "Should only get there with an overloaded binary operator" + " or an overloaded call operator!"); + + if (SequencingKind == LHSBeforeRest) { + assert(CXXOCE->getOperator() == OO_Call && + "We should only have an overloaded call operator here!"); + + // This is very similar to VisitCallExpr, except that we only have the + // C++17 case. The postfix-expression is the first argument of the + // CXXOperatorCallExpr. The expressions in the expression-list, if any, + // are in the following arguments. + // + // Note that we intentionally do not visit the callee expression since + // it is just a decayed reference to a function. + SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); + SequenceTree::Seq ArgsRegion = Tree.allocate(Region); + SequenceTree::Seq OldRegion = Region; + + assert(CXXOCE->getNumArgs() >= 1 && + "An overloaded call operator must have at least one argument" + " for the postfix-expression!"); + const Expr *PostfixExpr = CXXOCE->getArgs()[0]; + llvm::ArrayRef Args(CXXOCE->getArgs() + 1, + CXXOCE->getNumArgs() - 1); + + // Visit the postfix-expression first. + { + Region = PostfixExprRegion; + SequencedSubexpression Sequenced(*this); + Visit(PostfixExpr); + } + + // Then visit the argument expressions. + Region = ArgsRegion; + for (const Expr *Arg : Args) + Visit(Arg); + + Region = OldRegion; + Tree.merge(PostfixExprRegion); + Tree.merge(ArgsRegion); + } else { + assert(CXXOCE->getNumArgs() == 2 && + "Should only have two arguments here!"); + assert((SequencingKind == LHSBeforeRHS || + SequencingKind == RHSBeforeLHS) && + "Unexpected sequencing kind!"); + + // We do not visit the callee expression since it is just a decayed + // reference to a function. + const Expr *E1 = CXXOCE->getArg(0); + const Expr *E2 = CXXOCE->getArg(1); + if (SequencingKind == RHSBeforeLHS) + std::swap(E1, E2); + + return VisitSequencedExpressions(E1, E2); + } + }); + } + + void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { + // This is a call, so all subexpressions are sequenced before the result. + SequencedSubexpression Sequenced(*this); + + if (!CCE->isListInitialization()) + return VisitExpr(CCE); + + // In C++11, list initializations are sequenced. + SmallVector Elts; + SequenceTree::Seq Parent = Region; + for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), + E = CCE->arg_end(); + I != E; ++I) { + Region = Tree.allocate(Parent); + Elts.push_back(Region); + Visit(*I); + } + + // Forget that the initializers are sequenced. + Region = Parent; + for (unsigned I = 0; I < Elts.size(); ++I) + Tree.merge(Elts[I]); + } + + void VisitInitListExpr(const InitListExpr *ILE) { + if (!SemaRef.getLangOpts().CPlusPlus11) + return VisitExpr(ILE); + + // In C++11, list initializations are sequenced. + SmallVector Elts; + SequenceTree::Seq Parent = Region; + for (unsigned I = 0; I < ILE->getNumInits(); ++I) { + const Expr *E = ILE->getInit(I); + if (!E) + continue; + Region = Tree.allocate(Parent); + Elts.push_back(Region); + Visit(E); + } + + // Forget that the initializers are sequenced. + Region = Parent; + for (unsigned I = 0; I < Elts.size(); ++I) + Tree.merge(Elts[I]); + } + }; + + } // namespace + + void Sema::CheckUnsequencedOperations(const Expr *E) { + SmallVector WorkList; + WorkList.push_back(E); + while (!WorkList.empty()) { + const Expr *Item = WorkList.pop_back_val(); + SequenceChecker(*this, Item, WorkList); + } + } + + void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, + bool IsConstexpr) { + llvm::SaveAndRestore ConstantContext( + isConstantEvaluatedOverride, IsConstexpr || isa(E)); + CheckImplicitConversions(E, CheckLoc); + if (!E->isInstantiationDependent()) + CheckUnsequencedOperations(E); + if (!IsConstexpr && !E->isValueDependent()) + CheckForIntOverflow(E); + DiagnoseMisalignedMembers(); + } + + void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, + FieldDecl *BitField, + Expr *Init) { + (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); + } + + static void diagnoseArrayStarInParamType(Sema &S, QualType PType, + SourceLocation Loc) { + if (!PType->isVariablyModifiedType()) + return; + if (const auto *PointerTy = dyn_cast(PType)) { + diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); + return; + } + if (const auto *ReferenceTy = dyn_cast(PType)) { + diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); + return; + } + if (const auto *ParenTy = dyn_cast(PType)) { + diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); + return; + } + + const ArrayType *AT = S.Context.getAsArrayType(PType); + if (!AT) + return; + + if (AT->getSizeModifier() != ArrayType::Star) { + diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); + return; + } + + S.Diag(Loc, diag::err_array_star_in_function_definition); + } + + /// CheckParmsForFunctionDef - Check that the parameters of the given + /// function are appropriate for the definition of a function. This + /// takes care of any checks that cannot be performed on the + /// declaration itself, e.g., that the types of each of the function + /// parameters are complete. + bool Sema::CheckParmsForFunctionDef(ArrayRef Parameters, + bool CheckParameterNames) { + bool HasInvalidParm = false; + for (ParmVarDecl *Param : Parameters) { + // C99 6.7.5.3p4: the parameters in a parameter type list in a + // function declarator that is part of a function definition of + // that function shall not have incomplete type. + // + // This is also C++ [dcl.fct]p6. + if (!Param->isInvalidDecl() && + RequireCompleteType(Param->getLocation(), Param->getType(), + diag::err_typecheck_decl_incomplete_type)) { + Param->setInvalidDecl(); + HasInvalidParm = true; + } + + // C99 6.9.1p5: If the declarator includes a parameter type list, the + // declaration of each parameter shall include an identifier. + if (CheckParameterNames && Param->getIdentifier() == nullptr && + !Param->isImplicit() && !getLangOpts().CPlusPlus) { + // Diagnose this as an extension in C17 and earlier. + if (!getLangOpts().C2x) + Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); + } + + // C99 6.7.5.3p12: + // If the function declarator is not part of a definition of that + // function, parameters may have incomplete type and may use the [*] + // notation in their sequences of declarator specifiers to specify + // variable length array types. + QualType PType = Param->getOriginalType(); + // FIXME: This diagnostic should point the '[*]' if source-location + // information is added for it. + diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); + + // If the parameter is a c++ class type and it has to be destructed in the + // callee function, declare the destructor so that it can be called by the + // callee function. Do not perform any direct access check on the dtor here. + if (!Param->isInvalidDecl()) { + if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { + if (!ClassDecl->isInvalidDecl() && + !ClassDecl->hasIrrelevantDestructor() && + !ClassDecl->isDependentContext() && + ClassDecl->isParamDestroyedInCallee()) { + CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); + MarkFunctionReferenced(Param->getLocation(), Destructor); + DiagnoseUseOfDecl(Destructor, Param->getLocation()); + } + } + } + + // Parameters with the pass_object_size attribute only need to be marked + // constant at function definitions. Because we lack information about + // whether we're on a declaration or definition when we're instantiating the + // attribute, we need to check for constness here. + if (const auto *Attr = Param->getAttr()) + if (!Param->getType().isConstQualified()) + Diag(Param->getLocation(), diag::err_attribute_pointers_only) + << Attr->getSpelling() << 1; + + // Check for parameter names shadowing fields from the class. + if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { + // The owning context for the parameter should be the function, but we + // want to see if this function's declaration context is a record. + DeclContext *DC = Param->getDeclContext(); + if (DC && DC->isFunctionOrMethod()) { + if (auto *RD = dyn_cast(DC->getParent())) + CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), + RD, /*DeclIsField*/ false); + } + } + } + + return HasInvalidParm; + } + + Optional> + static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); + + /// Compute the alignment and offset of the base class object given the + /// derived-to-base cast expression and the alignment and offset of the derived + /// class object. + static std::pair + getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, + CharUnits BaseAlignment, CharUnits Offset, + ASTContext &Ctx) { + for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; + ++PathI) { + const CXXBaseSpecifier *Base = *PathI; + const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); + if (Base->isVirtual()) { + // The complete object may have a lower alignment than the non-virtual + // alignment of the base, in which case the base may be misaligned. Choose + // the smaller of the non-virtual alignment and BaseAlignment, which is a + // conservative lower bound of the complete object alignment. + CharUnits NonVirtualAlignment = + Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); + BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); + Offset = CharUnits::Zero(); + } else { + const ASTRecordLayout &RL = + Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); + Offset += RL.getBaseClassOffset(BaseDecl); + } + DerivedType = Base->getType(); + } + + return std::make_pair(BaseAlignment, Offset); + } + + /// Compute the alignment and offset of a binary additive operator. + static Optional> + getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, + bool IsSub, ASTContext &Ctx) { + QualType PointeeType = PtrE->getType()->getPointeeType(); + + if (!PointeeType->isConstantSizeType()) + return llvm::None; + + auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); + + if (!P) + return llvm::None; + + CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); + if (Optional IdxRes = IntE->getIntegerConstantExpr(Ctx)) { + CharUnits Offset = EltSize * IdxRes->getExtValue(); + if (IsSub) + Offset = -Offset; + return std::make_pair(P->first, P->second + Offset); + } + + // If the integer expression isn't a constant expression, compute the lower + // bound of the alignment using the alignment and offset of the pointer + // expression and the element size. + return std::make_pair( + P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), + CharUnits::Zero()); + } + + /// This helper function takes an lvalue expression and returns the alignment of + /// a VarDecl and a constant offset from the VarDecl. + Optional> + static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { + E = E->IgnoreParens(); + switch (E->getStmtClass()) { + default: + break; + case Stmt::CStyleCastExprClass: + case Stmt::CXXStaticCastExprClass: + case Stmt::ImplicitCastExprClass: { + auto *CE = cast(E); + const Expr *From = CE->getSubExpr(); + switch (CE->getCastKind()) { + default: + break; + case CK_NoOp: + return getBaseAlignmentAndOffsetFromLValue(From, Ctx); + case CK_UncheckedDerivedToBase: + case CK_DerivedToBase: { + auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); + if (!P) + break; + return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, + P->second, Ctx); + } + } + break; + } + case Stmt::ArraySubscriptExprClass: { + auto *ASE = cast(E); + return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), + false, Ctx); + } + case Stmt::DeclRefExprClass: { + if (auto *VD = dyn_cast(cast(E)->getDecl())) { + // FIXME: If VD is captured by copy or is an escaping __block variable, + // use the alignment of VD's type. + if (!VD->getType()->isReferenceType()) + return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); + if (VD->hasInit()) + return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); + } + break; + } + case Stmt::MemberExprClass: { + auto *ME = cast(E); + auto *FD = dyn_cast(ME->getMemberDecl()); + if (!FD || FD->getType()->isReferenceType() || + FD->getParent()->isInvalidDecl()) + break; + Optional> P; + if (ME->isArrow()) + P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); + else + P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); + if (!P) + break; + const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); + uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); + return std::make_pair(P->first, + P->second + CharUnits::fromQuantity(Offset)); + } + case Stmt::UnaryOperatorClass: { + auto *UO = cast(E); + switch (UO->getOpcode()) { + default: + break; + case UO_Deref: + return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); + } + break; + } + case Stmt::BinaryOperatorClass: { + auto *BO = cast(E); + auto Opcode = BO->getOpcode(); + switch (Opcode) { + default: + break; + case BO_Comma: + return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); + } + break; + } + } + return llvm::None; + } + + /// This helper function takes a pointer expression and returns the alignment of + /// a VarDecl and a constant offset from the VarDecl. + Optional> + static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { + E = E->IgnoreParens(); + switch (E->getStmtClass()) { + default: + break; + case Stmt::CStyleCastExprClass: + case Stmt::CXXStaticCastExprClass: + case Stmt::ImplicitCastExprClass: { + auto *CE = cast(E); + const Expr *From = CE->getSubExpr(); + switch (CE->getCastKind()) { + default: + break; + case CK_NoOp: + return getBaseAlignmentAndOffsetFromPtr(From, Ctx); + case CK_ArrayToPointerDecay: + return getBaseAlignmentAndOffsetFromLValue(From, Ctx); + case CK_UncheckedDerivedToBase: + case CK_DerivedToBase: { + auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); + if (!P) + break; + return getDerivedToBaseAlignmentAndOffset( + CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); + } + } + break; + } + case Stmt::CXXThisExprClass: { + auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); + CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); + return std::make_pair(Alignment, CharUnits::Zero()); + } + case Stmt::UnaryOperatorClass: { + auto *UO = cast(E); + if (UO->getOpcode() == UO_AddrOf) + return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); + break; + } + case Stmt::BinaryOperatorClass: { + auto *BO = cast(E); + auto Opcode = BO->getOpcode(); + switch (Opcode) { + default: + break; + case BO_Add: + case BO_Sub: { + const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); + if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) + std::swap(LHS, RHS); + return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, + Ctx); + } + case BO_Comma: + return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); + } + break; + } + } + return llvm::None; + } + + static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { + // See if we can compute the alignment of a VarDecl and an offset from it. + Optional> P = + getBaseAlignmentAndOffsetFromPtr(E, S.Context); + + if (P) + return P->first.alignmentAtOffset(P->second); + + // If that failed, return the type's alignment. + return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); + } + + /// CheckCastAlign - Implements -Wcast-align, which warns when a + /// pointer cast increases the alignment requirements. + void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { + // This is actually a lot of work to potentially be doing on every + // cast; don't do it if we're ignoring -Wcast_align (as is the default). + if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) + return; + + // Ignore dependent types. + if (T->isDependentType() || Op->getType()->isDependentType()) + return; + + // Require that the destination be a pointer type. + const PointerType *DestPtr = T->getAs(); + if (!DestPtr) return; + + // If the destination has alignment 1, we're done. + QualType DestPointee = DestPtr->getPointeeType(); + if (DestPointee->isIncompleteType()) return; + CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); + if (DestAlign.isOne()) return; + + // Require that the source be a pointer type. + const PointerType *SrcPtr = Op->getType()->getAs(); + if (!SrcPtr) return; + QualType SrcPointee = SrcPtr->getPointeeType(); + + // Explicitly allow casts from cv void*. We already implicitly + // allowed casts to cv void*, since they have alignment 1. + // Also allow casts involving incomplete types, which implicitly + // includes 'void'. + if (SrcPointee->isIncompleteType()) return; + + CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); + + if (SrcAlign >= DestAlign) return; + + Diag(TRange.getBegin(), diag::warn_cast_align) + << Op->getType() << T + << static_cast(SrcAlign.getQuantity()) + << static_cast(DestAlign.getQuantity()) + << TRange << Op->getSourceRange(); + } + + /// Check whether this array fits the idiom of a size-one tail padded + /// array member of a struct. + /// + /// We avoid emitting out-of-bounds access warnings for such arrays as they are + /// commonly used to emulate flexible arrays in C89 code. + static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, + const NamedDecl *ND) { + if (Size != 1 || !ND) return false; + + const FieldDecl *FD = dyn_cast(ND); + if (!FD) return false; + + // Don't consider sizes resulting from macro expansions or template argument + // substitution to form C89 tail-padded arrays. + + TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); + while (TInfo) { + TypeLoc TL = TInfo->getTypeLoc(); + // Look through typedefs. + if (TypedefTypeLoc TTL = TL.getAs()) { + const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); + TInfo = TDL->getTypeSourceInfo(); + continue; + } + if (ConstantArrayTypeLoc CTL = TL.getAs()) { + const Expr *SizeExpr = dyn_cast(CTL.getSizeExpr()); + if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) + return false; + } + break; + } + + const RecordDecl *RD = dyn_cast(FD->getDeclContext()); + if (!RD) return false; + if (RD->isUnion()) return false; + if (const CXXRecordDecl *CRD = dyn_cast(RD)) { + if (!CRD->isStandardLayout()) return false; + } + + // See if this is the last field decl in the record. + const Decl *D = FD; + while ((D = D->getNextDeclInContext())) + if (isa(D)) + return false; + return true; + } + + void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, + const ArraySubscriptExpr *ASE, + bool AllowOnePastEnd, bool IndexNegated) { + // Already diagnosed by the constant evaluator. + if (isConstantEvaluated()) + return; + + IndexExpr = IndexExpr->IgnoreParenImpCasts(); + if (IndexExpr->isValueDependent()) + return; + + const Type *EffectiveType = + BaseExpr->getType()->getPointeeOrArrayElementType(); + BaseExpr = BaseExpr->IgnoreParenCasts(); + const ConstantArrayType *ArrayTy = + Context.getAsConstantArrayType(BaseExpr->getType()); + + const Type *BaseType = + ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); + bool IsUnboundedArray = (BaseType == nullptr); + if (EffectiveType->isDependentType() || + (!IsUnboundedArray && BaseType->isDependentType())) + return; + + Expr::EvalResult Result; + if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) + return; + + llvm::APSInt index = Result.Val.getInt(); + if (IndexNegated) { + index.setIsUnsigned(false); + index = -index; + } + + const NamedDecl *ND = nullptr; + if (const DeclRefExpr *DRE = dyn_cast(BaseExpr)) + ND = DRE->getDecl(); + if (const MemberExpr *ME = dyn_cast(BaseExpr)) + ND = ME->getMemberDecl(); + + if (IsUnboundedArray) { + if (index.isUnsigned() || !index.isNegative()) { + const auto &ASTC = getASTContext(); + unsigned AddrBits = + ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( + EffectiveType->getCanonicalTypeInternal())); + if (index.getBitWidth() < AddrBits) + index = index.zext(AddrBits); + Optional ElemCharUnits = + ASTC.getTypeSizeInCharsIfKnown(EffectiveType); + // PR50741 - If EffectiveType has unknown size (e.g., if it's a void + // pointer) bounds-checking isn't meaningful. + if (!ElemCharUnits) + return; + llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); + // If index has more active bits than address space, we already know + // we have a bounds violation to warn about. Otherwise, compute + // address of (index + 1)th element, and warn about bounds violation + // only if that address exceeds address space. + if (index.getActiveBits() <= AddrBits) { + bool Overflow; + llvm::APInt Product(index); + Product += 1; + Product = Product.umul_ov(ElemBytes, Overflow); + if (!Overflow && Product.getActiveBits() <= AddrBits) + return; + } + + // Need to compute max possible elements in address space, since that + // is included in diag message. + llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); + MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); + MaxElems += 1; + ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); + MaxElems = MaxElems.udiv(ElemBytes); + + unsigned DiagID = + ASE ? diag::warn_array_index_exceeds_max_addressable_bounds + : diag::warn_ptr_arith_exceeds_max_addressable_bounds; + + // Diag message shows element size in bits and in "bytes" (platform- + // dependent CharUnits) + DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, + PDiag(DiagID) + << toString(index, 10, true) << AddrBits + << (unsigned)ASTC.toBits(*ElemCharUnits) + << toString(ElemBytes, 10, false) + << toString(MaxElems, 10, false) + << (unsigned)MaxElems.getLimitedValue(~0U) + << IndexExpr->getSourceRange()); + + if (!ND) { + // Try harder to find a NamedDecl to point at in the note. + while (const auto *ASE = dyn_cast(BaseExpr)) + BaseExpr = ASE->getBase()->IgnoreParenCasts(); + if (const auto *DRE = dyn_cast(BaseExpr)) + ND = DRE->getDecl(); + if (const auto *ME = dyn_cast(BaseExpr)) + ND = ME->getMemberDecl(); + } + + if (ND) + DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, + PDiag(diag::note_array_declared_here) << ND); + } + return; + } + + if (index.isUnsigned() || !index.isNegative()) { + // It is possible that the type of the base expression after + // IgnoreParenCasts is incomplete, even though the type of the base + // expression before IgnoreParenCasts is complete (see PR39746 for an + // example). In this case we have no information about whether the array + // access exceeds the array bounds. However we can still diagnose an array + // access which precedes the array bounds. + if (BaseType->isIncompleteType()) + return; + + llvm::APInt size = ArrayTy->getSize(); + if (!size.isStrictlyPositive()) + return; + + if (BaseType != EffectiveType) { + // Make sure we're comparing apples to apples when comparing index to size + uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); + uint64_t array_typesize = Context.getTypeSize(BaseType); + // Handle ptrarith_typesize being zero, such as when casting to void* + if (!ptrarith_typesize) ptrarith_typesize = 1; + if (ptrarith_typesize != array_typesize) { + // There's a cast to a different size type involved + uint64_t ratio = array_typesize / ptrarith_typesize; + // TODO: Be smarter about handling cases where array_typesize is not a + // multiple of ptrarith_typesize + if (ptrarith_typesize * ratio == array_typesize) + size *= llvm::APInt(size.getBitWidth(), ratio); + } + } + + if (size.getBitWidth() > index.getBitWidth()) + index = index.zext(size.getBitWidth()); + else if (size.getBitWidth() < index.getBitWidth()) + size = size.zext(index.getBitWidth()); + + // For array subscripting the index must be less than size, but for pointer + // arithmetic also allow the index (offset) to be equal to size since + // computing the next address after the end of the array is legal and + // commonly done e.g. in C++ iterators and range-based for loops. + if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) + return; + + // Also don't warn for arrays of size 1 which are members of some + // structure. These are often used to approximate flexible arrays in C89 + // code. + if (IsTailPaddedMemberArray(*this, size, ND)) + return; + + // Suppress the warning if the subscript expression (as identified by the + // ']' location) and the index expression are both from macro expansions + // within a system header. + if (ASE) { + SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( + ASE->getRBracketLoc()); + if (SourceMgr.isInSystemHeader(RBracketLoc)) { + SourceLocation IndexLoc = + SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); + if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) + return; + } + } + + unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds + : diag::warn_ptr_arith_exceeds_bounds; + + DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, + PDiag(DiagID) << toString(index, 10, true) + << toString(size, 10, true) + << (unsigned)size.getLimitedValue(~0U) + << IndexExpr->getSourceRange()); + } else { + unsigned DiagID = diag::warn_array_index_precedes_bounds; + if (!ASE) { + DiagID = diag::warn_ptr_arith_precedes_bounds; + if (index.isNegative()) index = -index; + } + + DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, + PDiag(DiagID) << toString(index, 10, true) + << IndexExpr->getSourceRange()); + } + + if (!ND) { + // Try harder to find a NamedDecl to point at in the note. + while (const auto *ASE = dyn_cast(BaseExpr)) + BaseExpr = ASE->getBase()->IgnoreParenCasts(); + if (const auto *DRE = dyn_cast(BaseExpr)) + ND = DRE->getDecl(); + if (const auto *ME = dyn_cast(BaseExpr)) + ND = ME->getMemberDecl(); + } + + if (ND) + DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, + PDiag(diag::note_array_declared_here) << ND); + } + + void Sema::CheckArrayAccess(const Expr *expr) { + int AllowOnePastEnd = 0; + while (expr) { + expr = expr->IgnoreParenImpCasts(); + switch (expr->getStmtClass()) { + case Stmt::ArraySubscriptExprClass: { + const ArraySubscriptExpr *ASE = cast(expr); + CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, + AllowOnePastEnd > 0); + expr = ASE->getBase(); + break; + } + case Stmt::MemberExprClass: { + expr = cast(expr)->getBase(); + break; + } + case Stmt::OMPArraySectionExprClass: { + const OMPArraySectionExpr *ASE = cast(expr); + if (ASE->getLowerBound()) + CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), + /*ASE=*/nullptr, AllowOnePastEnd > 0); + return; + } + case Stmt::UnaryOperatorClass: { + // Only unwrap the * and & unary operators + const UnaryOperator *UO = cast(expr); + expr = UO->getSubExpr(); + switch (UO->getOpcode()) { + case UO_AddrOf: + AllowOnePastEnd++; + break; + case UO_Deref: + AllowOnePastEnd--; + break; + default: + return; + } + break; + } + case Stmt::ConditionalOperatorClass: { + const ConditionalOperator *cond = cast(expr); + if (const Expr *lhs = cond->getLHS()) + CheckArrayAccess(lhs); + if (const Expr *rhs = cond->getRHS()) + CheckArrayAccess(rhs); + return; + } + case Stmt::CXXOperatorCallExprClass: { + const auto *OCE = cast(expr); + for (const auto *Arg : OCE->arguments()) + CheckArrayAccess(Arg); + return; + } + default: + return; + } + } + } + + //===--- CHECK: Objective-C retain cycles ----------------------------------// + + namespace { + + struct RetainCycleOwner { + VarDecl *Variable = nullptr; + SourceRange Range; + SourceLocation Loc; + bool Indirect = false; + + RetainCycleOwner() = default; + + void setLocsFrom(Expr *e) { + Loc = e->getExprLoc(); + Range = e->getSourceRange(); + } + }; + + } // namespace + + /// Consider whether capturing the given variable can possibly lead to + /// a retain cycle. + static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { + // In ARC, it's captured strongly iff the variable has __strong + // lifetime. In MRR, it's captured strongly if the variable is + // __block and has an appropriate type. + if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) + return false; + + owner.Variable = var; + if (ref) + owner.setLocsFrom(ref); + return true; + } + + static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { + while (true) { + e = e->IgnoreParens(); + if (CastExpr *cast = dyn_cast(e)) { + switch (cast->getCastKind()) { + case CK_BitCast: + case CK_LValueBitCast: + case CK_LValueToRValue: + case CK_ARCReclaimReturnedObject: + e = cast->getSubExpr(); + continue; + + default: + return false; + } + } + + if (ObjCIvarRefExpr *ref = dyn_cast(e)) { + ObjCIvarDecl *ivar = ref->getDecl(); + if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) + return false; + + // Try to find a retain cycle in the base. + if (!findRetainCycleOwner(S, ref->getBase(), owner)) + return false; + + if (ref->isFreeIvar()) owner.setLocsFrom(ref); + owner.Indirect = true; + return true; + } + + if (DeclRefExpr *ref = dyn_cast(e)) { + VarDecl *var = dyn_cast(ref->getDecl()); + if (!var) return false; + return considerVariable(var, ref, owner); + } + + if (MemberExpr *member = dyn_cast(e)) { + if (member->isArrow()) return false; + + // Don't count this as an indirect ownership. + e = member->getBase(); + continue; + } + + if (PseudoObjectExpr *pseudo = dyn_cast(e)) { + // Only pay attention to pseudo-objects on property references. + ObjCPropertyRefExpr *pre + = dyn_cast(pseudo->getSyntacticForm() + ->IgnoreParens()); + if (!pre) return false; + if (pre->isImplicitProperty()) return false; + ObjCPropertyDecl *property = pre->getExplicitProperty(); + if (!property->isRetaining() && + !(property->getPropertyIvarDecl() && + property->getPropertyIvarDecl()->getType() + .getObjCLifetime() == Qualifiers::OCL_Strong)) + return false; + + owner.Indirect = true; + if (pre->isSuperReceiver()) { + owner.Variable = S.getCurMethodDecl()->getSelfDecl(); + if (!owner.Variable) + return false; + owner.Loc = pre->getLocation(); + owner.Range = pre->getSourceRange(); + return true; + } + e = const_cast(cast(pre->getBase()) + ->getSourceExpr()); + continue; + } + + // Array ivars? + + return false; + } + } + + namespace { + + struct FindCaptureVisitor : EvaluatedExprVisitor { + ASTContext &Context; + VarDecl *Variable; + Expr *Capturer = nullptr; + bool VarWillBeReased = false; + + FindCaptureVisitor(ASTContext &Context, VarDecl *variable) + : EvaluatedExprVisitor(Context), + Context(Context), Variable(variable) {} + + void VisitDeclRefExpr(DeclRefExpr *ref) { + if (ref->getDecl() == Variable && !Capturer) + Capturer = ref; + } + + void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { + if (Capturer) return; + Visit(ref->getBase()); + if (Capturer && ref->isFreeIvar()) + Capturer = ref; + } + + void VisitBlockExpr(BlockExpr *block) { + // Look inside nested blocks + if (block->getBlockDecl()->capturesVariable(Variable)) + Visit(block->getBlockDecl()->getBody()); + } + + void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { + if (Capturer) return; + if (OVE->getSourceExpr()) + Visit(OVE->getSourceExpr()); + } + + void VisitBinaryOperator(BinaryOperator *BinOp) { + if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) + return; + Expr *LHS = BinOp->getLHS(); + if (const DeclRefExpr *DRE = dyn_cast_or_null(LHS)) { + if (DRE->getDecl() != Variable) + return; + if (Expr *RHS = BinOp->getRHS()) { + RHS = RHS->IgnoreParenCasts(); + Optional Value; + VarWillBeReased = + (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && + *Value == 0); + } + } + } + }; + + } // namespace + + /// Check whether the given argument is a block which captures a + /// variable. + static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { + assert(owner.Variable && owner.Loc.isValid()); + + e = e->IgnoreParenCasts(); + + // Look through [^{...} copy] and Block_copy(^{...}). + if (ObjCMessageExpr *ME = dyn_cast(e)) { + Selector Cmd = ME->getSelector(); + if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { + e = ME->getInstanceReceiver(); + if (!e) + return nullptr; + e = e->IgnoreParenCasts(); + } + } else if (CallExpr *CE = dyn_cast(e)) { + if (CE->getNumArgs() == 1) { + FunctionDecl *Fn = dyn_cast_or_null(CE->getCalleeDecl()); + if (Fn) { + const IdentifierInfo *FnI = Fn->getIdentifier(); + if (FnI && FnI->isStr("_Block_copy")) { + e = CE->getArg(0)->IgnoreParenCasts(); + } + } + } + } + + BlockExpr *block = dyn_cast(e); + if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) + return nullptr; + + FindCaptureVisitor visitor(S.Context, owner.Variable); + visitor.Visit(block->getBlockDecl()->getBody()); + return visitor.VarWillBeReased ? nullptr : visitor.Capturer; + } + + static void diagnoseRetainCycle(Sema &S, Expr *capturer, + RetainCycleOwner &owner) { + assert(capturer); + assert(owner.Variable && owner.Loc.isValid()); + + S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) + << owner.Variable << capturer->getSourceRange(); + S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) + << owner.Indirect << owner.Range; + } + + /// Check for a keyword selector that starts with the word 'add' or + /// 'set'. + static bool isSetterLikeSelector(Selector sel) { + if (sel.isUnarySelector()) return false; + + StringRef str = sel.getNameForSlot(0); + while (!str.empty() && str.front() == '_') str = str.substr(1); + if (str.startswith("set")) + str = str.substr(3); + else if (str.startswith("add")) { + // Specially allow 'addOperationWithBlock:'. + if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) + return false; + str = str.substr(3); + } + else + return false; + + if (str.empty()) return true; + return !isLowercase(str.front()); + } + + static Optional GetNSMutableArrayArgumentIndex(Sema &S, + ObjCMessageExpr *Message) { + bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( + Message->getReceiverInterface(), + NSAPI::ClassId_NSMutableArray); + if (!IsMutableArray) { + return None; + } + + Selector Sel = Message->getSelector(); + + Optional MKOpt = + S.NSAPIObj->getNSArrayMethodKind(Sel); + if (!MKOpt) { + return None; + } + + NSAPI::NSArrayMethodKind MK = *MKOpt; + + switch (MK) { + case NSAPI::NSMutableArr_addObject: + case NSAPI::NSMutableArr_insertObjectAtIndex: + case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: + return 0; + case NSAPI::NSMutableArr_replaceObjectAtIndex: + return 1; + + default: + return None; + } + + return None; + } + + static + Optional GetNSMutableDictionaryArgumentIndex(Sema &S, + ObjCMessageExpr *Message) { + bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( + Message->getReceiverInterface(), + NSAPI::ClassId_NSMutableDictionary); + if (!IsMutableDictionary) { + return None; + } + + Selector Sel = Message->getSelector(); + + Optional MKOpt = + S.NSAPIObj->getNSDictionaryMethodKind(Sel); + if (!MKOpt) { + return None; + } + + NSAPI::NSDictionaryMethodKind MK = *MKOpt; + + switch (MK) { + case NSAPI::NSMutableDict_setObjectForKey: + case NSAPI::NSMutableDict_setValueForKey: + case NSAPI::NSMutableDict_setObjectForKeyedSubscript: + return 0; + + default: + return None; + } + + return None; + } + + static Optional GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { + bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( + Message->getReceiverInterface(), + NSAPI::ClassId_NSMutableSet); + + bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( + Message->getReceiverInterface(), + NSAPI::ClassId_NSMutableOrderedSet); + if (!IsMutableSet && !IsMutableOrderedSet) { + return None; + } + + Selector Sel = Message->getSelector(); + + Optional MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); + if (!MKOpt) { + return None; + } + + NSAPI::NSSetMethodKind MK = *MKOpt; + + switch (MK) { + case NSAPI::NSMutableSet_addObject: + case NSAPI::NSOrderedSet_setObjectAtIndex: + case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: + case NSAPI::NSOrderedSet_insertObjectAtIndex: + return 0; + case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: + return 1; + } + + return None; + } + + void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { + if (!Message->isInstanceMessage()) { + return; + } + + Optional ArgOpt; + + if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && + !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && + !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { + return; + } + + int ArgIndex = *ArgOpt; + + Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); + if (OpaqueValueExpr *OE = dyn_cast(Arg)) { + Arg = OE->getSourceExpr()->IgnoreImpCasts(); + } + + if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { + if (DeclRefExpr *ArgRE = dyn_cast(Arg)) { + if (ArgRE->isObjCSelfExpr()) { + Diag(Message->getSourceRange().getBegin(), + diag::warn_objc_circular_container) + << ArgRE->getDecl() << StringRef("'super'"); + } + } + } else { + Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); + + if (OpaqueValueExpr *OE = dyn_cast(Receiver)) { + Receiver = OE->getSourceExpr()->IgnoreImpCasts(); + } + + if (DeclRefExpr *ReceiverRE = dyn_cast(Receiver)) { + if (DeclRefExpr *ArgRE = dyn_cast(Arg)) { + if (ReceiverRE->getDecl() == ArgRE->getDecl()) { + ValueDecl *Decl = ReceiverRE->getDecl(); + Diag(Message->getSourceRange().getBegin(), + diag::warn_objc_circular_container) + << Decl << Decl; + if (!ArgRE->isObjCSelfExpr()) { + Diag(Decl->getLocation(), + diag::note_objc_circular_container_declared_here) + << Decl; + } + } + } + } else if (ObjCIvarRefExpr *IvarRE = dyn_cast(Receiver)) { + if (ObjCIvarRefExpr *IvarArgRE = dyn_cast(Arg)) { + if (IvarRE->getDecl() == IvarArgRE->getDecl()) { + ObjCIvarDecl *Decl = IvarRE->getDecl(); + Diag(Message->getSourceRange().getBegin(), + diag::warn_objc_circular_container) + << Decl << Decl; + Diag(Decl->getLocation(), + diag::note_objc_circular_container_declared_here) + << Decl; + } + } + } + } + } + + /// Check a message send to see if it's likely to cause a retain cycle. + void Sema::checkRetainCycles(ObjCMessageExpr *msg) { + // Only check instance methods whose selector looks like a setter. + if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) + return; + + // Try to find a variable that the receiver is strongly owned by. + RetainCycleOwner owner; + if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { + if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) + return; + } else { + assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); + owner.Variable = getCurMethodDecl()->getSelfDecl(); + owner.Loc = msg->getSuperLoc(); + owner.Range = msg->getSuperLoc(); + } + + // Check whether the receiver is captured by any of the arguments. + const ObjCMethodDecl *MD = msg->getMethodDecl(); + for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { + if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { + // noescape blocks should not be retained by the method. + if (MD && MD->parameters()[i]->hasAttr()) + continue; + return diagnoseRetainCycle(*this, capturer, owner); + } + } + } + + /// Check a property assign to see if it's likely to cause a retain cycle. + void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { + RetainCycleOwner owner; + if (!findRetainCycleOwner(*this, receiver, owner)) + return; + + if (Expr *capturer = findCapturingExpr(*this, argument, owner)) + diagnoseRetainCycle(*this, capturer, owner); + } + + void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { + RetainCycleOwner Owner; + if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) + return; + + // Because we don't have an expression for the variable, we have to set the + // location explicitly here. + Owner.Loc = Var->getLocation(); + Owner.Range = Var->getSourceRange(); + + if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) + diagnoseRetainCycle(*this, Capturer, Owner); + } + + static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, + Expr *RHS, bool isProperty) { + // Check if RHS is an Objective-C object literal, which also can get + // immediately zapped in a weak reference. Note that we explicitly + // allow ObjCStringLiterals, since those are designed to never really die. + RHS = RHS->IgnoreParenImpCasts(); + + // This enum needs to match with the 'select' in + // warn_objc_arc_literal_assign (off-by-1). + Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); + if (Kind == Sema::LK_String || Kind == Sema::LK_None) + return false; + + S.Diag(Loc, diag::warn_arc_literal_assign) + << (unsigned) Kind + << (isProperty ? 0 : 1) + << RHS->getSourceRange(); + + return true; + } + + static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, + Qualifiers::ObjCLifetime LT, + Expr *RHS, bool isProperty) { + // Strip off any implicit cast added to get to the one ARC-specific. + while (ImplicitCastExpr *cast = dyn_cast(RHS)) { + if (cast->getCastKind() == CK_ARCConsumeObject) { + S.Diag(Loc, diag::warn_arc_retained_assign) + << (LT == Qualifiers::OCL_ExplicitNone) + << (isProperty ? 0 : 1) + << RHS->getSourceRange(); + return true; + } + RHS = cast->getSubExpr(); + } + + if (LT == Qualifiers::OCL_Weak && + checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) + return true; + + return false; + } + + bool Sema::checkUnsafeAssigns(SourceLocation Loc, + QualType LHS, Expr *RHS) { + Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); + + if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) + return false; + + if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) + return true; + + return false; + } + + void Sema::checkUnsafeExprAssigns(SourceLocation Loc, + Expr *LHS, Expr *RHS) { + QualType LHSType; + // PropertyRef on LHS type need be directly obtained from + // its declaration as it has a PseudoType. + ObjCPropertyRefExpr *PRE + = dyn_cast(LHS->IgnoreParens()); + if (PRE && !PRE->isImplicitProperty()) { + const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); + if (PD) + LHSType = PD->getType(); + } + + if (LHSType.isNull()) + LHSType = LHS->getType(); + + Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); + + if (LT == Qualifiers::OCL_Weak) { + if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) + getCurFunction()->markSafeWeakUse(LHS); + } + + if (checkUnsafeAssigns(Loc, LHSType, RHS)) + return; + + // FIXME. Check for other life times. + if (LT != Qualifiers::OCL_None) + return; + + if (PRE) { + if (PRE->isImplicitProperty()) + return; + const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); + if (!PD) + return; + + unsigned Attributes = PD->getPropertyAttributes(); + if (Attributes & ObjCPropertyAttribute::kind_assign) { + // when 'assign' attribute was not explicitly specified + // by user, ignore it and rely on property type itself + // for lifetime info. + unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); + if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && + LHSType->isObjCRetainableType()) + return; + + while (ImplicitCastExpr *cast = dyn_cast(RHS)) { + if (cast->getCastKind() == CK_ARCConsumeObject) { + Diag(Loc, diag::warn_arc_retained_property_assign) + << RHS->getSourceRange(); + return; + } + RHS = cast->getSubExpr(); + } + } else if (Attributes & ObjCPropertyAttribute::kind_weak) { + if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) + return; + } + } + } + + //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// + + static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, + SourceLocation StmtLoc, + const NullStmt *Body) { + // Do not warn if the body is a macro that expands to nothing, e.g: + // + // #define CALL(x) + // if (condition) + // CALL(0); + if (Body->hasLeadingEmptyMacro()) + return false; + + // Get line numbers of statement and body. + bool StmtLineInvalid; + unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, + &StmtLineInvalid); + if (StmtLineInvalid) + return false; + + bool BodyLineInvalid; + unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), + &BodyLineInvalid); + if (BodyLineInvalid) + return false; + + // Warn if null statement and body are on the same line. + if (StmtLine != BodyLine) + return false; + + return true; + } + + void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, + const Stmt *Body, + unsigned DiagID) { + // Since this is a syntactic check, don't emit diagnostic for template + // instantiations, this just adds noise. + if (CurrentInstantiationScope) + return; + + // The body should be a null statement. + const NullStmt *NBody = dyn_cast(Body); + if (!NBody) + return; + + // Do the usual checks. + if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) + return; + + Diag(NBody->getSemiLoc(), DiagID); + Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); + } + + void Sema::DiagnoseEmptyLoopBody(const Stmt *S, + const Stmt *PossibleBody) { + assert(!CurrentInstantiationScope); // Ensured by caller + + SourceLocation StmtLoc; + const Stmt *Body; + unsigned DiagID; + if (const ForStmt *FS = dyn_cast(S)) { + StmtLoc = FS->getRParenLoc(); + Body = FS->getBody(); + DiagID = diag::warn_empty_for_body; + } else if (const WhileStmt *WS = dyn_cast(S)) { + StmtLoc = WS->getCond()->getSourceRange().getEnd(); + Body = WS->getBody(); + DiagID = diag::warn_empty_while_body; + } else + return; // Neither `for' nor `while'. + + // The body should be a null statement. + const NullStmt *NBody = dyn_cast(Body); + if (!NBody) + return; + + // Skip expensive checks if diagnostic is disabled. + if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) + return; + + // Do the usual checks. + if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) + return; + + // `for(...);' and `while(...);' are popular idioms, so in order to keep + // noise level low, emit diagnostics only if for/while is followed by a + // CompoundStmt, e.g.: + // for (int i = 0; i < n; i++); + // { + // a(i); + // } + // or if for/while is followed by a statement with more indentation + // than for/while itself: + // for (int i = 0; i < n; i++); + // a(i); + bool ProbableTypo = isa(PossibleBody); + if (!ProbableTypo) { + bool BodyColInvalid; + unsigned BodyCol = SourceMgr.getPresumedColumnNumber( + PossibleBody->getBeginLoc(), &BodyColInvalid); + if (BodyColInvalid) + return; + + bool StmtColInvalid; + unsigned StmtCol = + SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); + if (StmtColInvalid) + return; + + if (BodyCol > StmtCol) + ProbableTypo = true; + } + + if (ProbableTypo) { + Diag(NBody->getSemiLoc(), DiagID); + Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); + } + } + + //===--- CHECK: Warn on self move with std::move. -------------------------===// + + /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. + void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, + SourceLocation OpLoc) { + if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) + return; + + if (inTemplateInstantiation()) + return; + + // Strip parens and casts away. + LHSExpr = LHSExpr->IgnoreParenImpCasts(); + RHSExpr = RHSExpr->IgnoreParenImpCasts(); + + // Check for a call expression + const CallExpr *CE = dyn_cast(RHSExpr); + if (!CE || CE->getNumArgs() != 1) + return; + + // Check for a call to std::move + if (!CE->isCallToStdMove()) + return; + + // Get argument from std::move + RHSExpr = CE->getArg(0); + + const DeclRefExpr *LHSDeclRef = dyn_cast(LHSExpr); + const DeclRefExpr *RHSDeclRef = dyn_cast(RHSExpr); + + // Two DeclRefExpr's, check that the decls are the same. + if (LHSDeclRef && RHSDeclRef) { + if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) + return; + if (LHSDeclRef->getDecl()->getCanonicalDecl() != + RHSDeclRef->getDecl()->getCanonicalDecl()) + return; + + Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() + << LHSExpr->getSourceRange() + << RHSExpr->getSourceRange(); + return; + } + + // Member variables require a different approach to check for self moves. + // MemberExpr's are the same if every nested MemberExpr refers to the same + // Decl and that the base Expr's are DeclRefExpr's with the same Decl or + // the base Expr's are CXXThisExpr's. + const Expr *LHSBase = LHSExpr; + const Expr *RHSBase = RHSExpr; + const MemberExpr *LHSME = dyn_cast(LHSExpr); + const MemberExpr *RHSME = dyn_cast(RHSExpr); + if (!LHSME || !RHSME) + return; + + while (LHSME && RHSME) { + if (LHSME->getMemberDecl()->getCanonicalDecl() != + RHSME->getMemberDecl()->getCanonicalDecl()) + return; + + LHSBase = LHSME->getBase(); + RHSBase = RHSME->getBase(); + LHSME = dyn_cast(LHSBase); + RHSME = dyn_cast(RHSBase); + } + + LHSDeclRef = dyn_cast(LHSBase); + RHSDeclRef = dyn_cast(RHSBase); + if (LHSDeclRef && RHSDeclRef) { + if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) + return; + if (LHSDeclRef->getDecl()->getCanonicalDecl() != + RHSDeclRef->getDecl()->getCanonicalDecl()) + return; + + Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() + << LHSExpr->getSourceRange() + << RHSExpr->getSourceRange(); + return; + } + + if (isa(LHSBase) && isa(RHSBase)) + Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() + << LHSExpr->getSourceRange() + << RHSExpr->getSourceRange(); + } + + //===--- Layout compatibility ----------------------------------------------// + + static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); + + /// Check if two enumeration types are layout-compatible. + static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { + // C++11 [dcl.enum] p8: + // Two enumeration types are layout-compatible if they have the same + // underlying type. + return ED1->isComplete() && ED2->isComplete() && + C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); + } + + /// Check if two fields are layout-compatible. + static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, + FieldDecl *Field2) { + if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) + return false; + + if (Field1->isBitField() != Field2->isBitField()) + return false; + + if (Field1->isBitField()) { + // Make sure that the bit-fields are the same length. + unsigned Bits1 = Field1->getBitWidthValue(C); + unsigned Bits2 = Field2->getBitWidthValue(C); + + if (Bits1 != Bits2) + return false; + } + + return true; + } + + /// Check if two standard-layout structs are layout-compatible. + /// (C++11 [class.mem] p17) + static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, + RecordDecl *RD2) { + // If both records are C++ classes, check that base classes match. + if (const CXXRecordDecl *D1CXX = dyn_cast(RD1)) { + // If one of records is a CXXRecordDecl we are in C++ mode, + // thus the other one is a CXXRecordDecl, too. + const CXXRecordDecl *D2CXX = cast(RD2); + // Check number of base classes. + if (D1CXX->getNumBases() != D2CXX->getNumBases()) + return false; + + // Check the base classes. + for (CXXRecordDecl::base_class_const_iterator + Base1 = D1CXX->bases_begin(), + BaseEnd1 = D1CXX->bases_end(), + Base2 = D2CXX->bases_begin(); + Base1 != BaseEnd1; + ++Base1, ++Base2) { + if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) + return false; + } + } else if (const CXXRecordDecl *D2CXX = dyn_cast(RD2)) { + // If only RD2 is a C++ class, it should have zero base classes. + if (D2CXX->getNumBases() > 0) + return false; + } + + // Check the fields. + RecordDecl::field_iterator Field2 = RD2->field_begin(), + Field2End = RD2->field_end(), + Field1 = RD1->field_begin(), + Field1End = RD1->field_end(); + for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { + if (!isLayoutCompatible(C, *Field1, *Field2)) + return false; + } + if (Field1 != Field1End || Field2 != Field2End) + return false; + + return true; + } + + /// Check if two standard-layout unions are layout-compatible. + /// (C++11 [class.mem] p18) + static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, + RecordDecl *RD2) { + llvm::SmallPtrSet UnmatchedFields; + for (auto *Field2 : RD2->fields()) + UnmatchedFields.insert(Field2); + + for (auto *Field1 : RD1->fields()) { + llvm::SmallPtrSet::iterator + I = UnmatchedFields.begin(), + E = UnmatchedFields.end(); + + for ( ; I != E; ++I) { + if (isLayoutCompatible(C, Field1, *I)) { + bool Result = UnmatchedFields.erase(*I); + (void) Result; + assert(Result); + break; + } + } + if (I == E) + return false; + } + + return UnmatchedFields.empty(); + } + + static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, + RecordDecl *RD2) { + if (RD1->isUnion() != RD2->isUnion()) + return false; + + if (RD1->isUnion()) + return isLayoutCompatibleUnion(C, RD1, RD2); + else + return isLayoutCompatibleStruct(C, RD1, RD2); + } + + /// Check if two types are layout-compatible in C++11 sense. + static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { + if (T1.isNull() || T2.isNull()) + return false; + + // C++11 [basic.types] p11: + // If two types T1 and T2 are the same type, then T1 and T2 are + // layout-compatible types. + if (C.hasSameType(T1, T2)) + return true; + + T1 = T1.getCanonicalType().getUnqualifiedType(); + T2 = T2.getCanonicalType().getUnqualifiedType(); + + const Type::TypeClass TC1 = T1->getTypeClass(); + const Type::TypeClass TC2 = T2->getTypeClass(); + + if (TC1 != TC2) + return false; + + if (TC1 == Type::Enum) { + return isLayoutCompatible(C, + cast(T1)->getDecl(), + cast(T2)->getDecl()); + } else if (TC1 == Type::Record) { + if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) + return false; + + return isLayoutCompatible(C, + cast(T1)->getDecl(), + cast(T2)->getDecl()); + } + + return false; + } + + //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// + + /// Given a type tag expression find the type tag itself. + /// + /// \param TypeExpr Type tag expression, as it appears in user's code. + /// + /// \param VD Declaration of an identifier that appears in a type tag. + /// + /// \param MagicValue Type tag magic value. + /// + /// \param isConstantEvaluated whether the evalaution should be performed in + + /// constant context. + static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, + const ValueDecl **VD, uint64_t *MagicValue, + bool isConstantEvaluated) { + while(true) { + if (!TypeExpr) + return false; + + TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); + + switch (TypeExpr->getStmtClass()) { + case Stmt::UnaryOperatorClass: { + const UnaryOperator *UO = cast(TypeExpr); + if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { + TypeExpr = UO->getSubExpr(); + continue; + } + return false; + } + + case Stmt::DeclRefExprClass: { + const DeclRefExpr *DRE = cast(TypeExpr); + *VD = DRE->getDecl(); + return true; + } + + case Stmt::IntegerLiteralClass: { + const IntegerLiteral *IL = cast(TypeExpr); + llvm::APInt MagicValueAPInt = IL->getValue(); + if (MagicValueAPInt.getActiveBits() <= 64) { + *MagicValue = MagicValueAPInt.getZExtValue(); + return true; + } else + return false; + } + + case Stmt::BinaryConditionalOperatorClass: + case Stmt::ConditionalOperatorClass: { + const AbstractConditionalOperator *ACO = + cast(TypeExpr); + bool Result; + if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, + isConstantEvaluated)) { + if (Result) + TypeExpr = ACO->getTrueExpr(); + else + TypeExpr = ACO->getFalseExpr(); + continue; + } + return false; + } + + case Stmt::BinaryOperatorClass: { + const BinaryOperator *BO = cast(TypeExpr); + if (BO->getOpcode() == BO_Comma) { + TypeExpr = BO->getRHS(); + continue; + } + return false; + } + + default: + return false; + } + } + } + + /// Retrieve the C type corresponding to type tag TypeExpr. + /// + /// \param TypeExpr Expression that specifies a type tag. + /// + /// \param MagicValues Registered magic values. + /// + /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong + /// kind. + /// + /// \param TypeInfo Information about the corresponding C type. + /// + /// \param isConstantEvaluated whether the evalaution should be performed in + /// constant context. + /// + /// \returns true if the corresponding C type was found. + static bool GetMatchingCType( + const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, + const ASTContext &Ctx, + const llvm::DenseMap + *MagicValues, + bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, + bool isConstantEvaluated) { + FoundWrongKind = false; + + // Variable declaration that has type_tag_for_datatype attribute. + const ValueDecl *VD = nullptr; + + uint64_t MagicValue; + + if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) + return false; + + if (VD) { + if (TypeTagForDatatypeAttr *I = VD->getAttr()) { + if (I->getArgumentKind() != ArgumentKind) { + FoundWrongKind = true; + return false; + } + TypeInfo.Type = I->getMatchingCType(); + TypeInfo.LayoutCompatible = I->getLayoutCompatible(); + TypeInfo.MustBeNull = I->getMustBeNull(); + return true; + } + return false; + } + + if (!MagicValues) + return false; + + llvm::DenseMap::const_iterator I = + MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); + if (I == MagicValues->end()) + return false; + + TypeInfo = I->second; + return true; + } + + void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, + uint64_t MagicValue, QualType Type, + bool LayoutCompatible, + bool MustBeNull) { + if (!TypeTagForDatatypeMagicValues) + TypeTagForDatatypeMagicValues.reset( + new llvm::DenseMap); + + TypeTagMagicValue Magic(ArgumentKind, MagicValue); + (*TypeTagForDatatypeMagicValues)[Magic] = + TypeTagData(Type, LayoutCompatible, MustBeNull); + } + + static bool IsSameCharType(QualType T1, QualType T2) { + const BuiltinType *BT1 = T1->getAs(); + if (!BT1) + return false; + + const BuiltinType *BT2 = T2->getAs(); + if (!BT2) + return false; + + BuiltinType::Kind T1Kind = BT1->getKind(); + BuiltinType::Kind T2Kind = BT2->getKind(); + + return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || + (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || + (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || + (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); + } + + void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, + const ArrayRef ExprArgs, + SourceLocation CallSiteLoc) { + const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); + bool IsPointerAttr = Attr->getIsPointer(); + + // Retrieve the argument representing the 'type_tag'. + unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); + if (TypeTagIdxAST >= ExprArgs.size()) { + Diag(CallSiteLoc, diag::err_tag_index_out_of_range) + << 0 << Attr->getTypeTagIdx().getSourceIndex(); + return; + } + const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; + bool FoundWrongKind; + TypeTagData TypeInfo; + if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, + TypeTagForDatatypeMagicValues.get(), FoundWrongKind, + TypeInfo, isConstantEvaluated())) { + if (FoundWrongKind) + Diag(TypeTagExpr->getExprLoc(), + diag::warn_type_tag_for_datatype_wrong_kind) + << TypeTagExpr->getSourceRange(); + return; + } + + // Retrieve the argument representing the 'arg_idx'. + unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); + if (ArgumentIdxAST >= ExprArgs.size()) { + Diag(CallSiteLoc, diag::err_tag_index_out_of_range) + << 1 << Attr->getArgumentIdx().getSourceIndex(); + return; + } + const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; + if (IsPointerAttr) { + // Skip implicit cast of pointer to `void *' (as a function argument). + if (const ImplicitCastExpr *ICE = dyn_cast(ArgumentExpr)) + if (ICE->getType()->isVoidPointerType() && + ICE->getCastKind() == CK_BitCast) + ArgumentExpr = ICE->getSubExpr(); + } + QualType ArgumentType = ArgumentExpr->getType(); + + // Passing a `void*' pointer shouldn't trigger a warning. + if (IsPointerAttr && ArgumentType->isVoidPointerType()) + return; + + if (TypeInfo.MustBeNull) { + // Type tag with matching void type requires a null pointer. + if (!ArgumentExpr->isNullPointerConstant(Context, + Expr::NPC_ValueDependentIsNotNull)) { + Diag(ArgumentExpr->getExprLoc(), + diag::warn_type_safety_null_pointer_required) + << ArgumentKind->getName() + << ArgumentExpr->getSourceRange() + << TypeTagExpr->getSourceRange(); + } + return; + } + + QualType RequiredType = TypeInfo.Type; + if (IsPointerAttr) + RequiredType = Context.getPointerType(RequiredType); + + bool mismatch = false; + if (!TypeInfo.LayoutCompatible) { + mismatch = !Context.hasSameType(ArgumentType, RequiredType); + + // C++11 [basic.fundamental] p1: + // Plain char, signed char, and unsigned char are three distinct types. + // + // But we treat plain `char' as equivalent to `signed char' or `unsigned + // char' depending on the current char signedness mode. + if (mismatch) + if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), + RequiredType->getPointeeType())) || + (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) + mismatch = false; + } else + if (IsPointerAttr) + mismatch = !isLayoutCompatible(Context, + ArgumentType->getPointeeType(), + RequiredType->getPointeeType()); + else + mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); + + if (mismatch) + Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) + << ArgumentType << ArgumentKind + << TypeInfo.LayoutCompatible << RequiredType + << ArgumentExpr->getSourceRange() + << TypeTagExpr->getSourceRange(); + } + + void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, + CharUnits Alignment) { + MisalignedMembers.emplace_back(E, RD, MD, Alignment); + } + + void Sema::DiagnoseMisalignedMembers() { + for (MisalignedMember &m : MisalignedMembers) { + const NamedDecl *ND = m.RD; + if (ND->getName().empty()) { + if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) + ND = TD; + } + Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) + << m.MD << ND << m.E->getSourceRange(); + } + MisalignedMembers.clear(); + } + + void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { + E = E->IgnoreParens(); + if (!T->isPointerType() && !T->isIntegerType()) + return; + if (isa(E) && + cast(E)->getOpcode() == UO_AddrOf) { + auto *Op = cast(E)->getSubExpr()->IgnoreParens(); + if (isa(Op)) { + auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); + if (MA != MisalignedMembers.end() && + (T->isIntegerType() || + (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || + Context.getTypeAlignInChars( + T->getPointeeType()) <= MA->Alignment)))) + MisalignedMembers.erase(MA); + } + } + } + + void Sema::RefersToMemberWithReducedAlignment( + Expr *E, + llvm::function_ref + Action) { + const auto *ME = dyn_cast(E); + if (!ME) + return; + + // No need to check expressions with an __unaligned-qualified type. + if (E->getType().getQualifiers().hasUnaligned()) + return; + + // For a chain of MemberExpr like "a.b.c.d" this list + // will keep FieldDecl's like [d, c, b]. + SmallVector ReverseMemberChain; + const MemberExpr *TopME = nullptr; + bool AnyIsPacked = false; + do { + QualType BaseType = ME->getBase()->getType(); + if (BaseType->isDependentType()) + return; + if (ME->isArrow()) + BaseType = BaseType->getPointeeType(); + RecordDecl *RD = BaseType->castAs()->getDecl(); + if (RD->isInvalidDecl()) + return; + + ValueDecl *MD = ME->getMemberDecl(); + auto *FD = dyn_cast(MD); + // We do not care about non-data members. + if (!FD || FD->isInvalidDecl()) + return; + + AnyIsPacked = + AnyIsPacked || (RD->hasAttr() || MD->hasAttr()); + ReverseMemberChain.push_back(FD); + + TopME = ME; + ME = dyn_cast(ME->getBase()->IgnoreParens()); + } while (ME); + assert(TopME && "We did not compute a topmost MemberExpr!"); + + // Not the scope of this diagnostic. + if (!AnyIsPacked) + return; + + const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); + const auto *DRE = dyn_cast(TopBase); + // TODO: The innermost base of the member expression may be too complicated. + // For now, just disregard these cases. This is left for future + // improvement. + if (!DRE && !isa(TopBase)) + return; + + // Alignment expected by the whole expression. + CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); + + // No need to do anything else with this case. + if (ExpectedAlignment.isOne()) + return; + + // Synthesize offset of the whole access. + CharUnits Offset; + for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); + I++) { + Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); + } + + // Compute the CompleteObjectAlignment as the alignment of the whole chain. + CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( + ReverseMemberChain.back()->getParent()->getTypeForDecl()); + + // The base expression of the innermost MemberExpr may give + // stronger guarantees than the class containing the member. + if (DRE && !TopME->isArrow()) { + const ValueDecl *VD = DRE->getDecl(); + if (!VD->getType()->isReferenceType()) + CompleteObjectAlignment = + std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); + } + + // Check if the synthesized offset fulfills the alignment. + if (Offset % ExpectedAlignment != 0 || + // It may fulfill the offset it but the effective alignment may still be + // lower than the expected expression alignment. + CompleteObjectAlignment < ExpectedAlignment) { + // If this happens, we want to determine a sensible culprit of this. + // Intuitively, watching the chain of member expressions from right to + // left, we start with the required alignment (as required by the field + // type) but some packed attribute in that chain has reduced the alignment. + // It may happen that another packed structure increases it again. But if + // we are here such increase has not been enough. So pointing the first + // FieldDecl that either is packed or else its RecordDecl is, + // seems reasonable. + FieldDecl *FD = nullptr; + CharUnits Alignment; + for (FieldDecl *FDI : ReverseMemberChain) { + if (FDI->hasAttr() || + FDI->getParent()->hasAttr()) { + FD = FDI; + Alignment = std::min( + Context.getTypeAlignInChars(FD->getType()), + Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); + break; + } + } + assert(FD && "We did not find a packed FieldDecl!"); + Action(E, FD->getParent(), FD, Alignment); + } + } + + void Sema::CheckAddressOfPackedMember(Expr *rhs) { + using namespace std::placeholders; + + RefersToMemberWithReducedAlignment( + rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, + _2, _3, _4)); + } + + ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, + ExprResult CallResult) { + if (checkArgCount(*this, TheCall, 1)) + return ExprError(); + + ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); + if (MatrixArg.isInvalid()) + return MatrixArg; + Expr *Matrix = MatrixArg.get(); + + auto *MType = Matrix->getType()->getAs(); + if (!MType) { + Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); + return ExprError(); + } + + // Create returned matrix type by swapping rows and columns of the argument + // matrix type. + QualType ResultType = Context.getConstantMatrixType( + MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); + + // Change the return type to the type of the returned matrix. + TheCall->setType(ResultType); + + // Update call argument to use the possibly converted matrix argument. + TheCall->setArg(0, Matrix); + return CallResult; + } + + // Get and verify the matrix dimensions. + static llvm::Optional + getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { + SourceLocation ErrorPos; + Optional Value = + Expr->getIntegerConstantExpr(S.Context, &ErrorPos); + if (!Value) { + S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) + << Name; + return {}; + } + uint64_t Dim = Value->getZExtValue(); + if (!ConstantMatrixType::isDimensionValid(Dim)) { + S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) + << Name << ConstantMatrixType::getMaxElementsPerDimension(); + return {}; + } + return Dim; + } + + ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, + ExprResult CallResult) { + if (!getLangOpts().MatrixTypes) { + Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); + return ExprError(); + } + + if (checkArgCount(*this, TheCall, 4)) + return ExprError(); + + unsigned PtrArgIdx = 0; + Expr *PtrExpr = TheCall->getArg(PtrArgIdx); + Expr *RowsExpr = TheCall->getArg(1); + Expr *ColumnsExpr = TheCall->getArg(2); + Expr *StrideExpr = TheCall->getArg(3); + + bool ArgError = false; + + // Check pointer argument. + { + ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); + if (PtrConv.isInvalid()) + return PtrConv; + PtrExpr = PtrConv.get(); + TheCall->setArg(0, PtrExpr); + if (PtrExpr->isTypeDependent()) { + TheCall->setType(Context.DependentTy); + return TheCall; + } + } + + auto *PtrTy = PtrExpr->getType()->getAs(); + QualType ElementTy; + if (!PtrTy) { + Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) + << PtrArgIdx + 1; + ArgError = true; + } else { + ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); + + if (!ConstantMatrixType::isValidElementType(ElementTy)) { + Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) + << PtrArgIdx + 1; + ArgError = true; + } + } + + // Apply default Lvalue conversions and convert the expression to size_t. + auto ApplyArgumentConversions = [this](Expr *E) { + ExprResult Conv = DefaultLvalueConversion(E); + if (Conv.isInvalid()) + return Conv; + + return tryConvertExprToType(Conv.get(), Context.getSizeType()); + }; + + // Apply conversion to row and column expressions. + ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); + if (!RowsConv.isInvalid()) { + RowsExpr = RowsConv.get(); + TheCall->setArg(1, RowsExpr); + } else + RowsExpr = nullptr; + + ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); + if (!ColumnsConv.isInvalid()) { + ColumnsExpr = ColumnsConv.get(); + TheCall->setArg(2, ColumnsExpr); + } else + ColumnsExpr = nullptr; + + // If any any part of the result matrix type is still pending, just use + // Context.DependentTy, until all parts are resolved. + if ((RowsExpr && RowsExpr->isTypeDependent()) || + (ColumnsExpr && ColumnsExpr->isTypeDependent())) { + TheCall->setType(Context.DependentTy); + return CallResult; + } + + // Check row and column dimensions. + llvm::Optional MaybeRows; + if (RowsExpr) + MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); + + llvm::Optional MaybeColumns; + if (ColumnsExpr) + MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); + + // Check stride argument. + ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); + if (StrideConv.isInvalid()) + return ExprError(); + StrideExpr = StrideConv.get(); + TheCall->setArg(3, StrideExpr); + + if (MaybeRows) { + if (Optional Value = + StrideExpr->getIntegerConstantExpr(Context)) { + uint64_t Stride = Value->getZExtValue(); + if (Stride < *MaybeRows) { + Diag(StrideExpr->getBeginLoc(), + diag::err_builtin_matrix_stride_too_small); + ArgError = true; + } + } + } + + if (ArgError || !MaybeRows || !MaybeColumns) + return ExprError(); + + TheCall->setType( + Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); + return CallResult; + } + + ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, + ExprResult CallResult) { + if (checkArgCount(*this, TheCall, 3)) + return ExprError(); + + unsigned PtrArgIdx = 1; + Expr *MatrixExpr = TheCall->getArg(0); + Expr *PtrExpr = TheCall->getArg(PtrArgIdx); + Expr *StrideExpr = TheCall->getArg(2); + + bool ArgError = false; + + { + ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); + if (MatrixConv.isInvalid()) + return MatrixConv; + MatrixExpr = MatrixConv.get(); + TheCall->setArg(0, MatrixExpr); + } + if (MatrixExpr->isTypeDependent()) { + TheCall->setType(Context.DependentTy); + return TheCall; + } + + auto *MatrixTy = MatrixExpr->getType()->getAs(); + if (!MatrixTy) { + Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; + ArgError = true; + } + + { + ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); + if (PtrConv.isInvalid()) + return PtrConv; + PtrExpr = PtrConv.get(); + TheCall->setArg(1, PtrExpr); + if (PtrExpr->isTypeDependent()) { + TheCall->setType(Context.DependentTy); + return TheCall; + } + } + + // Check pointer argument. + auto *PtrTy = PtrExpr->getType()->getAs(); + if (!PtrTy) { + Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) + << PtrArgIdx + 1; + ArgError = true; + } else { + QualType ElementTy = PtrTy->getPointeeType(); + if (ElementTy.isConstQualified()) { + Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); + ArgError = true; + } + ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); + if (MatrixTy && + !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { + Diag(PtrExpr->getBeginLoc(), + diag::err_builtin_matrix_pointer_arg_mismatch) + << ElementTy << MatrixTy->getElementType(); + ArgError = true; + } + } + + // Apply default Lvalue conversions and convert the stride expression to + // size_t. + { + ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); + if (StrideConv.isInvalid()) + return StrideConv; + + StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); + if (StrideConv.isInvalid()) + return StrideConv; + StrideExpr = StrideConv.get(); + TheCall->setArg(2, StrideExpr); + } + + // Check stride argument. + if (MatrixTy) { + if (Optional Value = + StrideExpr->getIntegerConstantExpr(Context)) { + uint64_t Stride = Value->getZExtValue(); + if (Stride < MatrixTy->getNumRows()) { + Diag(StrideExpr->getBeginLoc(), + diag::err_builtin_matrix_stride_too_small); + ArgError = true; + } + } + } + + if (ArgError) + return ExprError(); + + return CallResult; + } + + /// \brief Enforce the bounds of a TCB + /// CheckTCBEnforcement - Enforces that every function in a named TCB only + /// directly calls other functions in the same TCB as marked by the enforce_tcb + /// and enforce_tcb_leaf attributes. + void Sema::CheckTCBEnforcement(const CallExpr *TheCall, + const FunctionDecl *Callee) { + const FunctionDecl *Caller = getCurFunctionDecl(); + + // Calls to builtins are not enforced. + if (!Caller || !Caller->hasAttr() || + Callee->getBuiltinID() != 0) + return; + + // Search through the enforce_tcb and enforce_tcb_leaf attributes to find + // all TCBs the callee is a part of. + llvm::StringSet<> CalleeTCBs; + for_each(Callee->specific_attrs(), + [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); + for_each(Callee->specific_attrs(), + [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); + + // Go through the TCBs the caller is a part of and emit warnings if Caller + // is in a TCB that the Callee is not. + for_each( + Caller->specific_attrs(), + [&](const auto *A) { + StringRef CallerTCB = A->getTCBName(); + if (CalleeTCBs.count(CallerTCB) == 0) { + this->Diag(TheCall->getExprLoc(), + diag::warn_tcb_enforcement_violation) << Callee + << CallerTCB; + } + }); + } +diff --git a/clang/test/Sema/warn-bitwise-and-bool.c b/clang/test/Sema/warn-bitwise-and-bool.c +new file mode 100644 +index 000000000000..146ed95eee4b +--- /dev/null ++++ b/clang/test/Sema/warn-bitwise-and-bool.c +@@ -0,0 +1,56 @@ ++// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wbool-operation %s ++// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wall %s ++// RUN: %clang_cc1 -x c -fsyntax-only -Wbitwise-instead-of-logical -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s ++// RUN: %clang_cc1 -x c -fsyntax-only -Wbool-operation -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s ++// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wbool-operation %s ++// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wall %s ++// RUN: %clang_cc1 -x c++ -fsyntax-only -Wbitwise-instead-of-logical -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s ++// RUN: %clang_cc1 -x c++ -fsyntax-only -Wbool-operation -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s ++ ++#ifdef __cplusplus ++typedef bool boolean; ++#else ++typedef _Bool boolean; ++#endif ++ ++boolean foo(void); ++boolean bar(void); ++boolean baz(void) __attribute__((const)); ++void sink(boolean); ++ ++#define FOO foo() ++ ++void test(boolean a, boolean b, int *p, volatile int *q, int i) { ++ b = a & b; ++ b = foo() & a; ++ b = (p != 0) & (*p == 42); // FIXME: also warn for a non-volatile pointer dereference ++ b = foo() & (*q == 42); // expected-warning {{use of bitwise '&' with boolean operands}} ++ b = foo() & (int)(*q == 42); // OK, no warning expected ++ b = a & foo(); ++ b = (int)a & foo(); // OK, no warning expected ++ b = foo() & bar(); // expected-warning {{use of bitwise '&' with boolean operands}} ++ // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:14}:"&&" ++ b = foo() & (int)bar(); // OK, no warning expected ++ b = foo() & !bar(); // expected-warning {{use of bitwise '&' with boolean operands}} ++ // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:14}:"&&" ++ b = a & baz(); ++ b = bar() & FOO; // expected-warning {{use of bitwise '&' with boolean operands}} ++ // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:14}:"&&" ++ b = foo() & (int)FOO; // OK, no warning expected ++ b = b & foo(); ++ b = bar() & (i > 4); ++ b = (i == 7) & foo(); ++#ifdef __cplusplus ++ b = foo() bitand bar(); // expected-warning {{use of bitwise '&' with boolean operands}} ++#endif ++ ++ if (foo() & bar()) // expected-warning {{use of bitwise '&' with boolean operands}} ++ ; ++ ++ sink(a & b); ++ sink(a & foo()); ++ sink(foo() & bar()); // expected-warning {{use of bitwise '&' with boolean operands}} ++ ++ int n = i + 10; ++ b = (n & (n - 1)); ++} +diff --git a/clang/test/Sema/warn-bitwise-or-bool.c b/clang/test/Sema/warn-bitwise-or-bool.c +new file mode 100644 +index 000000000000..2fb9265d33a5 +--- /dev/null ++++ b/clang/test/Sema/warn-bitwise-or-bool.c +@@ -0,0 +1,56 @@ ++// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wbool-operation %s ++// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wall %s ++// RUN: %clang_cc1 -x c -fsyntax-only -Wbitwise-instead-of-logical -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s ++// RUN: %clang_cc1 -x c -fsyntax-only -Wbool-operation -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s ++// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wbool-operation %s ++// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wall %s ++// RUN: %clang_cc1 -x c++ -fsyntax-only -Wbitwise-instead-of-logical -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s ++// RUN: %clang_cc1 -x c++ -fsyntax-only -Wbool-operation -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s ++ ++#ifdef __cplusplus ++typedef bool boolean; ++#else ++typedef _Bool boolean; ++#endif ++ ++boolean foo(void); ++boolean bar(void); ++boolean baz(void) __attribute__((const)); ++void sink(boolean); ++ ++#define FOO foo() ++ ++void test(boolean a, boolean b, int *p, volatile int *q, int i) { ++ b = a | b; ++ b = foo() | a; ++ b = (p != 0) | (*p == 42); // FIXME: also warn for a non-volatile pointer dereference ++ b = foo() | (*q == 42); // expected-warning {{use of bitwise '|' with boolean operands}} ++ b = foo() | (int)(*q == 42); // OK, no warning expected ++ b = a | foo(); ++ b = (int)a | foo(); // OK, no warning expected ++ b = foo() | bar(); // expected-warning {{use of bitwise '|' with boolean operands}} ++ // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:14}:"||" ++ b = foo() | !bar(); // expected-warning {{use of bitwise '|' with boolean operands}} ++ // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:14}:"||" ++ b = foo() | (int)bar(); // OK, no warning expected ++ b = a | baz(); ++ b = bar() | FOO; // expected-warning {{use of bitwise '|' with boolean operands}} ++ // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:14}:"||" ++ b = foo() | (int)FOO; // OK, no warning expected ++ b = b | foo(); ++ b = bar() | (i > 4); ++ b = (i == 7) | foo(); ++#ifdef __cplusplus ++ b = foo() bitor bar(); // expected-warning {{use of bitwise '|' with boolean operands}} ++#endif ++ ++ if (foo() | bar()) // expected-warning {{use of bitwise '|' with boolean operands}} ++ ; ++ ++ sink(a | b); ++ sink(a | foo()); ++ sink(foo() | bar()); // expected-warning {{use of bitwise '|' with boolean operands}} ++ ++ int n = i + 10; ++ b = (n | (n - 1)); ++} Index: clang/test/Sema/warn-bitwise-and-bool.c =================================================================== --- /dev/null +++ clang/test/Sema/warn-bitwise-and-bool.c @@ -0,0 +1,63 @@ +// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wbool-operation %s +// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wall %s +// RUN: %clang_cc1 -x c -fsyntax-only -Wbitwise-instead-of-logical -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s +// RUN: %clang_cc1 -x c -fsyntax-only -Wbool-operation -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s +// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wbool-operation %s +// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wall %s +// RUN: %clang_cc1 -x c++ -fsyntax-only -Wbitwise-instead-of-logical -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s +// RUN: %clang_cc1 -x c++ -fsyntax-only -Wbool-operation -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s + +#ifdef __cplusplus +typedef bool boolean; +#else +typedef _Bool boolean; +#endif + +boolean foo(void); +boolean bar(void); +boolean baz(void) __attribute__((const)); +void sink(boolean); + +#define FOO foo() + +void test(boolean a, boolean b, int *p, volatile int *q, int i) { + b = a & b; + b = foo() & a; + b = (p != 0) & (*p == 42); // FIXME: also warn for a non-volatile pointer dereference + b = foo() & (*q == 42); // expected-warning {{use of bitwise '&' with boolean operands}} + // expected-note@-1 {{cast one or both operands to int to silence warning}} + b = foo() & (int)(*q == 42); // OK, no warning expected + b = a & foo(); + b = (int)a & foo(); // OK, no warning expected + b = foo() & bar(); // expected-warning {{use of bitwise '&' with boolean operands}} + // expected-note@-1 {{cast one or both operands to int to silence warning}} + // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:13-[[@LINE-2]]:14}:"&&" + b = foo() & (int)bar(); // OK, no warning expected + b = foo() & !bar(); // expected-warning {{use of bitwise '&' with boolean operands}} + // expected-note@-1 {{cast one or both operands to int to silence warning}} + // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:13-[[@LINE-2]]:14}:"&&" + b = a & baz(); + b = bar() & FOO; // expected-warning {{use of bitwise '&' with boolean operands}} + // expected-note@-1 {{cast one or both operands to int to silence warning}} + // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:13-[[@LINE-2]]:14}:"&&" + b = foo() & (int)FOO; // OK, no warning expected + b = b & foo(); + b = bar() & (i > 4); + b = (i == 7) & foo(); +#ifdef __cplusplus + b = foo() bitand bar(); // expected-warning {{use of bitwise '&' with boolean operands}} + // expected-note@-1 {{cast one or both operands to int to silence warning}} +#endif + + if (foo() & bar()) // expected-warning {{use of bitwise '&' with boolean operands}} + // expected-note@-1 {{cast one or both operands to int to silence warning}} + ; + + sink(a & b); + sink(a & foo()); + sink(foo() & bar()); // expected-warning {{use of bitwise '&' with boolean operands}} + // expected-note@-1 {{cast one or both operands to int to silence warning}} + + int n = i + 10; + b = (n & (n - 1)); +} Index: clang/test/Sema/warn-bitwise-or-bool.c =================================================================== --- /dev/null +++ clang/test/Sema/warn-bitwise-or-bool.c @@ -0,0 +1,63 @@ +// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wbool-operation %s +// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wall %s +// RUN: %clang_cc1 -x c -fsyntax-only -Wbitwise-instead-of-logical -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s +// RUN: %clang_cc1 -x c -fsyntax-only -Wbool-operation -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s +// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wbool-operation %s +// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wall %s +// RUN: %clang_cc1 -x c++ -fsyntax-only -Wbitwise-instead-of-logical -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s +// RUN: %clang_cc1 -x c++ -fsyntax-only -Wbool-operation -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s + +#ifdef __cplusplus +typedef bool boolean; +#else +typedef _Bool boolean; +#endif + +boolean foo(void); +boolean bar(void); +boolean baz(void) __attribute__((const)); +void sink(boolean); + +#define FOO foo() + +void test(boolean a, boolean b, int *p, volatile int *q, int i) { + b = a | b; + b = foo() | a; + b = (p != 0) | (*p == 42); // FIXME: also warn for a non-volatile pointer dereference + b = foo() | (*q == 42); // expected-warning {{use of bitwise '|' with boolean operands}} + // expected-note@-1 {{cast one or both operands to int to silence warning}} + b = foo() | (int)(*q == 42); // OK, no warning expected + b = a | foo(); + b = (int)a | foo(); // OK, no warning expected + b = foo() | bar(); // expected-warning {{use of bitwise '|' with boolean operands}} + // expected-note@-1 {{cast one or both operands to int to silence warning}} + // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:13-[[@LINE-2]]:14}:"||" + b = foo() | !bar(); // expected-warning {{use of bitwise '|' with boolean operands}} + // expected-note@-1 {{cast one or both operands to int to silence warning}} + // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:13-[[@LINE-2]]:14}:"||" + b = foo() | (int)bar(); // OK, no warning expected + b = a | baz(); + b = bar() | FOO; // expected-warning {{use of bitwise '|' with boolean operands}} + // expected-note@-1 {{cast one or both operands to int to silence warning}} + // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:13-[[@LINE-2]]:14}:"||" + b = foo() | (int)FOO; // OK, no warning expected + b = b | foo(); + b = bar() | (i > 4); + b = (i == 7) | foo(); +#ifdef __cplusplus + b = foo() bitor bar(); // expected-warning {{use of bitwise '|' with boolean operands}} + // expected-note@-1 {{cast one or both operands to int to silence warning}} +#endif + + if (foo() | bar()) // expected-warning {{use of bitwise '|' with boolean operands}} + // expected-note@-1 {{cast one or both operands to int to silence warning}} + ; + + sink(a | b); + sink(a | foo()); + sink(foo() | bar()); // expected-warning {{use of bitwise '|' with boolean operands}} + // expected-note@-1 {{cast one or both operands to int to silence warning}} + + int n = i + 10; + b = (n | (n - 1)); +}