Index: clang/include/clang/Basic/DiagnosticSemaKinds.td =================================================================== --- clang/include/clang/Basic/DiagnosticSemaKinds.td +++ clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -3241,6 +3241,13 @@ "the only well defined values for BOOL are YES and NO">, InGroup; +def warn_impcast_integer_float_precision : Warning< + "implicit conversion from %0 to %1 may loses integer precision">, + InGroup, DefaultIgnore; +def warn_impcast_integer_float_precision_constant : Warning< + "implicit conversion from %2 to %3 changes value from %0 to %1">, + InGroup, DefaultIgnore; + def warn_impcast_fixed_point_range : Warning< "implicit conversion from %0 cannot fit within the range of values for %1">, InGroup; Index: clang/lib/Driver/ToolChains/Arch/AArch64.cpp =================================================================== --- clang/lib/Driver/ToolChains/Arch/AArch64.cpp +++ clang/lib/Driver/ToolChains/Arch/AArch64.cpp @@ -88,7 +88,7 @@ unsigned Extension = llvm::AArch64::getDefaultExtensions(CPU, ArchKind); if (!llvm::AArch64::getExtensionFeatures(Extension, Features)) return false; - } + } if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features)) return false; Index: clang/lib/Sema/SemaChecking.cpp =================================================================== --- clang/lib/Sema/SemaChecking.cpp +++ clang/lib/Sema/SemaChecking.cpp @@ -11400,6 +11400,54 @@ } } + // If we are casting an integer type to a floating point type, we might + // lose accuracy if the floating point type has a narrower signicand + // than the floating point type. Issue warnings for that accuracy loss. + if (SourceBT && TargetBT && + SourceBT->isIntegerType() && TargetBT->isFloatingType()) { + // Determine the number of precision bits in the source integer type. + IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); + unsigned int SourcePrecision = SourceRange.Width; + + // Determine the number of precision bits in the target floating point type + // Also create the APFloat object to represent the converted value. + unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( + S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); + llvm::APFloat SourceToFloatValue( + S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); + + // If we manage to find out the precisions for both types, perform + // acccuracy loss check and issue warning if necessary. + if (SourcePrecision > 0 && TargetPrecision > 0 && + SourcePrecision > TargetPrecision) { + // If the source integer is a constant, then we are sure that the + // implicit conversion will lose precision. Otherwise, the implicit + // conversion *may* lose precision. + llvm::APSInt SourceInt; + if (E->isIntegerConstantExpr(SourceInt, S.Context)) { + // Obtain string representations of source value and converted value. + std::string PrettySourceValue = SourceInt.toString(10); + SourceToFloatValue.convertFromAPInt(SourceInt, + SourceBT->isSignedInteger(), llvm::APFloat::rmTowardZero); + SmallString<32> PrettySourceConvertedValue; + SourceToFloatValue.toString(PrettySourceConvertedValue, + SourcePrecision); + + // Issue constant integer to float precision loss warning. + S.DiagRuntimeBehavior( + E->getExprLoc(), E, + S.PDiag(diag::warn_impcast_integer_float_precision_constant) + << PrettySourceValue << PrettySourceConvertedValue + << E->getType() << T + << E->getSourceRange() << clang::SourceRange(CC)); + } else { + // Issue integer variable to float precision may loss warning. + DiagnoseImpCast(S, E, T, CC, + diag::warn_impcast_integer_float_precision); + } + } + } + DiagnoseNullConversion(S, E, T, CC); S.DiscardMisalignedMemberAddress(Target, E); Index: clang/test/Sema/conversion.c =================================================================== --- clang/test/Sema/conversion.c +++ clang/test/Sema/conversion.c @@ -233,7 +233,7 @@ takes_int(v); takes_long(v); takes_longlong(v); - takes_float(v); + takes_float(v); // expected-warning {{implicit conversion from 'int' to 'float' may loses integer precision}} takes_double(v); takes_longdouble(v); } @@ -244,8 +244,8 @@ takes_int(v); // expected-warning {{implicit conversion loses integer precision}} takes_long(v); takes_longlong(v); - takes_float(v); - takes_double(v); + takes_float(v); // expected-warning {{implicit conversion from 'long' to 'float' may loses integer precision}} + takes_double(v); // expected-warning {{implicit conversion from 'long' to 'double' may loses integer precision}} takes_longdouble(v); } @@ -255,8 +255,8 @@ takes_int(v); // expected-warning {{implicit conversion loses integer precision}} takes_long(v); takes_longlong(v); - takes_float(v); - takes_double(v); + takes_float(v); // expected-warning {{implicit conversion from 'long long' to 'float' may loses integer precision}} + takes_double(v); // expected-warning {{implicit conversion from 'long long' to 'double' may loses integer precision}} takes_longdouble(v); } Index: clang/test/Sema/ext_vector_casts.c =================================================================== --- clang/test/Sema/ext_vector_casts.c +++ clang/test/Sema/ext_vector_casts.c @@ -115,12 +115,12 @@ vl = vl + t; // expected-warning {{implicit conversion loses integer precision}} vf = 1 + vf; - vf = l + vf; + vf = l + vf; // expected-warning {{implicit conversion from 'long' to 'float2' (vector of 2 'float' values) may loses integer precision}} vf = 2.0 + vf; vf = d + vf; // expected-warning {{implicit conversion loses floating-point precision}} - vf = vf + 0xffffffff; + vf = vf + 0xffffffff; // expected-warning {{implicit conversion from 'unsigned int' to 'float2' (vector of 2 'float' values) changes value}} vf = vf + 2.1; // expected-warning {{implicit conversion loses floating-point precision}} - vd = l + vd; - vd = vd + t; + vd = l + vd; // expected-warning {{implicit conversion from 'long' to 'double2' (vector of 2 'double' values) may loses integer precision}} + vd = vd + t; // expected-warning {{implicit conversion from '__uint128_t' (aka 'unsigned __int128') to 'double2' (vector of 2 'double' values) may loses integer precision}} } Index: clang/test/Sema/implicit-float-conversion.c =================================================================== --- /dev/null +++ clang/test/Sema/implicit-float-conversion.c @@ -0,0 +1,30 @@ +// RUN: %clang_cc1 %s -verify -Wno-conversion -Wimplicit-float-conversion + + +long testReturn(long a, float b) { + return a + b; // expected-warning {{implicit conversion from 'long' to 'float' may loses integer precision}} +} + + +void testAssignment() { + float f = 222222; + double b = 222222222222L; + + float ff = 222222222222L; // expected-warning {{implicit conversion from 'long' to 'float' changes value}} + + long l = 222222222222L; + float fff = l; // expected-warning {{implicit conversion from 'long' to 'float' may loses integer precision}} +} + + +void testExpression() { + float a = 0.0f; + float b = 222222222222L + a; // expected-warning {{implicit conversion from 'long' to 'float' changes value}} + float c = 22222222 + 22222223; // expected-warning {{implicit conversion from 'int' to 'float' changes value}} + + int i = 0; + float d = i + a; // expected-warning {{implicit conversion from 'int' to 'float' may loses integer precision}} + + double e = 0.0; + double f = i + e; +} Index: patch.patch =================================================================== --- /dev/null +++ patch.patch @@ -0,0 +1,25211 @@ +commit 83b6dfbef78deec435d45015f51a237b5bda93bf +Author: Ziang Wan +Date: Fri Jul 12 14:08:45 2019 -0700 + + integer type to floating type implicit conversion loss accuracy warning + +diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td +index 380db32ba4b..c20f21908a2 100644 +--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td ++++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td +@@ -1,9743 +1,9750 @@ + //==--- 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|constexpr if condition|explicit specifier argument}0 " + "is not a constant expression">; + def ext_cce_narrowing : ExtWarn< + "%select{case value|enumerator value|non-type template argument|" + "array size|constexpr if condition|explicit 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< + "integral constant expression must have integral or unscoped enumeration " + "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 cl_khr_fp64, 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 : Extension< + "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_init : Error< + "designator in initializer for scalar type %0">; + def warn_subobject_initializer_overrides : Warning< + "subobject initialization overrides initialization of other fields " + "within its enclosing subobject">, InGroup; + def warn_initializer_overrides : Warning< + "initializer overrides prior initialization of this subobject">, + InGroup; + def note_previous_initializer : Note< + "previous initialization %select{|with side effects }0is here" + "%select{| (side effects may 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; + + // 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_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 err_parameter_name_omitted : Error<"parameter name omitted">; + 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_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_variable : Warning<"unused variable %0">, + 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_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}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++2a 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++2a">, + 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 %2 elements, but %select{only |}3%1 " + "names were 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_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 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 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 err_using_decl_can_not_refer_to_scoped_enum : Error< + "using declaration cannot refer to a scoped enumerator">; + 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 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_operation : Warning< + "definition of implicit copy %select{constructor|assignment operator}1 " + "for %0 is deprecated because it has a user-declared " + "%select{copy %select{assignment operator|constructor}1|destructor}2">, + 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">; + + def warn_maybe_falloff_nonvoid_function : Warning< + "control may reach end of non-void function">, + InGroup; + def warn_falloff_nonvoid_function : Warning< + "control reaches end of non-void function">, + InGroup; + def err_maybe_falloff_nonvoid_block : Error< + "control may reach end of non-void block">; + def err_falloff_nonvoid_block : Error< + "control reaches end of non-void block">; + def warn_maybe_falloff_nonvoid_coroutine : Warning< + "control may reach end of coroutine; which is undefined behavior because the promise type %0 does not declare 'return_void()'">, + InGroup; + def warn_falloff_nonvoid_coroutine : Warning< + "control reaches end of coroutine; which is undefined behavior because the promise type %0 does not declare 'return_void()'">, + 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 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_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_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_nontrivial_primitive_type_in_union : Error< + "non-trivial C types are disallowed in union">; + 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_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; + + /// 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 ext_typedef_without_a_name : ExtWarn<"typedef requires a name">, + InGroup; + def err_typedef_not_identifier : Error<"typedef name must be an identifier">; + def err_typedef_changes_linkage : Error<"unsupported: typedef changes linkage" + " of anonymous type, but linkage was already computed">; + def note_typedef_changes_linkage : Note<"use a tag name here to establish " + "linkage prior to definition">; + 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_half_param : Error< + "declaring function parameter of type %0 is not allowed; did you forget * ?">; + 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 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 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_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 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_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_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>; + + // C++ declarations + def err_static_assert_expression_is_not_constant : Error< + "static_assert expression is not an integral 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">; + 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_type : Error< + "by-copy capture of variable %0 with incomplete type %1">; + 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 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 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">; + + // 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_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 implicit %sub{select_special_member_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_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_in_class_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">; + + def err_static_data_member_not_allowed_in_anon_struct : Error< + "static data member %0 not allowed in anonymous struct">; + 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 err_destructor_typedef_name : Error< + "destructor cannot be declared using a %select{typedef|type alias}1 %0 of the class name">; + def err_destructor_name : Error< + "expected the class name after '~' to name the enclosing class">; + def err_destructor_class_name : Error< + "expected the class name after '~' to name a destructor">; + def err_ident_in_dtor_not_a_type : 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 is declared here">; + + 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|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 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}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_cxx2a_compat_aggregate_init_with_ctors : Warning< + "aggregate initialization of type %0 with user-declared constructors " + "is incompatible with C++2a">, 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_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_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|" + "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}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_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 : Warning < + "%0 overrides a destructor but is not marked 'override'">, + InGroup, DefaultIgnore; + def warn_function_marked_not_override_overriding : Warning < + "%0 overrides a member function but is not marked 'override'">, + InGroup; + 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; + + // 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_enum_class_reference : Error< + "reference to %select{|scoped }0enumeration must use 'enum' " + "not 'enum class'">; + 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'}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_reference_copy : Warning< + "loop variable %0 " + "%diff{has type $ but is initialized with type $" + "| is initialized with a value of a different type}1,2 resulting in a copy">, + InGroup, DefaultIgnore; + def note_use_type_or_non_reference : Note< + "use non-reference type %0 to keep the copy or type %1 to prevent copying">; + def warn_for_range_variable_always_copy : Warning< + "loop variable %0 is always a copy because the range of type %1 does not " + "return a reference">, + InGroup, DefaultIgnore; + def note_use_non_reference_type : Note<"use non-reference type %0">; + def warn_for_range_copy : Warning< + "loop variable %0 of type %1 creates a copy from type %2">, + 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_constexpr : Error< + "%select{function parameter|typedef|non-static data member}0 " + "cannot be %select{constexpr|consteval}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 %select{constexpr|consteval}1">; + def err_constexpr_dtor : Error< + "destructor cannot be marked %select{constexpr|consteval}0">; + def err_constexpr_wrong_decl_kind : Error< + "%select{constexpr|consteval}0 can only be used " + "in %select{variable and |}0function 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_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++2a">, 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_cxx2a : ExtWarn< + "use of this statement in a constexpr %select{function|constructor}0 " + "is a C++2a 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++2a">, + 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 err_constexpr_local_var_no_init : Error< + "variables defined in a constexpr %select{function|constructor}0 must be " + "initialized">; + def ext_constexpr_function_never_constant_expr : ExtWarn< + "constexpr %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">; + def err_constexpr_function_try_block : Error< + "function try block not allowed in constexpr %select{function|constructor}0">; + + // c++2a function try blocks in constexpr + def ext_constexpr_function_try_block_cxx2a : ExtWarn< + "function try block in constexpr %select{function|constructor}0 is " + "a C++2a 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++2a">, + InGroup, DefaultIgnore; + + def err_constexpr_union_ctor_no_init : Error< + "constexpr union constructor does not initialize any member">; + def err_constexpr_ctor_missing_init : Error< + "constexpr constructor must initialize all members">; + 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_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_initialized_with_non_bool_type : Error< + "constraint expression must be of type 'bool' but is of type %0">; + 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_concept_not_implemented : Error< + "sorry, unimplemented concepts feature %0 used">; + + def err_template_different_associated_constraints : Error< + "associated constraints differ in template redeclaration">; + + // 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 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_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_bad_neon_vector_size : Error< + "Neon vector size must be 64 or 128 bits">; + 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< + "%0 attribute requires OpenCL version %1%select{| or above}2">; + def warn_unsupported_target_attribute + : Warning<"%select{unsupported|duplicate}0%select{| architecture}1 '%2' in" + " the 'target' attribute string; 'target' attribute ignored">, + InGroup; + def err_attribute_unsupported + : Error<"%0 attribute is not supported for this target">; + // 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 err_attribute_argument_n_type : Error< + "%0 attribute requires parameter %1 to be %select{int or bool|an integer " + "constant|a string|an identifier}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_vec_type_hint : Error< + "invalid attribute argument %0 - expecting a vector or vectorizable scalar 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 vector size">; + def err_attribute_size_too_large : Error<"vector size too large">; + 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_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< + "string 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_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 err_swift_param_attr_not_swiftcall : Error< + "'%0' parameter can only be used with swiftcall calling convention">; + 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_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 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_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 err_alignment_dependent_typedef_name : Error< + "requested alignment is dependent but declaration is not dependent">; + + def err_attribute_aligned_too_great : Error< + "requested alignment must be %0 bytes or smaller">; + 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_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_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 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 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 form 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 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_ignored : Warning< + "%0 calling convention ignored %select{" + // Use CallingConventionIgnoredReason Enum to specify these. + "for this target" + "|on variadic function" + "|on constructor/destructor" + "|on builtin function" + "}1">, + InGroup; + 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 ext_cannot_use_trivial_abi : ExtWarn< + "'trivial_abi' cannot be applied to %0">, InGroup; + + // 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>; + + // Thread Safety Attributes + def warn_invalid_capability_name : Warning< + "invalid capability name '%0'; capability name must be 'mutex' or 'role'">, + InGroup, DefaultIgnore; + 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(\"mutex\")' 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 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; + + // 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_int_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_integer_float_precision : Warning< ++ "implicit conversion from %0 to %1 may loses integer precision">, ++ InGroup, DefaultIgnore; ++def warn_impcast_integer_float_precision_constant : Warning< ++ "implicit conversion from %2 to %3 changes value from %0 to %1">, ++ InGroup, DefaultIgnore; ++ + 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_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_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_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 warn_division_sizeof_ptr : Warning< + "'%0' will return the size of the pointer, not the array itself">, + 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_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 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_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">; + + // 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">; + + 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 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">; + + 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|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)|" + "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_forbidden : Note< + "candidate %0 ignored: cannot be explicit">; + def note_explicit_bool_resolved_to_true : Note< + "explicit(bool) specifier resolved to true">; + 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 conflicting %select{types|values|" + "templates}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_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 note_ovl_candidate_disabled_by_extension : Note< + "candidate unavailable as it requires OpenCL extension '%0' to be enabled">; + 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 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: " + "cannot convert initializer list 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_lvalue : Note< + "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " + "expects an l-value 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: " + "address space mismatch in %select{%ordinal6|'this'}5 argument (%3), " + "parameter type must be %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_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_binary_candidate : Note< + "built-in candidate %0">; + def note_ovl_builtin_unary_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 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_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">; + + // 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 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 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++2a">, + 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++2a 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_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++2a 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++2a">, + 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 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_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; + + // 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 note_typename_refers_here : Note< + "referenced member %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 following the 'template' keyword 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_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_alias_template_expansion_into_fixed_list : Error< + "pack expansion used as argument for non-pack parameter of alias template">; + 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}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_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 ext_found_via_dependent_bases_lookup : ExtWarn<"use of identifier %0 " + "found via unqualified lookup into dependent bases of class templates is a " + "Microsoft extension">, InGroup; + def note_dependent_var_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_internal_linkage_redeclaration : Error< + "'internal_linkage' attribute does not appear on the first declaration of %0">; + 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 warn_illegal_constant_array_size : Extension< + "size of static array must be an integer constant expression">; + 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 warn_typecheck_zero_static_array_size : Warning< + "'static' has no effect on zero-length arrays">, + InGroup; + 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_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">; + 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">; + 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">; + def warn_missing_field_initializers : Warning< + "missing field %0 initializer">, + InGroup, DefaultIgnore; + def warn_braces_around_scalar_init : Warning< + "braces around scalar initializer">, InGroup>; + def ext_many_braces_around_scalar_init : ExtWarn< + "too many braces around scalar initializer">, + 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 warn_cxx98_compat_empty_scalar_initializer : Warning< + "scalar initialized from 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 bit-field %0 (%1 bits) exceeds %select{width|size}2 " + "of its type (%3 bit%s3)">; + def err_anon_bitfield_width_exceeds_type_width : Error< + "width of anonymous bit-field (%0 bits) exceeds %select{width|size}1 " + "of its type (%2 bit%s2)">; + 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 warn_anon_bitfield_width_exceeds_type_width : Warning< + "width of anonymous bit-field (%0 bits) exceeds width of its type; value " + "will be truncated to %1 bit%s1">, InGroup; + 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_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_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 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 : Error<"field has incomplete type %0">; + 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_object_in_tag : Error< + "ARC forbids %select{Objective-C objects|blocks}0 in " + "%select{struct|interface|union|<>|enum}1">; + 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_illegal_decl_array_incomplete_type : Error< + "array has incomplete element type %0">; + 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 |}0type " + "%1 %select{||||||which is not trivially copyable}0">; + + // Expressions. + def select_unary_expr_or_type_trait_kind : TextSubstitution< + "%select{sizeof|alignof|vec_step|__builtin_omp_required_simd_align|" + "__alignof}0">; + def ext_sizeof_alignof_function_type : Extension< + "invalid application of '%sub{select_unary_expr_or_type_trait_kind}0' " + "to a function type">, InGroup; + def ext_sizeof_alignof_void_type : Extension< + "invalid application of '%sub{select_unary_expr_or_type_trait_kind}0' " + "to a void type">, InGroup; + def err_opencl_sizeof_alignof_type : Error< + "invalid application of '%sub{select_unary_expr_or_type_trait_kind}0' " + "to a void type">; + def err_sizeof_alignof_incomplete_type : Error< + "invalid application of '%sub{select_unary_expr_or_type_trait_kind}0' " + "to an incomplete type %1">; + def err_sizeof_alignof_function_type : Error< + "invalid application of '%sub{select_unary_expr_or_type_trait_kind}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_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 note_precedence_conditional_first : Note< + "place parentheses around the '?:' expression to evaluate it first">; + + 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; + + def warn_logical_and_in_logical_or : Warning< + "'&&' within '||'">, InGroup; + + 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 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_return_std_move : Warning< + "local variable %0 will be copied despite being %select{returned|thrown}1 by name">, + InGroup, DefaultIgnore; + def note_add_std_move : Note< + "call 'std::move' explicitly to avoid copying">; + def warn_return_std_move_in_cxx11 : Warning< + "prior to the resolution of a defect report against ISO C++11, " + "local variable %0 would have been copied despite being returned by name, " + "due to its not matching the function return type%diff{ ($ vs $)|}1,2">, + InGroup, DefaultIgnore; + def note_add_std_move_in_cxx11 : Note< + "call 'std::move' explicitly to avoid copying on older compilers">; + + 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 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_type : Error< + "subscript of pointer to incomplete type %0">; + 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_type : Error< + "arithmetic on a pointer to an incomplete type %0">; + 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_cxx2a_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++2a">, InGroup, DefaultIgnore; + def note_cxx2a_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}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 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)">; + 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 ext_typecheck_ordered_comparison_of_function_pointers : ExtWarn< + "ordered comparison of function pointers (%0 and %1)">, + InGroup>; + 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 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_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 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_comparison_of_mixed_enum_types : Warning< + "comparison of two values with different enumeration types" + "%diff{ ($ and $)|}0,1">, + InGroup; + def warn_comparison_of_mixed_enum_types_switch : Warning< + "comparison of two values with different enumeration types in switch statement" + "%diff{ ($ and $)|}0,1">, + 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_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 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}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}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}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 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< + "%0 is not a reference or pointer">; + def err_bad_dynamic_cast_not_class : Error<"%0 is not a class">; + def err_bad_dynamic_cast_incomplete : Error<"%0 is an incomplete type">; + def err_bad_dynamic_cast_not_ptr : Error<"%0 is not a pointer">; + 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_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_type : Error< + "allocation of incomplete type %0">; + 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 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 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_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 only " + "available on %2 %3 or newer">; + 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_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 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 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_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< + "control may reach end of non-void lambda">, + InGroup; + def warn_falloff_nonvoid_lambda : Warning< + "control reaches end of non-void lambda">, + 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++2a">, InGroup, DefaultIgnore; + def ext_init_capture_pack : ExtWarn< + "initialized lambda pack captures are a C++2a 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++2a [=, 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++2a">, InGroup, DefaultIgnore; + def ext_equals_this_lambda_capture_cxx2a : ExtWarn< + "explicit capture of 'this' with a capture default of '=' " + "is a C++2a 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++2a 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++2a">, 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 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; + // 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 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 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 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 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 with different sign">, + InGroup>; + 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 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 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 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 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_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_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_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_int32_or_ptr : Error< + "address argument to atomic operation must be a pointer to signed or unsigned 32-bit integer">; + def err_atomic_op_bitwise_needs_atomic_int : Error< + "address argument to bitwise 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_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 " + "function %1 in %select{__device__|__global__|__host__|__host__ __device__}2 function">; + def err_ref_bad_target_global_initializer : Error< + "reference to %select{__device__|__global__|__host__|__host__ __device__}0 " + "function %1 in global initializer">; + 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__, and __shared__ variables.">; + def err_shared_var_init : Error< + "initialization is not supported for __shared__ variables.">; + def err_device_static_local_var : Error< + "within a %select{__device__|__global__|__host__|__host__ __device__}0 " + "function, only __shared__ variables or const variables without device " + "memory qualifier may be marked 'static'">; + 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_nonglobal_constant : Error<"__constant__ variables must be global">; + 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 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 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 err_cast_pointer_to_non_pointer_int : Error< + "pointer cannot be cast to type %0">; + 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_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_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_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 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">; + + def err_require_constant_init_failed : Error< + "variable does not have a constant initializer">; + def note_declared_required_constant_init_here : Note< + "required by 'require_constant_initialization' attribute 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_immediate_expected : Error<"constraint '%0' expects " + "an integer constant expression">; + 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_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 l-value: " + "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 l-value: " + "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_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< + "pointers 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_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_in_class_initializer_not_yet_parsed : Error< + "default member initializer for %1 needed within definition of enclosing " + "class %0 outside of member functions">; + def note_in_class_initializer_not_yet_parsed : Note< + "default member initializer declared here">; + def err_in_class_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 class %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 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">; + def warn_conv_to_base_not_used : Warning< + "conversion function converting %0 to its base class %1 will never be used">; + def warn_conv_to_void_not_used : Warning< + "conversion function converting %0 to %1 will never be used">; + + 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++2a">, 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">; + + 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 note_array_index_out_of_bounds : 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< + "format specifies type %0 but the argument has " + "%select{type|underlying type}2 %1">, + InGroup; + 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< + "%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, 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 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_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 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_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|%2}1">, + InGroup; + def warn_comparison_bitwise_always : Warning< + "bitwise comparison always evaluates to %select{false|true}0">, + InGroup; + def warn_tautological_overlap_comparison : Warning< + "overlapping comparisons always evaluate to %select{false|true}0">, + InGroup, DefaultIgnore; + + def warn_stringcompare : Warning< + "result of comparison against %select{a string literal|@encode}0 is " + "unspecified (use strncmp 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_fallthrough_attr_unreachable : Warning< + "fallthrough annotation in unreachable code">, + InGroup, DefaultIgnore; + + 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_noreturn_missing_on_first_decl : Error< + "function declared '[[noreturn]]' after its first declaration">; + def note_noreturn_missing_first_decl : Note< + "declaration missing '[[noreturn]]' attribute is here">; + 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_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 err_argument_not_multiple : Error< + "argument should be a multiple of %0">; + 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_ppc_builtin_only_on_pwr7 : Error< + "this builtin is only valid on POWER7 or later CPUs">; + 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_hexagon_builtin_unsupported_cpu : Error< + "builtin is not supported on this CPU">; + def err_hexagon_builtin_requires_hvx : Error< + "builtin requires HVX">; + def err_hexagon_builtin_unsupported_hvx : Error< + "builtin is not supported on this version of HVX">; + + 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 l-value 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 parameters">, + 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_invalid_sign_spec : Extension<"'%0' cannot be signed or unsigned">; + 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 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 type should be an integral value not %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 warn_opencl_attr_deprecated_ignored : Warning < + "%0 attribute is deprecated and ignored in OpenCL version %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 extension to be enabled">; + 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 version 2.0}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_arg_num : Error< + "invalid number of arguments to function: %0">; + 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 v2.2 s2.1.2.3 - Vector Component Access + def ext_opencl_ext_vector_type_rgba_selector: ExtWarn< + "vector component name '%0' is an OpenCL version 2.2 feature">, + 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 or array section">; + 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_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_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 note_omp_default_dsa_none : Note< + "explicit data sharing attribute 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_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_multiple : Error< + "%0 appears multiple times in clauses on the same declare target directive">; + 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_aligned_twice : Error< + "%select{a variable|a parameter|'this'}0 cannot appear in more than one aligned 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 " + "('<', '<=', '>', or '>=') of loop variable %0">; + 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_in_reduction_not_task_reduction : Error< + "in_reduction variable must appear in a task_reduction clause">; + 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?}2">; + def err_omp_prohibited_region_simd : Error< + "OpenMP constructs may not be nested inside a simd region">; + 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_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 l-value 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 l-value 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 l-value 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 l-value 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 note_omp_atomic_previous_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 : Error< + "single declaration is expected after 'declare simd' directive">; + def err_omp_function_expected : Error< + "'#pragma omp declare simd' 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_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_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_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 with specified parameter">; + 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_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_grainsize_num_tasks_mutually_exclusive : Error< + "'%0' and '%1' clause are mutually exclusive and may not appear on the same directive">; + def note_omp_previous_grainsize_num_tasks : 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_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_schedule_nonmonotonic_ordered : Error< + "'schedule' clause with 'nonmonotonic' 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 }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< + "Non-trivial type %0 is mapped, only trivial types are 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_target_before_requires : Error < + "target region encountered before requires directive with '%0' clause">; + def note_omp_requires_encountered_target : Note < + "target 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_implied_omp_allocator_handle_t_not_found : Error< + "omp_allocator_handle_t type not found; include ">; + 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_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_omp_unsupported_type : Error < + "host requires %0 bit size %1 type support, but device '%2' does not support it">; + } // 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< + "missing '#include %3'; " + "%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_global_module_fragment : 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 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'" + >; + } + + 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_no_other_attrs : Error< + "attribute '%select{target|cpu_specific|cpu_dispatch}0' multiversioning cannot be combined" + " with other attributes">; + def err_multiversion_diff : Error< + "multiversioned function declaration has a different %select{calling convention" + "|return type|constexpr specification|inline specification|storage class|" + "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 deduce return type of 'operator<=>' 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">; + + // 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 err_memtag_arg_must_be_unsigned : Error< + "%0 argument of MTE builtin function must be an unsigned 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_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)">; + } // end of sema component. +diff --git a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp +index 35d11f4e2d3..de57bd9fe56 100644 +--- a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp ++++ b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp +@@ -1,429 +1,429 @@ + //===--- AArch64.cpp - AArch64 (not ARM) Helpers for Tools ------*- C++ -*-===// + // + // 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 + // + //===----------------------------------------------------------------------===// + + #include "AArch64.h" + #include "clang/Driver/Driver.h" + #include "clang/Driver/DriverDiagnostic.h" + #include "clang/Driver/Options.h" + #include "llvm/Option/ArgList.h" + #include "llvm/Support/TargetParser.h" + + using namespace clang::driver; + using namespace clang::driver::tools; + using namespace clang; + using namespace llvm::opt; + + /// \returns true if the given triple can determine the default CPU type even + /// if -arch is not specified. + static bool isCPUDeterminedByTriple(const llvm::Triple &Triple) { + return Triple.isOSDarwin(); + } + + /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are + /// targeting. Set \p A to the Arg corresponding to the -mcpu argument if it is + /// provided, or to nullptr otherwise. + std::string aarch64::getAArch64TargetCPU(const ArgList &Args, + const llvm::Triple &Triple, Arg *&A) { + std::string CPU; + // If we have -mcpu, use that. + if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) { + StringRef Mcpu = A->getValue(); + CPU = Mcpu.split("+").first.lower(); + } + + // Handle CPU name is 'native'. + if (CPU == "native") + return llvm::sys::getHostCPUName(); + else if (CPU.size()) + return CPU; + + // Make sure we pick "cyclone" if -arch is used or when targetting a Darwin + // OS. + if (Args.getLastArg(options::OPT_arch) || Triple.isOSDarwin()) + return "cyclone"; + + return "generic"; + } + + // Decode AArch64 features from string like +[no]featureA+[no]featureB+... + static bool DecodeAArch64Features(const Driver &D, StringRef text, + std::vector &Features) { + SmallVector Split; + text.split(Split, StringRef("+"), -1, false); + + for (StringRef Feature : Split) { + StringRef FeatureName = llvm::AArch64::getArchExtFeature(Feature); + if (!FeatureName.empty()) + Features.push_back(FeatureName); + else if (Feature == "neon" || Feature == "noneon") + D.Diag(clang::diag::err_drv_no_neon_modifier); + else + return false; + } + return true; + } + + // Check if the CPU name and feature modifiers in -mcpu are legal. If yes, + // decode CPU and feature. + static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU, + std::vector &Features) { + std::pair Split = Mcpu.split("+"); + CPU = Split.first; + + if (CPU == "native") + CPU = llvm::sys::getHostCPUName(); + + if (CPU == "generic") { + Features.push_back("+neon"); + } else { + llvm::AArch64::ArchKind ArchKind = llvm::AArch64::parseCPUArch(CPU); + if (!llvm::AArch64::getArchFeatures(ArchKind, Features)) + return false; + + unsigned Extension = llvm::AArch64::getDefaultExtensions(CPU, ArchKind); + if (!llvm::AArch64::getExtensionFeatures(Extension, Features)) + return false; +- } ++ } + + if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features)) + return false; + + return true; + } + + static bool + getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March, + const ArgList &Args, + std::vector &Features) { + std::string MarchLowerCase = March.lower(); + std::pair Split = StringRef(MarchLowerCase).split("+"); + + llvm::AArch64::ArchKind ArchKind = llvm::AArch64::parseArch(Split.first); + if (ArchKind == llvm::AArch64::ArchKind::INVALID || + !llvm::AArch64::getArchFeatures(ArchKind, Features) || + (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))) + return false; + + return true; + } + + static bool + getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu, + const ArgList &Args, + std::vector &Features) { + StringRef CPU; + std::string McpuLowerCase = Mcpu.lower(); + if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features)) + return false; + + return true; + } + + static bool + getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune, + const ArgList &Args, + std::vector &Features) { + std::string MtuneLowerCase = Mtune.lower(); + // Check CPU name is valid + std::vector MtuneFeatures; + StringRef Tune; + if (!DecodeAArch64Mcpu(D, MtuneLowerCase, Tune, MtuneFeatures)) + return false; + + // Handle CPU name is 'native'. + if (MtuneLowerCase == "native") + MtuneLowerCase = llvm::sys::getHostCPUName(); + if (MtuneLowerCase == "cyclone") { + Features.push_back("+zcm"); + Features.push_back("+zcz"); + } + return true; + } + + static bool + getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu, + const ArgList &Args, + std::vector &Features) { + StringRef CPU; + std::vector DecodedFeature; + std::string McpuLowerCase = Mcpu.lower(); + if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature)) + return false; + + return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features); + } + + void aarch64::getAArch64TargetFeatures(const Driver &D, + const llvm::Triple &Triple, + const ArgList &Args, + std::vector &Features) { + Arg *A; + bool success = true; + // Enable NEON by default. + Features.push_back("+neon"); + if ((A = Args.getLastArg(options::OPT_march_EQ))) + success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features); + else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) + success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features); + else if (Args.hasArg(options::OPT_arch) || isCPUDeterminedByTriple(Triple)) + success = getAArch64ArchFeaturesFromMcpu( + D, getAArch64TargetCPU(Args, Triple, A), Args, Features); + + if (success && (A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ))) + success = + getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features); + else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ))) + success = + getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features); + else if (success && + (Args.hasArg(options::OPT_arch) || isCPUDeterminedByTriple(Triple))) + success = getAArch64MicroArchFeaturesFromMcpu( + D, getAArch64TargetCPU(Args, Triple, A), Args, Features); + + if (!success) + D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args); + + if (Args.getLastArg(options::OPT_mgeneral_regs_only)) { + Features.push_back("-fp-armv8"); + Features.push_back("-crypto"); + Features.push_back("-neon"); + } + + if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) { + StringRef Mtp = A->getValue(); + if (Mtp == "el3") + Features.push_back("+tpidr-el3"); + else if (Mtp == "el2") + Features.push_back("+tpidr-el2"); + else if (Mtp == "el1") + Features.push_back("+tpidr-el1"); + else if (Mtp != "el0") + D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args); + } + + // En/disable crc + if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) { + if (A->getOption().matches(options::OPT_mcrc)) + Features.push_back("+crc"); + else + Features.push_back("-crc"); + } + + // Handle (arch-dependent) fp16fml/fullfp16 relationship. + // FIXME: this fp16fml option handling will be reimplemented after the + // TargetParser rewrite. + const auto ItRNoFullFP16 = std::find(Features.rbegin(), Features.rend(), "-fullfp16"); + const auto ItRFP16FML = std::find(Features.rbegin(), Features.rend(), "+fp16fml"); + if (llvm::is_contained(Features, "+v8.4a")) { + const auto ItRFullFP16 = std::find(Features.rbegin(), Features.rend(), "+fullfp16"); + if (ItRFullFP16 < ItRNoFullFP16 && ItRFullFP16 < ItRFP16FML) { + // Only entangled feature that can be to the right of this +fullfp16 is -fp16fml. + // Only append the +fp16fml if there is no -fp16fml after the +fullfp16. + if (std::find(Features.rbegin(), ItRFullFP16, "-fp16fml") == ItRFullFP16) + Features.push_back("+fp16fml"); + } + else + goto fp16_fml_fallthrough; + } else { + fp16_fml_fallthrough: + // In both of these cases, putting the 'other' feature on the end of the vector will + // result in the same effect as placing it immediately after the current feature. + if (ItRNoFullFP16 < ItRFP16FML) + Features.push_back("-fp16fml"); + else if (ItRNoFullFP16 > ItRFP16FML) + Features.push_back("+fullfp16"); + } + + // FIXME: this needs reimplementation too after the TargetParser rewrite + // + // Context sensitive meaning of Crypto: + // 1) For Arch >= ARMv8.4a: crypto = sm4 + sha3 + sha2 + aes + // 2) For Arch <= ARMv8.3a: crypto = sha2 + aes + const auto ItBegin = Features.begin(); + const auto ItEnd = Features.end(); + const auto ItRBegin = Features.rbegin(); + const auto ItREnd = Features.rend(); + const auto ItRCrypto = std::find(ItRBegin, ItREnd, "+crypto"); + const auto ItRNoCrypto = std::find(ItRBegin, ItREnd, "-crypto"); + const auto HasCrypto = ItRCrypto != ItREnd; + const auto HasNoCrypto = ItRNoCrypto != ItREnd; + const ptrdiff_t PosCrypto = ItRCrypto - ItRBegin; + const ptrdiff_t PosNoCrypto = ItRNoCrypto - ItRBegin; + + bool NoCrypto = false; + if (HasCrypto && HasNoCrypto) { + if (PosNoCrypto < PosCrypto) + NoCrypto = true; + } + + if (std::find(ItBegin, ItEnd, "+v8.4a") != ItEnd) { + if (HasCrypto && !NoCrypto) { + // Check if we have NOT disabled an algorithm with something like: + // +crypto, -algorithm + // And if "-algorithm" does not occur, we enable that crypto algorithm. + const bool HasSM4 = (std::find(ItBegin, ItEnd, "-sm4") == ItEnd); + const bool HasSHA3 = (std::find(ItBegin, ItEnd, "-sha3") == ItEnd); + const bool HasSHA2 = (std::find(ItBegin, ItEnd, "-sha2") == ItEnd); + const bool HasAES = (std::find(ItBegin, ItEnd, "-aes") == ItEnd); + if (HasSM4) + Features.push_back("+sm4"); + if (HasSHA3) + Features.push_back("+sha3"); + if (HasSHA2) + Features.push_back("+sha2"); + if (HasAES) + Features.push_back("+aes"); + } else if (HasNoCrypto) { + // Check if we have NOT enabled a crypto algorithm with something like: + // -crypto, +algorithm + // And if "+algorithm" does not occur, we disable that crypto algorithm. + const bool HasSM4 = (std::find(ItBegin, ItEnd, "+sm4") != ItEnd); + const bool HasSHA3 = (std::find(ItBegin, ItEnd, "+sha3") != ItEnd); + const bool HasSHA2 = (std::find(ItBegin, ItEnd, "+sha2") != ItEnd); + const bool HasAES = (std::find(ItBegin, ItEnd, "+aes") != ItEnd); + if (!HasSM4) + Features.push_back("-sm4"); + if (!HasSHA3) + Features.push_back("-sha3"); + if (!HasSHA2) + Features.push_back("-sha2"); + if (!HasAES) + Features.push_back("-aes"); + } + } else { + if (HasCrypto && !NoCrypto) { + const bool HasSHA2 = (std::find(ItBegin, ItEnd, "-sha2") == ItEnd); + const bool HasAES = (std::find(ItBegin, ItEnd, "-aes") == ItEnd); + if (HasSHA2) + Features.push_back("+sha2"); + if (HasAES) + Features.push_back("+aes"); + } else if (HasNoCrypto) { + const bool HasSHA2 = (std::find(ItBegin, ItEnd, "+sha2") != ItEnd); + const bool HasAES = (std::find(ItBegin, ItEnd, "+aes") != ItEnd); + const bool HasV82a = (std::find(ItBegin, ItEnd, "+v8.2a") != ItEnd); + const bool HasV83a = (std::find(ItBegin, ItEnd, "+v8.3a") != ItEnd); + const bool HasV84a = (std::find(ItBegin, ItEnd, "+v8.4a") != ItEnd); + if (!HasSHA2) + Features.push_back("-sha2"); + if (!HasAES) + Features.push_back("-aes"); + if (HasV82a || HasV83a || HasV84a) { + Features.push_back("-sm4"); + Features.push_back("-sha3"); + } + } + } + + if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access, + options::OPT_munaligned_access)) + if (A->getOption().matches(options::OPT_mno_unaligned_access)) + Features.push_back("+strict-align"); + + if (Args.hasArg(options::OPT_ffixed_x1)) + Features.push_back("+reserve-x1"); + + if (Args.hasArg(options::OPT_ffixed_x2)) + Features.push_back("+reserve-x2"); + + if (Args.hasArg(options::OPT_ffixed_x3)) + Features.push_back("+reserve-x3"); + + if (Args.hasArg(options::OPT_ffixed_x4)) + Features.push_back("+reserve-x4"); + + if (Args.hasArg(options::OPT_ffixed_x5)) + Features.push_back("+reserve-x5"); + + if (Args.hasArg(options::OPT_ffixed_x6)) + Features.push_back("+reserve-x6"); + + if (Args.hasArg(options::OPT_ffixed_x7)) + Features.push_back("+reserve-x7"); + + if (Args.hasArg(options::OPT_ffixed_x9)) + Features.push_back("+reserve-x9"); + + if (Args.hasArg(options::OPT_ffixed_x10)) + Features.push_back("+reserve-x10"); + + if (Args.hasArg(options::OPT_ffixed_x11)) + Features.push_back("+reserve-x11"); + + if (Args.hasArg(options::OPT_ffixed_x12)) + Features.push_back("+reserve-x12"); + + if (Args.hasArg(options::OPT_ffixed_x13)) + Features.push_back("+reserve-x13"); + + if (Args.hasArg(options::OPT_ffixed_x14)) + Features.push_back("+reserve-x14"); + + if (Args.hasArg(options::OPT_ffixed_x15)) + Features.push_back("+reserve-x15"); + + if (Args.hasArg(options::OPT_ffixed_x18)) + Features.push_back("+reserve-x18"); + + if (Args.hasArg(options::OPT_ffixed_x20)) + Features.push_back("+reserve-x20"); + + if (Args.hasArg(options::OPT_ffixed_x21)) + Features.push_back("+reserve-x21"); + + if (Args.hasArg(options::OPT_ffixed_x22)) + Features.push_back("+reserve-x22"); + + if (Args.hasArg(options::OPT_ffixed_x23)) + Features.push_back("+reserve-x23"); + + if (Args.hasArg(options::OPT_ffixed_x24)) + Features.push_back("+reserve-x24"); + + if (Args.hasArg(options::OPT_ffixed_x25)) + Features.push_back("+reserve-x25"); + + if (Args.hasArg(options::OPT_ffixed_x26)) + Features.push_back("+reserve-x26"); + + if (Args.hasArg(options::OPT_ffixed_x27)) + Features.push_back("+reserve-x27"); + + if (Args.hasArg(options::OPT_ffixed_x28)) + Features.push_back("+reserve-x28"); + + if (Args.hasArg(options::OPT_fcall_saved_x8)) + Features.push_back("+call-saved-x8"); + + if (Args.hasArg(options::OPT_fcall_saved_x9)) + Features.push_back("+call-saved-x9"); + + if (Args.hasArg(options::OPT_fcall_saved_x10)) + Features.push_back("+call-saved-x10"); + + if (Args.hasArg(options::OPT_fcall_saved_x11)) + Features.push_back("+call-saved-x11"); + + if (Args.hasArg(options::OPT_fcall_saved_x12)) + Features.push_back("+call-saved-x12"); + + if (Args.hasArg(options::OPT_fcall_saved_x13)) + Features.push_back("+call-saved-x13"); + + if (Args.hasArg(options::OPT_fcall_saved_x14)) + Features.push_back("+call-saved-x14"); + + if (Args.hasArg(options::OPT_fcall_saved_x15)) + Features.push_back("+call-saved-x15"); + + if (Args.hasArg(options::OPT_fcall_saved_x18)) + Features.push_back("+call-saved-x18"); + + if (Args.hasArg(options::OPT_mno_neg_immediates)) + Features.push_back("+no-neg-immediates"); + } +diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp +index 1c3d12ea098..b57373731d6 100644 +--- a/clang/lib/Sema/SemaChecking.cpp ++++ b/clang/lib/Sema/SemaChecking.cpp +@@ -1,14326 +1,14379 @@ + //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// + // + // 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 + // + //===----------------------------------------------------------------------===// + // + // This file implements extra semantic analysis beyond what is enforced + // by the C type system. + // + //===----------------------------------------------------------------------===// + + #include "clang/AST/APValue.h" + #include "clang/AST/ASTContext.h" + #include "clang/AST/Attr.h" + #include "clang/AST/AttrIterator.h" + #include "clang/AST/CharUnits.h" + #include "clang/AST/Decl.h" + #include "clang/AST/DeclBase.h" + #include "clang/AST/DeclCXX.h" + #include "clang/AST/DeclObjC.h" + #include "clang/AST/DeclarationName.h" + #include "clang/AST/EvaluatedExprVisitor.h" + #include "clang/AST/Expr.h" + #include "clang/AST/ExprCXX.h" + #include "clang/AST/ExprObjC.h" + #include "clang/AST/ExprOpenMP.h" + #include "clang/AST/FormatString.h" + #include "clang/AST/NSAPI.h" + #include "clang/AST/NonTrivialTypeVisitor.h" + #include "clang/AST/OperationKinds.h" + #include "clang/AST/Stmt.h" + #include "clang/AST/TemplateBase.h" + #include "clang/AST/Type.h" + #include "clang/AST/TypeLoc.h" + #include "clang/AST/UnresolvedSet.h" + #include "clang/Basic/AddressSpaces.h" + #include "clang/Basic/CharInfo.h" + #include "clang/Basic/Diagnostic.h" + #include "clang/Basic/IdentifierTable.h" + #include "clang/Basic/LLVM.h" + #include "clang/Basic/LangOptions.h" + #include "clang/Basic/OpenCLOptions.h" + #include "clang/Basic/OperatorKinds.h" + #include "clang/Basic/PartialDiagnostic.h" + #include "clang/Basic/SourceLocation.h" + #include "clang/Basic/SourceManager.h" + #include "clang/Basic/Specifiers.h" + #include "clang/Basic/SyncScope.h" + #include "clang/Basic/TargetBuiltins.h" + #include "clang/Basic/TargetCXXABI.h" + #include "clang/Basic/TargetInfo.h" + #include "clang/Basic/TypeTraits.h" + #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. + #include "clang/Sema/Initialization.h" + #include "clang/Sema/Lookup.h" + #include "clang/Sema/Ownership.h" + #include "clang/Sema/Scope.h" + #include "clang/Sema/ScopeInfo.h" + #include "clang/Sema/Sema.h" + #include "clang/Sema/SemaInternal.h" + #include "llvm/ADT/APFloat.h" + #include "llvm/ADT/APInt.h" + #include "llvm/ADT/APSInt.h" + #include "llvm/ADT/ArrayRef.h" + #include "llvm/ADT/DenseMap.h" + #include "llvm/ADT/FoldingSet.h" + #include "llvm/ADT/None.h" + #include "llvm/ADT/Optional.h" + #include "llvm/ADT/STLExtras.h" + #include "llvm/ADT/SmallBitVector.h" + #include "llvm/ADT/SmallPtrSet.h" + #include "llvm/ADT/SmallString.h" + #include "llvm/ADT/SmallVector.h" + #include "llvm/ADT/StringRef.h" + #include "llvm/ADT/StringSwitch.h" + #include "llvm/ADT/Triple.h" + #include "llvm/Support/AtomicOrdering.h" + #include "llvm/Support/Casting.h" + #include "llvm/Support/Compiler.h" + #include "llvm/Support/ConvertUTF.h" + #include "llvm/Support/ErrorHandling.h" + #include "llvm/Support/Format.h" + #include "llvm/Support/Locale.h" + #include "llvm/Support/MathExtras.h" + #include "llvm/Support/SaveAndRestore.h" + #include "llvm/Support/raw_ostream.h" + #include + #include + #include + #include + #include + #include + #include + #include + #include + ++namespace llvm { ++ ++ struct fltSemantics; ++}; ++ + using namespace clang; + using namespace sema; + + SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, + unsigned ByteNo) const { + return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, + Context.getTargetInfo()); + } + + /// Checks that a call expression's argument count is the desired number. + /// This is useful when doing custom type-checking. Returns true on error. + static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { + unsigned argCount = call->getNumArgs(); + if (argCount == desiredArgCount) return false; + + if (argCount < desiredArgCount) + return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) + << 0 /*function call*/ << desiredArgCount << argCount + << call->getSourceRange(); + + // Highlight all the excess arguments. + SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), + call->getArg(argCount - 1)->getEndLoc()); + + return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) + << 0 /*function call*/ << desiredArgCount << argCount + << call->getArg(1)->getSourceRange(); + } + + /// Check that the first argument to __builtin_annotation is an integer + /// and the second argument is a non-wide string literal. + static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { + if (checkArgCount(S, TheCall, 2)) + return true; + + // First argument should be an integer. + Expr *ValArg = TheCall->getArg(0); + QualType Ty = ValArg->getType(); + if (!Ty->isIntegerType()) { + S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) + << ValArg->getSourceRange(); + return true; + } + + // Second argument should be a constant string. + Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); + StringLiteral *Literal = dyn_cast(StrArg); + if (!Literal || !Literal->isAscii()) { + S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) + << StrArg->getSourceRange(); + return true; + } + + TheCall->setType(Ty); + return false; + } + + static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { + // We need at least one argument. + if (TheCall->getNumArgs() < 1) { + S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) + << 0 << 1 << TheCall->getNumArgs() + << TheCall->getCallee()->getSourceRange(); + return true; + } + + // All arguments should be wide string literals. + for (Expr *Arg : TheCall->arguments()) { + auto *Literal = dyn_cast(Arg->IgnoreParenCasts()); + if (!Literal || !Literal->isWide()) { + S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) + << Arg->getSourceRange(); + return true; + } + } + + return false; + } + + /// Check that the argument to __builtin_addressof is a glvalue, and set the + /// result type to the corresponding pointer type. + static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { + if (checkArgCount(S, TheCall, 1)) + return true; + + ExprResult Arg(TheCall->getArg(0)); + QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); + if (ResultType.isNull()) + return true; + + TheCall->setArg(0, Arg.get()); + TheCall->setType(ResultType); + return false; + } + + /// Check the number of arguments, and set the result type to + /// the argument type. + static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { + if (checkArgCount(S, TheCall, 1)) + return true; + + TheCall->setType(TheCall->getArg(0)->getType()); + return false; + } + + static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { + if (checkArgCount(S, TheCall, 3)) + return true; + + // First two arguments should be integers. + for (unsigned I = 0; I < 2; ++I) { + ExprResult Arg = TheCall->getArg(I); + QualType Ty = Arg.get()->getType(); + if (!Ty->isIntegerType()) { + S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) + << Ty << Arg.get()->getSourceRange(); + return true; + } + InitializedEntity Entity = InitializedEntity::InitializeParameter( + S.getASTContext(), Ty, /*consume*/ false); + Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); + if (Arg.isInvalid()) + return true; + TheCall->setArg(I, Arg.get()); + } + + // Third argument should be a pointer to a non-const integer. + // IRGen correctly handles volatile, restrict, and address spaces, and + // the other qualifiers aren't possible. + { + ExprResult Arg = TheCall->getArg(2); + QualType Ty = Arg.get()->getType(); + const auto *PtrTy = Ty->getAs(); + if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && + !PtrTy->getPointeeType().isConstQualified())) { + S.Diag(Arg.get()->getBeginLoc(), + diag::err_overflow_builtin_must_be_ptr_int) + << Ty << Arg.get()->getSourceRange(); + return true; + } + InitializedEntity Entity = InitializedEntity::InitializeParameter( + S.getASTContext(), Ty, /*consume*/ false); + Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); + if (Arg.isInvalid()) + return true; + TheCall->setArg(2, Arg.get()); + } + return false; + } + + static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { + if (checkArgCount(S, BuiltinCall, 2)) + return true; + + SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); + Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); + Expr *Call = BuiltinCall->getArg(0); + Expr *Chain = BuiltinCall->getArg(1); + + if (Call->getStmtClass() != Stmt::CallExprClass) { + S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) + << Call->getSourceRange(); + return true; + } + + auto CE = cast(Call); + if (CE->getCallee()->getType()->isBlockPointerType()) { + S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) + << Call->getSourceRange(); + return true; + } + + const Decl *TargetDecl = CE->getCalleeDecl(); + if (const FunctionDecl *FD = dyn_cast_or_null(TargetDecl)) + if (FD->getBuiltinID()) { + S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) + << Call->getSourceRange(); + return true; + } + + if (isa(CE->getCallee()->IgnoreParens())) { + S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) + << Call->getSourceRange(); + return true; + } + + ExprResult ChainResult = S.UsualUnaryConversions(Chain); + if (ChainResult.isInvalid()) + return true; + if (!ChainResult.get()->getType()->isPointerType()) { + S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) + << Chain->getSourceRange(); + return true; + } + + QualType ReturnTy = CE->getCallReturnType(S.Context); + QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; + QualType BuiltinTy = S.Context.getFunctionType( + ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); + QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); + + Builtin = + S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); + + BuiltinCall->setType(CE->getType()); + BuiltinCall->setValueKind(CE->getValueKind()); + BuiltinCall->setObjectKind(CE->getObjectKind()); + BuiltinCall->setCallee(Builtin); + BuiltinCall->setArg(1, ChainResult.get()); + + return false; + } + + /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a + /// __builtin_*_chk function, then use the object size argument specified in the + /// source. Otherwise, infer the object size using __builtin_object_size. + void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, + CallExpr *TheCall) { + // FIXME: There are some more useful checks we could be doing here: + // - Analyze the format string of sprintf to see how much of buffer is used. + // - Evaluate strlen of strcpy arguments, use as object size. + + if (TheCall->isValueDependent() || TheCall->isTypeDependent() || + isConstantEvaluated()) + return; + + unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); + if (!BuiltinID) + return; + + unsigned DiagID = 0; + bool IsChkVariant = false; + unsigned SizeIndex, ObjectIndex; + switch (BuiltinID) { + default: + return; + case Builtin::BI__builtin___memcpy_chk: + case Builtin::BI__builtin___memmove_chk: + case Builtin::BI__builtin___memset_chk: + case Builtin::BI__builtin___strlcat_chk: + case Builtin::BI__builtin___strlcpy_chk: + case Builtin::BI__builtin___strncat_chk: + case Builtin::BI__builtin___strncpy_chk: + case Builtin::BI__builtin___stpncpy_chk: + case Builtin::BI__builtin___memccpy_chk: { + DiagID = diag::warn_builtin_chk_overflow; + IsChkVariant = true; + SizeIndex = TheCall->getNumArgs() - 2; + ObjectIndex = TheCall->getNumArgs() - 1; + break; + } + + case Builtin::BI__builtin___snprintf_chk: + case Builtin::BI__builtin___vsnprintf_chk: { + DiagID = diag::warn_builtin_chk_overflow; + IsChkVariant = true; + SizeIndex = 1; + ObjectIndex = 3; + break; + } + + case Builtin::BIstrncat: + case Builtin::BI__builtin_strncat: + case Builtin::BIstrncpy: + case Builtin::BI__builtin_strncpy: + case Builtin::BIstpncpy: + case Builtin::BI__builtin_stpncpy: { + // Whether these functions overflow depends on the runtime strlen of the + // string, not just the buffer size, so emitting the "always overflow" + // diagnostic isn't quite right. We should still diagnose passing a buffer + // size larger than the destination buffer though; this is a runtime abort + // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. + DiagID = diag::warn_fortify_source_size_mismatch; + SizeIndex = TheCall->getNumArgs() - 1; + ObjectIndex = 0; + break; + } + + case Builtin::BImemcpy: + case Builtin::BI__builtin_memcpy: + case Builtin::BImemmove: + case Builtin::BI__builtin_memmove: + case Builtin::BImemset: + case Builtin::BI__builtin_memset: { + DiagID = diag::warn_fortify_source_overflow; + SizeIndex = TheCall->getNumArgs() - 1; + ObjectIndex = 0; + break; + } + case Builtin::BIsnprintf: + case Builtin::BI__builtin_snprintf: + case Builtin::BIvsnprintf: + case Builtin::BI__builtin_vsnprintf: { + DiagID = diag::warn_fortify_source_size_mismatch; + SizeIndex = 1; + ObjectIndex = 0; + break; + } + } + + llvm::APSInt ObjectSize; + // For __builtin___*_chk, the object size is explicitly provided by the caller + // (usually using __builtin_object_size). Use that value to check this call. + if (IsChkVariant) { + Expr::EvalResult Result; + Expr *SizeArg = TheCall->getArg(ObjectIndex); + if (!SizeArg->EvaluateAsInt(Result, getASTContext())) + return; + ObjectSize = Result.Val.getInt(); + + // Otherwise, try to evaluate an imaginary call to __builtin_object_size. + } else { + // If the parameter has a pass_object_size attribute, then we should use its + // (potentially) more strict checking mode. Otherwise, conservatively assume + // type 0. + int BOSType = 0; + if (const auto *POS = + FD->getParamDecl(ObjectIndex)->getAttr()) + BOSType = POS->getType(); + + Expr *ObjArg = TheCall->getArg(ObjectIndex); + uint64_t Result; + if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) + return; + // Get the object size in the target's size_t width. + const TargetInfo &TI = getASTContext().getTargetInfo(); + unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); + ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); + } + + // Evaluate the number of bytes of the object that this call will use. + Expr::EvalResult Result; + Expr *UsedSizeArg = TheCall->getArg(SizeIndex); + if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) + return; + llvm::APSInt UsedSize = Result.Val.getInt(); + + if (UsedSize.ule(ObjectSize)) + return; + + StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); + // Skim off the details of whichever builtin was called to produce a better + // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. + if (IsChkVariant) { + FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); + FunctionName = FunctionName.drop_back(std::strlen("_chk")); + } else if (FunctionName.startswith("__builtin_")) { + FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); + } + + DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, + PDiag(DiagID) + << FunctionName << ObjectSize.toString(/*Radix=*/10) + << UsedSize.toString(/*Radix=*/10)); + } + + static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, + Scope::ScopeFlags NeededScopeFlags, + unsigned DiagID) { + // Scopes aren't available during instantiation. Fortunately, builtin + // functions cannot be template args so they cannot be formed through template + // instantiation. Therefore checking once during the parse is sufficient. + if (SemaRef.inTemplateInstantiation()) + return false; + + Scope *S = SemaRef.getCurScope(); + while (S && !S->isSEHExceptScope()) + S = S->getParent(); + if (!S || !(S->getFlags() & NeededScopeFlags)) { + auto *DRE = cast(TheCall->getCallee()->IgnoreParenCasts()); + SemaRef.Diag(TheCall->getExprLoc(), DiagID) + << DRE->getDecl()->getIdentifier(); + return true; + } + + return false; + } + + static inline bool isBlockPointer(Expr *Arg) { + return Arg->getType()->isBlockPointerType(); + } + + /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local + /// void*, which is a requirement of device side enqueue. + static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { + const BlockPointerType *BPT = + cast(BlockArg->getType().getCanonicalType()); + ArrayRef Params = + BPT->getPointeeType()->getAs()->getParamTypes(); + unsigned ArgCounter = 0; + bool IllegalParams = false; + // Iterate through the block parameters until either one is found that is not + // a local void*, or the block is valid. + for (ArrayRef::iterator I = Params.begin(), E = Params.end(); + I != E; ++I, ++ArgCounter) { + if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || + (*I)->getPointeeType().getQualifiers().getAddressSpace() != + LangAS::opencl_local) { + // Get the location of the error. If a block literal has been passed + // (BlockExpr) then we can point straight to the offending argument, + // else we just point to the variable reference. + SourceLocation ErrorLoc; + if (isa(BlockArg)) { + BlockDecl *BD = cast(BlockArg)->getBlockDecl(); + ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); + } else if (isa(BlockArg)) { + ErrorLoc = cast(BlockArg)->getBeginLoc(); + } + S.Diag(ErrorLoc, + diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); + IllegalParams = true; + } + } + + return IllegalParams; + } + + static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { + if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { + S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) + << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; + return true; + } + return false; + } + + static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { + if (checkArgCount(S, TheCall, 2)) + return true; + + if (checkOpenCLSubgroupExt(S, TheCall)) + return true; + + // First argument is an ndrange_t type. + Expr *NDRangeArg = TheCall->getArg(0); + if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { + S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) + << TheCall->getDirectCallee() << "'ndrange_t'"; + return true; + } + + Expr *BlockArg = TheCall->getArg(1); + if (!isBlockPointer(BlockArg)) { + S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) + << TheCall->getDirectCallee() << "block"; + return true; + } + return checkOpenCLBlockArgs(S, BlockArg); + } + + /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the + /// get_kernel_work_group_size + /// and get_kernel_preferred_work_group_size_multiple builtin functions. + static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { + if (checkArgCount(S, TheCall, 1)) + return true; + + Expr *BlockArg = TheCall->getArg(0); + if (!isBlockPointer(BlockArg)) { + S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) + << TheCall->getDirectCallee() << "block"; + return true; + } + return checkOpenCLBlockArgs(S, BlockArg); + } + + /// Diagnose integer type and any valid implicit conversion to it. + static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, + const QualType &IntType); + + static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, + unsigned Start, unsigned End) { + bool IllegalParams = false; + for (unsigned I = Start; I <= End; ++I) + IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), + S.Context.getSizeType()); + return IllegalParams; + } + + /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all + /// 'local void*' parameter of passed block. + static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, + Expr *BlockArg, + unsigned NumNonVarArgs) { + const BlockPointerType *BPT = + cast(BlockArg->getType().getCanonicalType()); + unsigned NumBlockParams = + BPT->getPointeeType()->getAs()->getNumParams(); + unsigned TotalNumArgs = TheCall->getNumArgs(); + + // For each argument passed to the block, a corresponding uint needs to + // be passed to describe the size of the local memory. + if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { + S.Diag(TheCall->getBeginLoc(), + diag::err_opencl_enqueue_kernel_local_size_args); + return true; + } + + // Check that the sizes of the local memory are specified by integers. + return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, + TotalNumArgs - 1); + } + + /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different + /// overload formats specified in Table 6.13.17.1. + /// int enqueue_kernel(queue_t queue, + /// kernel_enqueue_flags_t flags, + /// const ndrange_t ndrange, + /// void (^block)(void)) + /// int enqueue_kernel(queue_t queue, + /// kernel_enqueue_flags_t flags, + /// const ndrange_t ndrange, + /// uint num_events_in_wait_list, + /// clk_event_t *event_wait_list, + /// clk_event_t *event_ret, + /// void (^block)(void)) + /// int enqueue_kernel(queue_t queue, + /// kernel_enqueue_flags_t flags, + /// const ndrange_t ndrange, + /// void (^block)(local void*, ...), + /// uint size0, ...) + /// int enqueue_kernel(queue_t queue, + /// kernel_enqueue_flags_t flags, + /// const ndrange_t ndrange, + /// uint num_events_in_wait_list, + /// clk_event_t *event_wait_list, + /// clk_event_t *event_ret, + /// void (^block)(local void*, ...), + /// uint size0, ...) + static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { + unsigned NumArgs = TheCall->getNumArgs(); + + if (NumArgs < 4) { + S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args); + return true; + } + + Expr *Arg0 = TheCall->getArg(0); + Expr *Arg1 = TheCall->getArg(1); + Expr *Arg2 = TheCall->getArg(2); + Expr *Arg3 = TheCall->getArg(3); + + // First argument always needs to be a queue_t type. + if (!Arg0->getType()->isQueueT()) { + S.Diag(TheCall->getArg(0)->getBeginLoc(), + diag::err_opencl_builtin_expected_type) + << TheCall->getDirectCallee() << S.Context.OCLQueueTy; + return true; + } + + // Second argument always needs to be a kernel_enqueue_flags_t enum value. + if (!Arg1->getType()->isIntegerType()) { + S.Diag(TheCall->getArg(1)->getBeginLoc(), + diag::err_opencl_builtin_expected_type) + << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; + return true; + } + + // Third argument is always an ndrange_t type. + if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { + S.Diag(TheCall->getArg(2)->getBeginLoc(), + diag::err_opencl_builtin_expected_type) + << TheCall->getDirectCallee() << "'ndrange_t'"; + return true; + } + + // With four arguments, there is only one form that the function could be + // called in: no events and no variable arguments. + if (NumArgs == 4) { + // check that the last argument is the right block type. + if (!isBlockPointer(Arg3)) { + S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) + << TheCall->getDirectCallee() << "block"; + return true; + } + // we have a block type, check the prototype + const BlockPointerType *BPT = + cast(Arg3->getType().getCanonicalType()); + if (BPT->getPointeeType()->getAs()->getNumParams() > 0) { + S.Diag(Arg3->getBeginLoc(), + diag::err_opencl_enqueue_kernel_blocks_no_args); + return true; + } + return false; + } + // we can have block + varargs. + if (isBlockPointer(Arg3)) + return (checkOpenCLBlockArgs(S, Arg3) || + checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); + // last two cases with either exactly 7 args or 7 args and varargs. + if (NumArgs >= 7) { + // check common block argument. + Expr *Arg6 = TheCall->getArg(6); + if (!isBlockPointer(Arg6)) { + S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) + << TheCall->getDirectCallee() << "block"; + return true; + } + if (checkOpenCLBlockArgs(S, Arg6)) + return true; + + // Forth argument has to be any integer type. + if (!Arg3->getType()->isIntegerType()) { + S.Diag(TheCall->getArg(3)->getBeginLoc(), + diag::err_opencl_builtin_expected_type) + << TheCall->getDirectCallee() << "integer"; + return true; + } + // check remaining common arguments. + Expr *Arg4 = TheCall->getArg(4); + Expr *Arg5 = TheCall->getArg(5); + + // Fifth argument is always passed as a pointer to clk_event_t. + if (!Arg4->isNullPointerConstant(S.Context, + Expr::NPC_ValueDependentIsNotNull) && + !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { + S.Diag(TheCall->getArg(4)->getBeginLoc(), + diag::err_opencl_builtin_expected_type) + << TheCall->getDirectCallee() + << S.Context.getPointerType(S.Context.OCLClkEventTy); + return true; + } + + // Sixth argument is always passed as a pointer to clk_event_t. + if (!Arg5->isNullPointerConstant(S.Context, + Expr::NPC_ValueDependentIsNotNull) && + !(Arg5->getType()->isPointerType() && + Arg5->getType()->getPointeeType()->isClkEventT())) { + S.Diag(TheCall->getArg(5)->getBeginLoc(), + diag::err_opencl_builtin_expected_type) + << TheCall->getDirectCallee() + << S.Context.getPointerType(S.Context.OCLClkEventTy); + return true; + } + + if (NumArgs == 7) + return false; + + return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); + } + + // None of the specific case has been detected, give generic error + S.Diag(TheCall->getBeginLoc(), + diag::err_opencl_enqueue_kernel_incorrect_args); + return true; + } + + /// Returns OpenCL access qual. + static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { + return D->getAttr(); + } + + /// Returns true if pipe element type is different from the pointer. + static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { + const Expr *Arg0 = Call->getArg(0); + // First argument type should always be pipe. + if (!Arg0->getType()->isPipeType()) { + S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) + << Call->getDirectCallee() << Arg0->getSourceRange(); + return true; + } + OpenCLAccessAttr *AccessQual = + getOpenCLArgAccess(cast(Arg0)->getDecl()); + // Validates the access qualifier is compatible with the call. + // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be + // read_only and write_only, and assumed to be read_only if no qualifier is + // specified. + switch (Call->getDirectCallee()->getBuiltinID()) { + case Builtin::BIread_pipe: + case Builtin::BIreserve_read_pipe: + case Builtin::BIcommit_read_pipe: + case Builtin::BIwork_group_reserve_read_pipe: + case Builtin::BIsub_group_reserve_read_pipe: + case Builtin::BIwork_group_commit_read_pipe: + case Builtin::BIsub_group_commit_read_pipe: + if (!(!AccessQual || AccessQual->isReadOnly())) { + S.Diag(Arg0->getBeginLoc(), + diag::err_opencl_builtin_pipe_invalid_access_modifier) + << "read_only" << Arg0->getSourceRange(); + return true; + } + break; + case Builtin::BIwrite_pipe: + case Builtin::BIreserve_write_pipe: + case Builtin::BIcommit_write_pipe: + case Builtin::BIwork_group_reserve_write_pipe: + case Builtin::BIsub_group_reserve_write_pipe: + case Builtin::BIwork_group_commit_write_pipe: + case Builtin::BIsub_group_commit_write_pipe: + if (!(AccessQual && AccessQual->isWriteOnly())) { + S.Diag(Arg0->getBeginLoc(), + diag::err_opencl_builtin_pipe_invalid_access_modifier) + << "write_only" << Arg0->getSourceRange(); + return true; + } + break; + default: + break; + } + return false; + } + + /// Returns true if pipe element type is different from the pointer. + static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { + const Expr *Arg0 = Call->getArg(0); + const Expr *ArgIdx = Call->getArg(Idx); + const PipeType *PipeTy = cast(Arg0->getType()); + const QualType EltTy = PipeTy->getElementType(); + const PointerType *ArgTy = ArgIdx->getType()->getAs(); + // The Idx argument should be a pointer and the type of the pointer and + // the type of pipe element should also be the same. + if (!ArgTy || + !S.Context.hasSameType( + EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { + S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) + << Call->getDirectCallee() << S.Context.getPointerType(EltTy) + << ArgIdx->getType() << ArgIdx->getSourceRange(); + return true; + } + return false; + } + + // Performs semantic analysis for the read/write_pipe call. + // \param S Reference to the semantic analyzer. + // \param Call A pointer to the builtin call. + // \return True if a semantic error has been found, false otherwise. + static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { + // OpenCL v2.0 s6.13.16.2 - The built-in read/write + // functions have two forms. + switch (Call->getNumArgs()) { + case 2: + if (checkOpenCLPipeArg(S, Call)) + return true; + // The call with 2 arguments should be + // read/write_pipe(pipe T, T*). + // Check packet type T. + if (checkOpenCLPipePacketType(S, Call, 1)) + return true; + break; + + case 4: { + if (checkOpenCLPipeArg(S, Call)) + return true; + // The call with 4 arguments should be + // read/write_pipe(pipe T, reserve_id_t, uint, T*). + // Check reserve_id_t. + if (!Call->getArg(1)->getType()->isReserveIDT()) { + S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) + << Call->getDirectCallee() << S.Context.OCLReserveIDTy + << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); + return true; + } + + // Check the index. + const Expr *Arg2 = Call->getArg(2); + if (!Arg2->getType()->isIntegerType() && + !Arg2->getType()->isUnsignedIntegerType()) { + S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) + << Call->getDirectCallee() << S.Context.UnsignedIntTy + << Arg2->getType() << Arg2->getSourceRange(); + return true; + } + + // Check packet type T. + if (checkOpenCLPipePacketType(S, Call, 3)) + return true; + } break; + default: + S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) + << Call->getDirectCallee() << Call->getSourceRange(); + return true; + } + + return false; + } + + // Performs a semantic analysis on the {work_group_/sub_group_ + // /_}reserve_{read/write}_pipe + // \param S Reference to the semantic analyzer. + // \param Call The call to the builtin function to be analyzed. + // \return True if a semantic error was found, false otherwise. + static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { + if (checkArgCount(S, Call, 2)) + return true; + + if (checkOpenCLPipeArg(S, Call)) + return true; + + // Check the reserve size. + if (!Call->getArg(1)->getType()->isIntegerType() && + !Call->getArg(1)->getType()->isUnsignedIntegerType()) { + S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) + << Call->getDirectCallee() << S.Context.UnsignedIntTy + << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); + return true; + } + + // Since return type of reserve_read/write_pipe built-in function is + // reserve_id_t, which is not defined in the builtin def file , we used int + // as return type and need to override the return type of these functions. + Call->setType(S.Context.OCLReserveIDTy); + + return false; + } + + // Performs a semantic analysis on {work_group_/sub_group_ + // /_}commit_{read/write}_pipe + // \param S Reference to the semantic analyzer. + // \param Call The call to the builtin function to be analyzed. + // \return True if a semantic error was found, false otherwise. + static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { + if (checkArgCount(S, Call, 2)) + return true; + + if (checkOpenCLPipeArg(S, Call)) + return true; + + // Check reserve_id_t. + if (!Call->getArg(1)->getType()->isReserveIDT()) { + S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) + << Call->getDirectCallee() << S.Context.OCLReserveIDTy + << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); + return true; + } + + return false; + } + + // Performs a semantic analysis on the call to built-in Pipe + // Query Functions. + // \param S Reference to the semantic analyzer. + // \param Call The call to the builtin function to be analyzed. + // \return True if a semantic error was found, false otherwise. + static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { + if (checkArgCount(S, Call, 1)) + return true; + + if (!Call->getArg(0)->getType()->isPipeType()) { + S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) + << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); + return true; + } + + return false; + } + + // OpenCL v2.0 s6.13.9 - Address space qualifier functions. + // Performs semantic analysis for the to_global/local/private call. + // \param S Reference to the semantic analyzer. + // \param BuiltinID ID of the builtin function. + // \param Call A pointer to the builtin call. + // \return True if a semantic error has been found, false otherwise. + static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, + CallExpr *Call) { + if (Call->getNumArgs() != 1) { + S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) + << Call->getDirectCallee() << Call->getSourceRange(); + return true; + } + + auto RT = Call->getArg(0)->getType(); + if (!RT->isPointerType() || RT->getPointeeType() + .getAddressSpace() == LangAS::opencl_constant) { + S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) + << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); + return true; + } + + if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { + S.Diag(Call->getArg(0)->getBeginLoc(), + diag::warn_opencl_generic_address_space_arg) + << Call->getDirectCallee()->getNameInfo().getAsString() + << Call->getArg(0)->getSourceRange(); + } + + RT = RT->getPointeeType(); + auto Qual = RT.getQualifiers(); + switch (BuiltinID) { + case Builtin::BIto_global: + Qual.setAddressSpace(LangAS::opencl_global); + break; + case Builtin::BIto_local: + Qual.setAddressSpace(LangAS::opencl_local); + break; + case Builtin::BIto_private: + Qual.setAddressSpace(LangAS::opencl_private); + break; + default: + llvm_unreachable("Invalid builtin function"); + } + Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( + RT.getUnqualifiedType(), Qual))); + + return false; + } + + static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { + if (checkArgCount(S, TheCall, 1)) + return ExprError(); + + // Compute __builtin_launder's parameter type from the argument. + // The parameter type is: + // * The type of the argument if it's not an array or function type, + // Otherwise, + // * The decayed argument type. + QualType ParamTy = [&]() { + QualType ArgTy = TheCall->getArg(0)->getType(); + if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) + return S.Context.getPointerType(Ty->getElementType()); + if (ArgTy->isFunctionType()) { + return S.Context.getPointerType(ArgTy); + } + return ArgTy; + }(); + + TheCall->setType(ParamTy); + + auto DiagSelect = [&]() -> llvm::Optional { + if (!ParamTy->isPointerType()) + return 0; + if (ParamTy->isFunctionPointerType()) + return 1; + if (ParamTy->isVoidPointerType()) + return 2; + return llvm::Optional{}; + }(); + if (DiagSelect.hasValue()) { + S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) + << DiagSelect.getValue() << TheCall->getSourceRange(); + return ExprError(); + } + + // We either have an incomplete class type, or we have a class template + // whose instantiation has not been forced. Example: + // + // template struct Foo { T value; }; + // Foo *p = nullptr; + // auto *d = __builtin_launder(p); + if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), + diag::err_incomplete_type)) + return ExprError(); + + assert(ParamTy->getPointeeType()->isObjectType() && + "Unhandled non-object pointer case"); + + InitializedEntity Entity = + InitializedEntity::InitializeParameter(S.Context, ParamTy, false); + ExprResult Arg = + S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); + if (Arg.isInvalid()) + return ExprError(); + TheCall->setArg(0, Arg.get()); + + return TheCall; + } + + // Emit an error and return true if the current architecture is not in the list + // of supported architectures. + static bool + CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, + ArrayRef SupportedArchs) { + llvm::Triple::ArchType CurArch = + S.getASTContext().getTargetInfo().getTriple().getArch(); + if (llvm::is_contained(SupportedArchs, CurArch)) + return false; + S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) + << TheCall->getSourceRange(); + return true; + } + + ExprResult + Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, + CallExpr *TheCall) { + ExprResult TheCallResult(TheCall); + + // Find out if any arguments are required to be integer constant expressions. + unsigned ICEArguments = 0; + ASTContext::GetBuiltinTypeError Error; + Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); + if (Error != ASTContext::GE_None) + ICEArguments = 0; // Don't diagnose previously diagnosed errors. + + // If any arguments are required to be ICE's, check and diagnose. + for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { + // Skip arguments not required to be ICE's. + if ((ICEArguments & (1 << ArgNo)) == 0) continue; + + llvm::APSInt Result; + if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) + return true; + ICEArguments &= ~(1 << ArgNo); + } + + switch (BuiltinID) { + case Builtin::BI__builtin___CFStringMakeConstantString: + assert(TheCall->getNumArgs() == 1 && + "Wrong # arguments to builtin CFStringMakeConstantString"); + if (CheckObjCString(TheCall->getArg(0))) + return ExprError(); + break; + case Builtin::BI__builtin_ms_va_start: + case Builtin::BI__builtin_stdarg_start: + case Builtin::BI__builtin_va_start: + if (SemaBuiltinVAStart(BuiltinID, TheCall)) + return ExprError(); + break; + case Builtin::BI__va_start: { + switch (Context.getTargetInfo().getTriple().getArch()) { + case llvm::Triple::aarch64: + case llvm::Triple::arm: + case llvm::Triple::thumb: + if (SemaBuiltinVAStartARMMicrosoft(TheCall)) + return ExprError(); + break; + default: + if (SemaBuiltinVAStart(BuiltinID, TheCall)) + return ExprError(); + break; + } + break; + } + + // The acquire, release, and no fence variants are ARM and AArch64 only. + case Builtin::BI_interlockedbittestandset_acq: + case Builtin::BI_interlockedbittestandset_rel: + case Builtin::BI_interlockedbittestandset_nf: + case Builtin::BI_interlockedbittestandreset_acq: + case Builtin::BI_interlockedbittestandreset_rel: + case Builtin::BI_interlockedbittestandreset_nf: + if (CheckBuiltinTargetSupport( + *this, BuiltinID, TheCall, + {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) + return ExprError(); + break; + + // The 64-bit bittest variants are x64, ARM, and AArch64 only. + case Builtin::BI_bittest64: + case Builtin::BI_bittestandcomplement64: + case Builtin::BI_bittestandreset64: + case Builtin::BI_bittestandset64: + case Builtin::BI_interlockedbittestandreset64: + case Builtin::BI_interlockedbittestandset64: + if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, + {llvm::Triple::x86_64, llvm::Triple::arm, + llvm::Triple::thumb, llvm::Triple::aarch64})) + return ExprError(); + break; + + case Builtin::BI__builtin_isgreater: + case Builtin::BI__builtin_isgreaterequal: + case Builtin::BI__builtin_isless: + case Builtin::BI__builtin_islessequal: + case Builtin::BI__builtin_islessgreater: + case Builtin::BI__builtin_isunordered: + if (SemaBuiltinUnorderedCompare(TheCall)) + return ExprError(); + break; + case Builtin::BI__builtin_fpclassify: + if (SemaBuiltinFPClassification(TheCall, 6)) + return ExprError(); + break; + case Builtin::BI__builtin_isfinite: + case Builtin::BI__builtin_isinf: + case Builtin::BI__builtin_isinf_sign: + case Builtin::BI__builtin_isnan: + case Builtin::BI__builtin_isnormal: + case Builtin::BI__builtin_signbit: + case Builtin::BI__builtin_signbitf: + case Builtin::BI__builtin_signbitl: + if (SemaBuiltinFPClassification(TheCall, 1)) + return ExprError(); + break; + case Builtin::BI__builtin_shufflevector: + return SemaBuiltinShuffleVector(TheCall); + // TheCall will be freed by the smart pointer here, but that's fine, since + // SemaBuiltinShuffleVector guts it, but then doesn't release it. + case Builtin::BI__builtin_prefetch: + if (SemaBuiltinPrefetch(TheCall)) + return ExprError(); + break; + case Builtin::BI__builtin_alloca_with_align: + if (SemaBuiltinAllocaWithAlign(TheCall)) + return ExprError(); + break; + case Builtin::BI__assume: + case Builtin::BI__builtin_assume: + if (SemaBuiltinAssume(TheCall)) + return ExprError(); + break; + case Builtin::BI__builtin_assume_aligned: + if (SemaBuiltinAssumeAligned(TheCall)) + return ExprError(); + break; + case Builtin::BI__builtin_dynamic_object_size: + case Builtin::BI__builtin_object_size: + if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) + return ExprError(); + break; + case Builtin::BI__builtin_longjmp: + if (SemaBuiltinLongjmp(TheCall)) + return ExprError(); + break; + case Builtin::BI__builtin_setjmp: + if (SemaBuiltinSetjmp(TheCall)) + return ExprError(); + break; + case Builtin::BI_setjmp: + case Builtin::BI_setjmpex: + if (checkArgCount(*this, TheCall, 1)) + return true; + break; + case Builtin::BI__builtin_classify_type: + if (checkArgCount(*this, TheCall, 1)) return true; + TheCall->setType(Context.IntTy); + break; + case Builtin::BI__builtin_constant_p: { + if (checkArgCount(*this, TheCall, 1)) return true; + ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); + if (Arg.isInvalid()) return true; + TheCall->setArg(0, Arg.get()); + TheCall->setType(Context.IntTy); + break; + } + case Builtin::BI__builtin_launder: + return SemaBuiltinLaunder(*this, TheCall); + 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: + 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: + 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: + 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: + 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: + 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: + 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: + 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: + 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: + 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: + 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: + 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: + 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: + 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: + 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: + 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: + 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: + return SemaBuiltinAtomicOverloaded(TheCallResult); + case Builtin::BI__sync_synchronize: + Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) + << TheCall->getCallee()->getSourceRange(); + break; + case Builtin::BI__builtin_nontemporal_load: + case Builtin::BI__builtin_nontemporal_store: + return SemaBuiltinNontemporalOverloaded(TheCallResult); + #define BUILTIN(ID, TYPE, ATTRS) + #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ + case Builtin::BI##ID: \ + return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); + #include "clang/Basic/Builtins.def" + case Builtin::BI__annotation: + if (SemaBuiltinMSVCAnnotation(*this, TheCall)) + return ExprError(); + break; + case Builtin::BI__builtin_annotation: + if (SemaBuiltinAnnotation(*this, TheCall)) + return ExprError(); + break; + case Builtin::BI__builtin_addressof: + if (SemaBuiltinAddressof(*this, TheCall)) + return ExprError(); + break; + case Builtin::BI__builtin_add_overflow: + case Builtin::BI__builtin_sub_overflow: + case Builtin::BI__builtin_mul_overflow: + if (SemaBuiltinOverflow(*this, TheCall)) + return ExprError(); + break; + case Builtin::BI__builtin_operator_new: + case Builtin::BI__builtin_operator_delete: { + bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; + ExprResult Res = + SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); + if (Res.isInvalid()) + CorrectDelayedTyposInExpr(TheCallResult.get()); + return Res; + } + case Builtin::BI__builtin_dump_struct: { + // We first want to ensure we are called with 2 arguments + if (checkArgCount(*this, TheCall, 2)) + return ExprError(); + // Ensure that the first argument is of type 'struct XX *' + const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); + const QualType PtrArgType = PtrArg->getType(); + if (!PtrArgType->isPointerType() || + !PtrArgType->getPointeeType()->isRecordType()) { + Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) + << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType + << "structure pointer"; + return ExprError(); + } + + // Ensure that the second argument is of type 'FunctionType' + const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); + const QualType FnPtrArgType = FnPtrArg->getType(); + if (!FnPtrArgType->isPointerType()) { + Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) + << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 + << FnPtrArgType << "'int (*)(const char *, ...)'"; + return ExprError(); + } + + const auto *FuncType = + FnPtrArgType->getPointeeType()->getAs(); + + if (!FuncType) { + Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) + << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 + << FnPtrArgType << "'int (*)(const char *, ...)'"; + return ExprError(); + } + + if (const auto *FT = dyn_cast(FuncType)) { + if (!FT->getNumParams()) { + Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) + << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 + << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; + return ExprError(); + } + QualType PT = FT->getParamType(0); + if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || + !PT->isPointerType() || !PT->getPointeeType()->isCharType() || + !PT->getPointeeType().isConstQualified()) { + Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) + << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 + << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; + return ExprError(); + } + } + + TheCall->setType(Context.IntTy); + break; + } + case Builtin::BI__builtin_preserve_access_index: + if (SemaBuiltinPreserveAI(*this, TheCall)) + return ExprError(); + break; + case Builtin::BI__builtin_call_with_static_chain: + if (SemaBuiltinCallWithStaticChain(*this, TheCall)) + return ExprError(); + break; + case Builtin::BI__exception_code: + case Builtin::BI_exception_code: + if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, + diag::err_seh___except_block)) + return ExprError(); + break; + case Builtin::BI__exception_info: + case Builtin::BI_exception_info: + if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, + diag::err_seh___except_filter)) + return ExprError(); + break; + case Builtin::BI__GetExceptionInfo: + if (checkArgCount(*this, TheCall, 1)) + return ExprError(); + + if (CheckCXXThrowOperand( + TheCall->getBeginLoc(), + Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), + TheCall)) + return ExprError(); + + TheCall->setType(Context.VoidPtrTy); + break; + // OpenCL v2.0, s6.13.16 - Pipe functions + case Builtin::BIread_pipe: + case Builtin::BIwrite_pipe: + // Since those two functions are declared with var args, we need a semantic + // check for the argument. + if (SemaBuiltinRWPipe(*this, TheCall)) + return ExprError(); + break; + case Builtin::BIreserve_read_pipe: + case Builtin::BIreserve_write_pipe: + case Builtin::BIwork_group_reserve_read_pipe: + case Builtin::BIwork_group_reserve_write_pipe: + if (SemaBuiltinReserveRWPipe(*this, TheCall)) + return ExprError(); + break; + case Builtin::BIsub_group_reserve_read_pipe: + case Builtin::BIsub_group_reserve_write_pipe: + if (checkOpenCLSubgroupExt(*this, TheCall) || + SemaBuiltinReserveRWPipe(*this, TheCall)) + return ExprError(); + break; + case Builtin::BIcommit_read_pipe: + case Builtin::BIcommit_write_pipe: + case Builtin::BIwork_group_commit_read_pipe: + case Builtin::BIwork_group_commit_write_pipe: + if (SemaBuiltinCommitRWPipe(*this, TheCall)) + return ExprError(); + break; + case Builtin::BIsub_group_commit_read_pipe: + case Builtin::BIsub_group_commit_write_pipe: + if (checkOpenCLSubgroupExt(*this, TheCall) || + SemaBuiltinCommitRWPipe(*this, TheCall)) + return ExprError(); + break; + case Builtin::BIget_pipe_num_packets: + case Builtin::BIget_pipe_max_packets: + if (SemaBuiltinPipePackets(*this, TheCall)) + return ExprError(); + break; + case Builtin::BIto_global: + case Builtin::BIto_local: + case Builtin::BIto_private: + if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) + return ExprError(); + break; + // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. + case Builtin::BIenqueue_kernel: + if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) + return ExprError(); + break; + case Builtin::BIget_kernel_work_group_size: + case Builtin::BIget_kernel_preferred_work_group_size_multiple: + if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) + return ExprError(); + break; + case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: + case Builtin::BIget_kernel_sub_group_count_for_ndrange: + if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) + return ExprError(); + break; + case Builtin::BI__builtin_os_log_format: + case Builtin::BI__builtin_os_log_format_buffer_size: + if (SemaBuiltinOSLogFormat(TheCall)) + return ExprError(); + break; + } + + // Since the target specific builtins for each arch overlap, only check those + // of the arch we are compiling for. + if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { + switch (Context.getTargetInfo().getTriple().getArch()) { + case llvm::Triple::arm: + case llvm::Triple::armeb: + case llvm::Triple::thumb: + case llvm::Triple::thumbeb: + if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) + return ExprError(); + break; + case llvm::Triple::aarch64: + case llvm::Triple::aarch64_be: + if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) + return ExprError(); + break; + case llvm::Triple::hexagon: + if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) + return ExprError(); + break; + case llvm::Triple::mips: + case llvm::Triple::mipsel: + case llvm::Triple::mips64: + case llvm::Triple::mips64el: + if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) + return ExprError(); + break; + case llvm::Triple::systemz: + if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) + return ExprError(); + break; + case llvm::Triple::x86: + case llvm::Triple::x86_64: + if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) + return ExprError(); + break; + case llvm::Triple::ppc: + case llvm::Triple::ppc64: + case llvm::Triple::ppc64le: + if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) + return ExprError(); + break; + default: + break; + } + } + + return TheCallResult; + } + + // Get the valid immediate range for the specified NEON type code. + static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { + NeonTypeFlags Type(t); + int IsQuad = ForceQuad ? true : Type.isQuad(); + switch (Type.getEltType()) { + case NeonTypeFlags::Int8: + case NeonTypeFlags::Poly8: + return shift ? 7 : (8 << IsQuad) - 1; + case NeonTypeFlags::Int16: + case NeonTypeFlags::Poly16: + return shift ? 15 : (4 << IsQuad) - 1; + case NeonTypeFlags::Int32: + return shift ? 31 : (2 << IsQuad) - 1; + case NeonTypeFlags::Int64: + case NeonTypeFlags::Poly64: + return shift ? 63 : (1 << IsQuad) - 1; + case NeonTypeFlags::Poly128: + return shift ? 127 : (1 << IsQuad) - 1; + case NeonTypeFlags::Float16: + assert(!shift && "cannot shift float types!"); + return (4 << IsQuad) - 1; + case NeonTypeFlags::Float32: + assert(!shift && "cannot shift float types!"); + return (2 << IsQuad) - 1; + case NeonTypeFlags::Float64: + assert(!shift && "cannot shift float types!"); + return (1 << IsQuad) - 1; + } + llvm_unreachable("Invalid NeonTypeFlag!"); + } + + /// getNeonEltType - Return the QualType corresponding to the elements of + /// the vector type specified by the NeonTypeFlags. This is used to check + /// the pointer arguments for Neon load/store intrinsics. + static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, + bool IsPolyUnsigned, bool IsInt64Long) { + switch (Flags.getEltType()) { + case NeonTypeFlags::Int8: + return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; + case NeonTypeFlags::Int16: + return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; + case NeonTypeFlags::Int32: + return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; + case NeonTypeFlags::Int64: + if (IsInt64Long) + return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; + else + return Flags.isUnsigned() ? Context.UnsignedLongLongTy + : Context.LongLongTy; + case NeonTypeFlags::Poly8: + return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; + case NeonTypeFlags::Poly16: + return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; + case NeonTypeFlags::Poly64: + if (IsInt64Long) + return Context.UnsignedLongTy; + else + return Context.UnsignedLongLongTy; + case NeonTypeFlags::Poly128: + break; + case NeonTypeFlags::Float16: + return Context.HalfTy; + case NeonTypeFlags::Float32: + return Context.FloatTy; + case NeonTypeFlags::Float64: + return Context.DoubleTy; + } + llvm_unreachable("Invalid NeonTypeFlag!"); + } + + bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { + llvm::APSInt Result; + uint64_t mask = 0; + unsigned TV = 0; + int PtrArgNum = -1; + bool HasConstPtr = false; + switch (BuiltinID) { + #define GET_NEON_OVERLOAD_CHECK + #include "clang/Basic/arm_neon.inc" + #include "clang/Basic/arm_fp16.inc" + #undef GET_NEON_OVERLOAD_CHECK + } + + // For NEON intrinsics which are overloaded on vector element type, validate + // the immediate which specifies which variant to emit. + unsigned ImmArg = TheCall->getNumArgs()-1; + if (mask) { + if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) + return true; + + TV = Result.getLimitedValue(64); + if ((TV > 63) || (mask & (1ULL << TV)) == 0) + return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) + << TheCall->getArg(ImmArg)->getSourceRange(); + } + + if (PtrArgNum >= 0) { + // Check that pointer arguments have the specified type. + Expr *Arg = TheCall->getArg(PtrArgNum); + if (ImplicitCastExpr *ICE = dyn_cast(Arg)) + Arg = ICE->getSubExpr(); + ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); + QualType RHSTy = RHS.get()->getType(); + + llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); + bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || + Arch == llvm::Triple::aarch64_be; + bool IsInt64Long = + Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; + QualType EltTy = + getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); + if (HasConstPtr) + EltTy = EltTy.withConst(); + QualType LHSTy = Context.getPointerType(EltTy); + AssignConvertType ConvTy; + ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); + if (RHS.isInvalid()) + return true; + if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, + RHS.get(), AA_Assigning)) + return true; + } + + // For NEON 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; + #define GET_NEON_IMMEDIATE_CHECK + #include "clang/Basic/arm_neon.inc" + #include "clang/Basic/arm_fp16.inc" + #undef GET_NEON_IMMEDIATE_CHECK + } + + return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); + } + + bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, + unsigned MaxWidth) { + assert((BuiltinID == ARM::BI__builtin_arm_ldrex || + BuiltinID == ARM::BI__builtin_arm_ldaex || + BuiltinID == ARM::BI__builtin_arm_strex || + BuiltinID == ARM::BI__builtin_arm_stlex || + BuiltinID == AArch64::BI__builtin_arm_ldrex || + BuiltinID == AArch64::BI__builtin_arm_ldaex || + BuiltinID == AArch64::BI__builtin_arm_strex || + BuiltinID == AArch64::BI__builtin_arm_stlex) && + "unexpected ARM builtin"); + bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || + BuiltinID == ARM::BI__builtin_arm_ldaex || + BuiltinID == AArch64::BI__builtin_arm_ldrex || + BuiltinID == AArch64::BI__builtin_arm_ldaex; + + DeclRefExpr *DRE =cast(TheCall->getCallee()->IgnoreParenCasts()); + + // Ensure that we have the proper number of arguments. + if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) + return true; + + // Inspect the pointer 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. + Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); + ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); + if (PointerArgRes.isInvalid()) + return true; + PointerArg = PointerArgRes.get(); + + const PointerType *pointerType = PointerArg->getType()->getAs(); + if (!pointerType) { + Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) + << PointerArg->getType() << PointerArg->getSourceRange(); + return true; + } + + // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next + // task is to insert the appropriate casts into the AST. First work out just + // what the appropriate type is. + QualType ValType = pointerType->getPointeeType(); + QualType AddrType = ValType.getUnqualifiedType().withVolatile(); + if (IsLdrex) + AddrType.addConst(); + + // Issue a warning if the cast is dodgy. + CastKind CastNeeded = CK_NoOp; + if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { + CastNeeded = CK_BitCast; + Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) + << PointerArg->getType() << Context.getPointerType(AddrType) + << AA_Passing << PointerArg->getSourceRange(); + } + + // Finally, do the cast and replace the argument with the corrected version. + AddrType = Context.getPointerType(AddrType); + PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); + if (PointerArgRes.isInvalid()) + return true; + PointerArg = PointerArgRes.get(); + + TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); + + // In general, we allow ints, floats and pointers to be loaded and stored. + if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && + !ValType->isBlockPointerType() && !ValType->isFloatingType()) { + Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) + << PointerArg->getType() << PointerArg->getSourceRange(); + return true; + } + + // But ARM doesn't have instructions to deal with 128-bit versions. + if (Context.getTypeSize(ValType) > MaxWidth) { + assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); + Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) + << PointerArg->getType() << PointerArg->getSourceRange(); + return true; + } + + 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 << PointerArg->getSourceRange(); + return true; + } + + if (IsLdrex) { + TheCall->setType(ValType); + return false; + } + + // Initialize the argument to be stored. + ExprResult ValArg = TheCall->getArg(0); + InitializedEntity Entity = InitializedEntity::InitializeParameter( + Context, ValType, /*consume*/ false); + ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); + if (ValArg.isInvalid()) + return true; + TheCall->setArg(0, ValArg.get()); + + // __builtin_arm_strex always returns an int. It's marked as such in the .def, + // but the custom checker bypasses all default analysis. + TheCall->setType(Context.IntTy); + return false; + } + + bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { + if (BuiltinID == ARM::BI__builtin_arm_ldrex || + BuiltinID == ARM::BI__builtin_arm_ldaex || + BuiltinID == ARM::BI__builtin_arm_strex || + BuiltinID == ARM::BI__builtin_arm_stlex) { + return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); + } + + if (BuiltinID == ARM::BI__builtin_arm_prefetch) { + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || + SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); + } + + if (BuiltinID == ARM::BI__builtin_arm_rsr64 || + BuiltinID == ARM::BI__builtin_arm_wsr64) + return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); + + if (BuiltinID == ARM::BI__builtin_arm_rsr || + BuiltinID == ARM::BI__builtin_arm_rsrp || + BuiltinID == ARM::BI__builtin_arm_wsr || + BuiltinID == ARM::BI__builtin_arm_wsrp) + return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); + + if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) + return true; + + // For intrinsics which take an immediate value as part of the instruction, + // range check them here. + // FIXME: VFP Intrinsics should error if VFP not present. + switch (BuiltinID) { + default: return false; + case ARM::BI__builtin_arm_ssat: + return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); + case ARM::BI__builtin_arm_usat: + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); + case ARM::BI__builtin_arm_ssat16: + return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); + case ARM::BI__builtin_arm_usat16: + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); + case ARM::BI__builtin_arm_vcvtr_f: + case ARM::BI__builtin_arm_vcvtr_d: + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); + case ARM::BI__builtin_arm_dmb: + case ARM::BI__builtin_arm_dsb: + case ARM::BI__builtin_arm_isb: + case ARM::BI__builtin_arm_dbg: + return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); + } + } + + bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, + CallExpr *TheCall) { + if (BuiltinID == AArch64::BI__builtin_arm_ldrex || + BuiltinID == AArch64::BI__builtin_arm_ldaex || + BuiltinID == AArch64::BI__builtin_arm_strex || + BuiltinID == AArch64::BI__builtin_arm_stlex) { + return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); + } + + if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { + return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || + SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || + SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || + SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); + } + + if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || + BuiltinID == AArch64::BI__builtin_arm_wsr64) + return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); + + // Memory Tagging Extensions (MTE) Intrinsics + if (BuiltinID == AArch64::BI__builtin_arm_irg || + BuiltinID == AArch64::BI__builtin_arm_addg || + BuiltinID == AArch64::BI__builtin_arm_gmi || + BuiltinID == AArch64::BI__builtin_arm_ldg || + BuiltinID == AArch64::BI__builtin_arm_stg || + BuiltinID == AArch64::BI__builtin_arm_subp) { + return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); + } + + if (BuiltinID == AArch64::BI__builtin_arm_rsr || + BuiltinID == AArch64::BI__builtin_arm_rsrp || + BuiltinID == AArch64::BI__builtin_arm_wsr || + BuiltinID == AArch64::BI__builtin_arm_wsrp) + return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); + + // Only check the valid encoding range. Any constant in this range would be + // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw + // an exception for incorrect registers. This matches MSVC behavior. + if (BuiltinID == AArch64::BI_ReadStatusReg || + BuiltinID == AArch64::BI_WriteStatusReg) + return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); + + if (BuiltinID == AArch64::BI__getReg) + return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); + + if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) + return true; + + // 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 AArch64::BI__builtin_arm_dmb: + case AArch64::BI__builtin_arm_dsb: + case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; + } + + return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); + } + + bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { + struct BuiltinAndString { + unsigned BuiltinID; + const char *Str; + }; + + static BuiltinAndString ValidCPU[] = { + { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" }, + { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" }, + { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" }, + { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" }, + }; + + static BuiltinAndString ValidHVX[] = { + { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" }, + { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" }, + }; + + // Sort the tables on first execution so we can binary search them. + auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) { + return LHS.BuiltinID < RHS.BuiltinID; + }; + static const bool SortOnce = + (llvm::sort(ValidCPU, SortCmp), + llvm::sort(ValidHVX, SortCmp), true); + (void)SortOnce; + auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) { + return BI.BuiltinID < BuiltinID; + }; + + const TargetInfo &TI = Context.getTargetInfo(); + + const BuiltinAndString *FC = + llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp); + if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) { + const TargetOptions &Opts = TI.getTargetOpts(); + StringRef CPU = Opts.CPU; + if (!CPU.empty()) { + assert(CPU.startswith("hexagon") && "Unexpected CPU name"); + CPU.consume_front("hexagon"); + SmallVector CPUs; + StringRef(FC->Str).split(CPUs, ','); + if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; })) + return Diag(TheCall->getBeginLoc(), + diag::err_hexagon_builtin_unsupported_cpu); + } + } + + const BuiltinAndString *FH = + llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp); + if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) { + if (!TI.hasFeature("hvx")) + return Diag(TheCall->getBeginLoc(), + diag::err_hexagon_builtin_requires_hvx); + + SmallVector HVXs; + StringRef(FH->Str).split(HVXs, ','); + bool IsValid = llvm::any_of(HVXs, + [&TI] (StringRef V) { + std::string F = "hvx" + V.str(); + return TI.hasFeature(F); + }); + if (!IsValid) + return Diag(TheCall->getBeginLoc(), + diag::err_hexagon_builtin_unsupported_hvx); + } + + return false; + } + + bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { + struct ArgInfo { + uint8_t OpNum; + bool IsSigned; + uint8_t BitWidth; + uint8_t Align; + }; + struct BuiltinInfo { + unsigned BuiltinID; + ArgInfo Infos[2]; + }; + + static BuiltinInfo Infos[] = { + { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, + { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, + { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, + { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, + { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, + { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, + { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, + { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, + { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, + { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, + { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, + + { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, + { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, + { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, + { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, + + { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, + {{ 1, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, + {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, + { 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, + { 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, + { 3, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, + { 3, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, + {{ 2, false, 4, 0 }, + { 3, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, + {{ 2, false, 4, 0 }, + { 3, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, + {{ 2, false, 4, 0 }, + { 3, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, + {{ 2, false, 4, 0 }, + { 3, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, + { 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, + { 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, + {{ 1, false, 4, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, + {{ 1, false, 4, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, + {{ 3, false, 1, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, + {{ 3, false, 1, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, + { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, + {{ 3, false, 1, 0 }} }, + }; + + // Use a dynamically initialized static to sort the table exactly once on + // first run. + static const bool SortOnce = + (llvm::sort(Infos, + [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { + return LHS.BuiltinID < RHS.BuiltinID; + }), + true); + (void)SortOnce; + + const BuiltinInfo *F = llvm::partition_point( + Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); + if (F == std::end(Infos) || F->BuiltinID != BuiltinID) + return false; + + bool Error = false; + + for (const ArgInfo &A : F->Infos) { + // Ignore empty ArgInfo elements. + if (A.BitWidth == 0) + continue; + + int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; + int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; + if (!A.Align) { + Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); + } else { + unsigned M = 1 << A.Align; + Min *= M; + Max *= M; + Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | + SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); + } + } + return Error; + } + + bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, + CallExpr *TheCall) { + return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || + CheckHexagonBuiltinArgument(BuiltinID, TheCall); + } + + + // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the + // intrinsic is correct. The switch statement is ordered by DSP, MSA. The + // ordering for DSP is unspecified. MSA is ordered by the data format used + // by the underlying instruction i.e., df/m, df/n and then by size. + // + // FIXME: The size tests here should instead be tablegen'd along with the + // definitions from include/clang/Basic/BuiltinsMips.def. + // FIXME: GCC is strict on signedness for some of these intrinsics, we should + // be too. + bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { + unsigned i = 0, l = 0, u = 0, m = 0; + switch (BuiltinID) { + default: return false; + case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; + case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; + case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; + case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; + case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; + case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; + case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; + // MSA intrinsics. Instructions (which the intrinsics maps to) which use the + // df/m field. + // These intrinsics take an unsigned 3 bit immediate. + case Mips::BI__builtin_msa_bclri_b: + case Mips::BI__builtin_msa_bnegi_b: + case Mips::BI__builtin_msa_bseti_b: + case Mips::BI__builtin_msa_sat_s_b: + case Mips::BI__builtin_msa_sat_u_b: + case Mips::BI__builtin_msa_slli_b: + case Mips::BI__builtin_msa_srai_b: + case Mips::BI__builtin_msa_srari_b: + case Mips::BI__builtin_msa_srli_b: + case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; + case Mips::BI__builtin_msa_binsli_b: + case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; + // These intrinsics take an unsigned 4 bit immediate. + case Mips::BI__builtin_msa_bclri_h: + case Mips::BI__builtin_msa_bnegi_h: + case Mips::BI__builtin_msa_bseti_h: + case Mips::BI__builtin_msa_sat_s_h: + case Mips::BI__builtin_msa_sat_u_h: + case Mips::BI__builtin_msa_slli_h: + case Mips::BI__builtin_msa_srai_h: + case Mips::BI__builtin_msa_srari_h: + case Mips::BI__builtin_msa_srli_h: + case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; + case Mips::BI__builtin_msa_binsli_h: + case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; + // These intrinsics take an unsigned 5 bit immediate. + // The first block of intrinsics actually have an unsigned 5 bit field, + // not a df/n field. + case Mips::BI__builtin_msa_cfcmsa: + case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; + case Mips::BI__builtin_msa_clei_u_b: + case Mips::BI__builtin_msa_clei_u_h: + case Mips::BI__builtin_msa_clei_u_w: + case Mips::BI__builtin_msa_clei_u_d: + case Mips::BI__builtin_msa_clti_u_b: + case Mips::BI__builtin_msa_clti_u_h: + case Mips::BI__builtin_msa_clti_u_w: + case Mips::BI__builtin_msa_clti_u_d: + case Mips::BI__builtin_msa_maxi_u_b: + case Mips::BI__builtin_msa_maxi_u_h: + case Mips::BI__builtin_msa_maxi_u_w: + case Mips::BI__builtin_msa_maxi_u_d: + case Mips::BI__builtin_msa_mini_u_b: + case Mips::BI__builtin_msa_mini_u_h: + case Mips::BI__builtin_msa_mini_u_w: + case Mips::BI__builtin_msa_mini_u_d: + case Mips::BI__builtin_msa_addvi_b: + case Mips::BI__builtin_msa_addvi_h: + case Mips::BI__builtin_msa_addvi_w: + case Mips::BI__builtin_msa_addvi_d: + case Mips::BI__builtin_msa_bclri_w: + case Mips::BI__builtin_msa_bnegi_w: + case Mips::BI__builtin_msa_bseti_w: + case Mips::BI__builtin_msa_sat_s_w: + case Mips::BI__builtin_msa_sat_u_w: + case Mips::BI__builtin_msa_slli_w: + case Mips::BI__builtin_msa_srai_w: + case Mips::BI__builtin_msa_srari_w: + case Mips::BI__builtin_msa_srli_w: + case Mips::BI__builtin_msa_srlri_w: + case Mips::BI__builtin_msa_subvi_b: + case Mips::BI__builtin_msa_subvi_h: + case Mips::BI__builtin_msa_subvi_w: + case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; + case Mips::BI__builtin_msa_binsli_w: + case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; + // These intrinsics take an unsigned 6 bit immediate. + case Mips::BI__builtin_msa_bclri_d: + case Mips::BI__builtin_msa_bnegi_d: + case Mips::BI__builtin_msa_bseti_d: + case Mips::BI__builtin_msa_sat_s_d: + case Mips::BI__builtin_msa_sat_u_d: + case Mips::BI__builtin_msa_slli_d: + case Mips::BI__builtin_msa_srai_d: + case Mips::BI__builtin_msa_srari_d: + case Mips::BI__builtin_msa_srli_d: + case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; + case Mips::BI__builtin_msa_binsli_d: + case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; + // These intrinsics take a signed 5 bit immediate. + case Mips::BI__builtin_msa_ceqi_b: + case Mips::BI__builtin_msa_ceqi_h: + case Mips::BI__builtin_msa_ceqi_w: + case Mips::BI__builtin_msa_ceqi_d: + case Mips::BI__builtin_msa_clti_s_b: + case Mips::BI__builtin_msa_clti_s_h: + case Mips::BI__builtin_msa_clti_s_w: + case Mips::BI__builtin_msa_clti_s_d: + case Mips::BI__builtin_msa_clei_s_b: + case Mips::BI__builtin_msa_clei_s_h: + case Mips::BI__builtin_msa_clei_s_w: + case Mips::BI__builtin_msa_clei_s_d: + case Mips::BI__builtin_msa_maxi_s_b: + case Mips::BI__builtin_msa_maxi_s_h: + case Mips::BI__builtin_msa_maxi_s_w: + case Mips::BI__builtin_msa_maxi_s_d: + case Mips::BI__builtin_msa_mini_s_b: + case Mips::BI__builtin_msa_mini_s_h: + case Mips::BI__builtin_msa_mini_s_w: + case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; + // These intrinsics take an unsigned 8 bit immediate. + case Mips::BI__builtin_msa_andi_b: + case Mips::BI__builtin_msa_nori_b: + case Mips::BI__builtin_msa_ori_b: + case Mips::BI__builtin_msa_shf_b: + case Mips::BI__builtin_msa_shf_h: + case Mips::BI__builtin_msa_shf_w: + case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; + case Mips::BI__builtin_msa_bseli_b: + case Mips::BI__builtin_msa_bmnzi_b: + case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; + // df/n format + // These intrinsics take an unsigned 4 bit immediate. + case Mips::BI__builtin_msa_copy_s_b: + case Mips::BI__builtin_msa_copy_u_b: + case Mips::BI__builtin_msa_insve_b: + case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; + case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; + // These intrinsics take an unsigned 3 bit immediate. + case Mips::BI__builtin_msa_copy_s_h: + case Mips::BI__builtin_msa_copy_u_h: + case Mips::BI__builtin_msa_insve_h: + case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; + case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; + // These intrinsics take an unsigned 2 bit immediate. + case Mips::BI__builtin_msa_copy_s_w: + case Mips::BI__builtin_msa_copy_u_w: + case Mips::BI__builtin_msa_insve_w: + case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; + case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; + // These intrinsics take an unsigned 1 bit immediate. + case Mips::BI__builtin_msa_copy_s_d: + case Mips::BI__builtin_msa_copy_u_d: + case Mips::BI__builtin_msa_insve_d: + case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; + case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; + // Memory offsets and immediate loads. + // These intrinsics take a signed 10 bit immediate. + case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; + case Mips::BI__builtin_msa_ldi_h: + case Mips::BI__builtin_msa_ldi_w: + case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; + case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; + case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; + case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; + case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; + case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; + case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; + case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; + case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; + } + + if (!m) + return SemaBuiltinConstantArgRange(TheCall, i, l, u); + + return SemaBuiltinConstantArgRange(TheCall, i, l, u) || + SemaBuiltinConstantArgMultiple(TheCall, i, m); + } + + bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { + unsigned i = 0, l = 0, u = 0; + bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || + BuiltinID == PPC::BI__builtin_divdeu || + BuiltinID == PPC::BI__builtin_bpermd; + bool IsTarget64Bit = Context.getTargetInfo() + .getTypeWidth(Context + .getTargetInfo() + .getIntPtrType()) == 64; + bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || + BuiltinID == PPC::BI__builtin_divweu || + BuiltinID == PPC::BI__builtin_divde || + BuiltinID == PPC::BI__builtin_divdeu; + + if (Is64BitBltin && !IsTarget64Bit) + return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) + << TheCall->getSourceRange(); + + if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || + (BuiltinID == PPC::BI__builtin_bpermd && + !Context.getTargetInfo().hasFeature("bpermd"))) + return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) + << TheCall->getSourceRange(); + + auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { + if (!Context.getTargetInfo().hasFeature("vsx")) + return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) + << TheCall->getSourceRange(); + return false; + }; + + 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_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_vsx_xxpermdi: + case PPC::BI__builtin_vsx_xxsldwi: + return SemaBuiltinVSX(TheCall); + case PPC::BI__builtin_unpack_vector_int128: + return SemaVSXCheck(TheCall) || + SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); + case PPC::BI__builtin_pack_vector_int128: + return SemaVSXCheck(TheCall); + } + return SemaBuiltinConstantArgRange(TheCall, i, l, u); + } + + bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, + CallExpr *TheCall) { + if (BuiltinID == SystemZ::BI__builtin_tabort) { + Expr *Arg = TheCall->getArg(0); + llvm::APSInt AbortCode(32); + if (Arg->isIntegerConstantExpr(AbortCode, Context) && + 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; + } + 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, 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 (!S.Context.getTargetInfo().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, 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 (!S.Context.getTargetInfo().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: + 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: + ArgNum = 2; + break; + 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_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_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_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_cvtss2sd_round_mask: + case X86::BI__builtin_ia32_getexpsd128_round_mask: + case X86::BI__builtin_ia32_getexpss128_round_mask: + case X86::BI__builtin_ia32_getmantpd512_mask: + case X86::BI__builtin_ia32_getmantps512_mask: + case X86::BI__builtin_ia32_maxsd_round_mask: + case X86::BI__builtin_ia32_maxss_round_mask: + case X86::BI__builtin_ia32_minsd_round_mask: + case X86::BI__builtin_ia32_minss_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_rndscalepd_mask: + case X86::BI__builtin_ia32_rndscaleps_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_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_rndscalesd_round_mask: + case X86::BI__builtin_ia32_rndscaless_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_sqrtpd512: + case X86::BI__builtin_ia32_sqrtps512: + ArgNum = 1; + HasRC = true; + break; + 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: + ArgNum = 2; + HasRC = true; + break; + case X86::BI__builtin_ia32_cvtdq2ps512_mask: + case X86::BI__builtin_ia32_cvtudq2ps512_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: + ArgNum = 3; + HasRC = true; + break; + case X86::BI__builtin_ia32_addss_round_mask: + case X86::BI__builtin_ia32_addsd_round_mask: + case X86::BI__builtin_ia32_divss_round_mask: + case X86::BI__builtin_ia32_divsd_round_mask: + case X86::BI__builtin_ia32_mulss_round_mask: + case X86::BI__builtin_ia32_mulsd_round_mask: + case X86::BI__builtin_ia32_subss_round_mask: + case X86::BI__builtin_ia32_subsd_round_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_cvtsd2ss_round_mask: + case X86::BI__builtin_ia32_sqrtsd_round_mask: + case X86::BI__builtin_ia32_sqrtss_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_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_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: + 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 (Result == 4/*ROUND_CUR_DIRECTION*/ || + Result == 8/*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(); + } + + 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(unsigned BuiltinID, CallExpr *TheCall) { + if (BuiltinID == X86::BI__builtin_cpu_supports) + return SemaBuiltinCpuSupports(*this, TheCall); + + if (BuiltinID == X86::BI__builtin_cpu_is) + return SemaBuiltinCpuIs(*this, TheCall); + + // Check for 32-bit only builtins on a 64-bit target. + const llvm::Triple &TT = Context.getTargetInfo().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; + + // 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_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_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_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_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_fpclasssd_mask: + case X86::BI__builtin_ia32_fpclassss_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: + 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); + } + } + + /// 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); + } + } + + 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, + ArrayRef Args, + const FunctionProtoType *Proto, + SourceLocation Loc) { + VariadicCallType CallType = + Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; + 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(); + + 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; + + CheckAbsoluteValueFunction(TheCall, FDecl); + CheckMaxUnsignedZero(TheCall, FDecl); + + if (getLangOpts().ObjC) + DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); + + unsigned CMId = FDecl->getMemoryFunctionKind(); + if (CMId == 0) + return false; + + // Handle memory setting and copying functions. + if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) + CheckStrlcpycatArguments(TheCall, FnInfo); + else if (CMId == Builtin::BIstrncat) + CheckStrncatArguments(TheCall, FnInfo); + else + 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()); + + // 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_xor + 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_xor) || + 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; + bool IsMinMax = 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__opencl_atomic_fetch_min: + case AtomicExpr::AO__opencl_atomic_fetch_max: + 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; + LLVM_FALLTHROUGH; + 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__atomic_fetch_min: + case AtomicExpr::AO__atomic_fetch_max: + IsMinMax = true; + 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 (TheCall->getNumArgs() < AdjustedNumArgs) { + Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) + << 0 << AdjustedNumArgs << TheCall->getNumArgs() + << TheCall->getCallee()->getSourceRange(); + return ExprError(); + } else if (TheCall->getNumArgs() > AdjustedNumArgs) { + Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(), + diag::err_typecheck_call_too_many_args) + << 0 << AdjustedNumArgs << TheCall->getNumArgs() + << TheCall->getCallee()->getSourceRange(); + return ExprError(); + } + + // Inspect the first argument of the atomic operation. + Expr *Ptr = TheCall->getArg(0); + ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); + if (ConvertedPtr.isInvalid()) + return ExprError(); + + Ptr = ConvertedPtr.get(); + const PointerType *pointerType = Ptr->getType()->getAs(); + if (!pointerType) { + Diag(DRE->getBeginLoc(), 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(DRE->getBeginLoc(), 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(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic) + << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() + << Ptr->getSourceRange(); + return ExprError(); + } + ValType = AtomTy->getAs()->getValueType(); + } else if (Form != Load && Form != LoadCopy) { + if (ValType.isConstQualified()) { + Diag(DRE->getBeginLoc(), 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. + if (IsAddSub && !ValType->isIntegerType() + && !ValType->isPointerType()) { + Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) + << IsC11 << Ptr->getType() << Ptr->getSourceRange(); + return ExprError(); + } + if (IsMinMax) { + const BuiltinType *BT = ValType->getAs(); + if (!BT || (BT->getKind() != BuiltinType::Int && + BT->getKind() != BuiltinType::UInt)) { + Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr); + return ExprError(); + } + } + if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { + Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_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(DRE->getBeginLoc(), 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(DRE->getBeginLoc(), 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(DRE->getBeginLoc(), 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; + } + + // 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 != TheCall->getNumArgs(); ++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, TheCall->getArg(i), DRE->getBeginLoc()); + // 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 == Init || (Form == Arithmetic && ValType->isIntegerType())) + Ty = ValType; + else if (Form == Copy || Form == Xchg) { + if (IsPassedByAddress) + // The value pointer is always dereferenced, a nullptr is undefined. + CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); + Ty = ByValType; + } else if (Form == Arithmetic) + Ty = Context.getPointerDiffType(); + else { + Expr *ValArg = TheCall->getArg(i); + // The value pointer is always dereferenced, a nullptr is undefined. + CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc()); + 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, TheCall->getArg(i), DRE->getBeginLoc()); + 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 = TheCall->getArg(i); + Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); + if (Arg.isInvalid()) + return true; + TheCall->setArg(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(TheCall->getArg(1)); // Val1 + break; + case Load: + SubExprs.push_back(TheCall->getArg(1)); // Order + break; + case LoadCopy: + case Copy: + case Arithmetic: + case Xchg: + SubExprs.push_back(TheCall->getArg(2)); // Order + SubExprs.push_back(TheCall->getArg(1)); // Val1 + break; + case GNUXchg: + // Note, AtomicExpr::getVal2() has a special case for this atomic. + SubExprs.push_back(TheCall->getArg(3)); // Order + SubExprs.push_back(TheCall->getArg(1)); // Val1 + SubExprs.push_back(TheCall->getArg(2)); // Val2 + break; + case C11CmpXchg: + SubExprs.push_back(TheCall->getArg(3)); // Order + SubExprs.push_back(TheCall->getArg(1)); // Val1 + SubExprs.push_back(TheCall->getArg(4)); // OrderFail + SubExprs.push_back(TheCall->getArg(2)); // Val2 + break; + case GNUCmpXchg: + SubExprs.push_back(TheCall->getArg(4)); // Order + SubExprs.push_back(TheCall->getArg(1)); // Val1 + SubExprs.push_back(TheCall->getArg(5)); // OrderFail + SubExprs.push_back(TheCall->getArg(2)); // Val2 + SubExprs.push_back(TheCall->getArg(3)); // Weak + break; + } + + if (SubExprs.size() >= 2 && Form != Init) { + llvm::APSInt Result(32); + if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && + !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 = TheCall->getArg(TheCall->getNumArgs() - 1); + llvm::APSInt Result(32); + if (Scope->isIntegerConstantExpr(Result, Context) && + !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(TheCall->getCallee()->getBeginLoc(), SubExprs, + ResultType, Op, TheCall->getRParenLoc()); + + 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); + + 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); + + 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; + 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()->getAs()->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 (TheCall->getNumArgs() > 2) { + Diag(TheCall->getArg(2)->getBeginLoc(), + diag::err_typecheck_call_too_many_args) + << 0 /*function call*/ << 2 << TheCall->getNumArgs() + << Fn->getSourceRange() + << SourceRange(TheCall->getArg(2)->getBeginLoc(), + (*(TheCall->arg_end() - 1))->getEndLoc()); + return true; + } + + if (TheCall->getNumArgs() < 2) { + return Diag(TheCall->getEndLoc(), + diag::err_typecheck_call_too_few_args_at_least) + << 0 /*function call*/ << 2 << TheCall->getNumArgs(); + } + + // 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->getAs()->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) { + // 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() || + Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) + 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 (TheCall->getNumArgs() < 2) + return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) + << 0 << 2 << TheCall->getNumArgs() /*function call*/; + if (TheCall->getNumArgs() > 2) + return Diag(TheCall->getArg(2)->getBeginLoc(), + diag::err_typecheck_call_too_many_args) + << 0 /*function call*/ << 2 << TheCall->getNumArgs() + << SourceRange(TheCall->getArg(2)->getBeginLoc(), + (*(TheCall->arg_end() - 1))->getEndLoc()); + + 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, false); + 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 (TheCall->getNumArgs() < NumArgs) + return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) + << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; + if (TheCall->getNumArgs() > NumArgs) + return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), + diag::err_typecheck_call_too_many_args) + << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() + << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), + (*(TheCall->arg_end() - 1))->getEndLoc()); + + Expr *OrigArg = TheCall->getArg(NumArgs-1); + + if (OrigArg->isTypeDependent()) + return false; + + // 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(); + + // If this is an implicit conversion from float -> float, double, or + // long double, remove it. + if (ImplicitCastExpr *Cast = dyn_cast(OrigArg)) { + // Only remove standard FloatCasts, leaving other casts inplace + if (Cast->getCastKind() == CK_FloatingCast) { + Expr *CastArg = Cast->getSubExpr(); + if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { + assert( + (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || + Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || + Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && + "promotion from float to either float, double, or long double is " + "the only expected cast here"); + Cast->setSubExpr(nullptr); + TheCall->setArg(NumArgs-1, CastArg); + } + } + } + + 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 (TheCall->getNumArgs() < ExpectedNumArgs) + return Diag(TheCall->getEndLoc(), + diag::err_typecheck_call_too_few_args_at_least) + << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() + << TheCall->getSourceRange(); + + if (TheCall->getNumArgs() > ExpectedNumArgs) + return Diag(TheCall->getEndLoc(), + diag::err_typecheck_call_too_many_args_at_most) + << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() + << TheCall->getSourceRange(); + + // Check the third argument is a compile time constant + llvm::APSInt Value; + if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, 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->getAs()->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->getAs()->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->getAs()->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; + + llvm::APSInt Result(32); + if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, 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_RValue; + 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->getAs()->getNumElements(); + unsigned DstElts = DstTy->getAs()->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; + } + + /// 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 (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; + + if (!Arg->isIntegerConstantExpr(Result, Context)) + return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) + << FDecl->getDeclName() << Arg->getSourceRange(); + + 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) + << Result.toString(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) + << Result.toString(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; + } + + /// 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_lower("cp") || + Fields[0].startswith_lower("p"); + if (ValidString) + Fields[0] = + Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); + + ValidString &= Fields[2].startswith_lower("c"); + if (ValidString) + Fields[2] = Fields[2].drop_front(1); + + if (FiveFields) { + ValidString &= Fields[3].startswith_lower("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; + } + + /// 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); + + // 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) { + 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); + if (Left == SLCT_NotALiteral || !CheckRight) { + return Left; + } + } + + StringLiteralCheckType Right = + checkFormatStringExpr(S, C->getFalseExpr(), Args, + HasVAListArg, format_idx, firstDataArg, + Type, CallType, InFunctionCall, CheckedVarArgs, + UncoveredArg, Offset); + + 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); + 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); + } + } + } + + return SLCT_NotALiteral; + } + case Stmt::ObjCMessageExprClass: { + const auto *ME = cast(E); + if (const auto *ND = ME->getMethodDecl()) { + if (const auto *FA = ND->getAttr()) { + const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); + return checkFormatStringExpr( + S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, + CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); + } + } + + 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); + 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(); + } + + const analyze_printf::ArgType::MatchKind Match = + AT.matchesType(S.Context, ExprTy); + bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic; + 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. + if (AT.matchesType(S.Context, ExprTy)) + return true; + } + } + } 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. + if (ExprTy == S.Context.IntTy) + 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)) + Pedantic = true; + 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 = + Pedantic + ? diag::warn_format_conversion_argument_type_mismatch_pedantic + : diag::warn_format_conversion_argument_type_mismatch; + // 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 = Pedantic + ? 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 = + Pedantic + ? diag::warn_format_conversion_argument_type_mismatch_pedantic + : diag::warn_format_conversion_argument_type_mismatch; + + 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) { + // 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; + + // 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->GetTemporaryExpr()); + 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()); + } + + 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; + } + } + } + + //===--- 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. + unsigned Width; + + /// True if the int is known not to have negative values. + bool NonNegative; + + IntRange(unsigned Width, bool NonNegative) + : Width(Width), NonNegative(NonNegative) {} + + /// 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*/); + } + + 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(); + + 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) { + return IntRange(std::max(L.Width, R.Width), + L.NonNegative && R.NonNegative); + } + + /// Returns the infinum of two ranges: i.e. their aggressive merge. + static IntRange meet(IntRange L, IntRange R) { + return IntRange(std::min(L.Width, R.Width), + L.NonNegative || R.NonNegative); + } + }; + + } // 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 + static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, + bool InConstantContext) { + 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); + + 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); + + // 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); + + // Otherwise, conservatively merge. + IntRange L = + GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); + IntRange R = + GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); + return IntRange::join(L, R); + } + + if (const auto *BO = dyn_cast(E)) { + 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); + + // 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: + return IntRange::meet( + GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), + GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); + + // 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); + + // If the shift amount is a positive constant, drop the width by + // that much. + llvm::APSInt shift; + if (BO->getRHS()->isIntegerConstantExpr(shift, C) && + 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); + + // Black-list pointer subtractions. + case BO_Sub: + if (BO->getLHS()->getType()->isPointerType()) + return IntRange::forValueOfType(C, GetExprType(E)); + 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); + + // If the divisor is constant, use that. + llvm::APSInt divisor; + if (BO->getRHS()->isIntegerConstantExpr(divisor, 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. + IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); + return IntRange(L.Width, L.NonNegative && R.NonNegative); + } + + // The result of a remainder can't be larger than the result of + // either side. + case BO_Rem: { + // Don't 'pre-truncate' the operands. + unsigned opWidth = C.getIntWidth(GetExprType(E)); + IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); + IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); + + IntRange meet = IntRange::meet(L, R); + meet.Width = std::min(meet.Width, MaxWidth); + return meet; + } + + // The default behavior is okay for these. + case BO_Mul: + case BO_Add: + case BO_Xor: + case BO_Or: + break; + } + + // The default case is to treat the operation as if it were closed + // on the narrowest type that encompasses both operands. + IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); + IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); + return IntRange::join(L, R); + } + + 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); + } + } + + if (const auto *OVE = dyn_cast(E)) + return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); + + 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) { + return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); + } + + /// 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); + + 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; + + // TODO: Investigate using GetExprRange() to get tighter bounds + // on the bit ranges. + QualType OtherT = Other->getType(); + if (const auto *AT = OtherT->getAs()) + OtherT = AT->getValueType(); + IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); + + // Special case for ObjC BOOL on targets where its a typedef for a signed char + // (Namely, macOS). + 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) + OtherRange = IntRange::forBoolType(); + + // Determine the promoted range of the other type and see if a comparison of + // the constant against that range is tautological. + PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), + Value.isUnsigned()); + auto Cmp = OtherPromotedRange.compare(Value); + auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); + if (!Result) + 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; + + // 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 (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 { + unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) + ? (HasEnumType(OriginalOther) + ? diag::warn_unsigned_enum_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)) { + llvm::APSInt RHSValue; + llvm::APSInt LHSValue; + + bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); + bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); + + // We don't care about expressions whose result is a constant. + if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) + return AnalyzeImpConvsInComparison(S, E); + + // We only care about expressions where just one side is literal + if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { + // Is the constant on the RHS or LHS? + const bool RhsConstant = IsRHSIntegralLiteral; + 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()); + + // 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()); + + // 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->getAs()->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->getNameAsString(); + } + } + + 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 = Value.toString(10); + std::string PrettyTrunc = TruncatedValue.toString(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); + } + + /// 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) { + 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); + + 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; + } + + // 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); + + 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 ValueInRange.toString(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 bool isObjCSignedCharBool(Sema &S, QualType Ty) { + return Ty->isSpecificBuiltinType(BuiltinType::SChar) && + S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); + } + + static void + CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, + bool *ICContext = nullptr) { + 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) && + Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { + auto Builder = S.Diag(CC, diag::warn_impcast_constant_int_to_objc_bool) + << Result.Val.getInt().toString(10); + Expr *Ignored = E->IgnoreImplicit(); + bool NeedsParens = isa(Ignored) || + isa(Ignored) || + isa(Ignored); + SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); + if (NeedsParens) + Builder << FixItHint::CreateInsertion(E->getBeginLoc(), "(") + << FixItHint::CreateInsertion(EndLoc, ")"); + Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); + 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 (!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())) { + APFixedPoint Value = Result.Val.getFixedPoint(); + APFixedPoint MaxVal = S.Context.getFixedPointMax(T); + 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)) { + 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; + APFixedPoint IntResult = APFixedPoint::getFromIntValue( + Value, S.Context.getFixedPointSemantics(T), &Overflowed); + + if (Overflowed) { + S.DiagRuntimeBehavior(E->getExprLoc(), E, + S.PDiag(diag::warn_impcast_fixed_point_range) + << Value.toString(/*radix=*/10) << T + << E->getSourceRange() + << clang::SourceRange(CC)); + return; + } + } + } + } + ++ // If we are casting an integer type to a floating point type, we might ++ // lose accuracy if the floating point type has a narrower signicand ++ // than the floating point type. Issue warnings for that accuracy loss. ++ if (SourceBT && TargetBT && ++ SourceBT->isIntegerType() && TargetBT->isFloatingType()) { ++ // Determine the number of precision bits in the source integer type. ++ IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); ++ unsigned int SourcePrecision = SourceRange.Width; ++ ++ // Determine the number of precision bits in the target floating point type ++ // Also create the APFloat object to represent the converted value. ++ unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( ++ S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); ++ llvm::APFloat SourceToFloatValue( ++ S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); ++ ++ // If we manage to find out the precisions for both types, perform ++ // acccuracy loss check and issue warning if necessary. ++ if (SourcePrecision > 0 && TargetPrecision > 0 && ++ SourcePrecision > TargetPrecision) { ++ // If the source integer is a constant, then we are sure that the ++ // implicit conversion will lose precision. Otherwise, the implicit ++ // conversion *may* lose precision. ++ llvm::APSInt SourceInt; ++ if (E->isIntegerConstantExpr(SourceInt, S.Context)) { ++ // Obtain string representations of source value and converted value. ++ std::string PrettySourceValue = SourceInt.toString(10); ++ SourceToFloatValue.convertFromAPInt(SourceInt, ++ SourceBT->isSignedInteger(), llvm::APFloat::rmTowardZero); ++ SmallString<32> PrettySourceConvertedValue; ++ SourceToFloatValue.toString(PrettySourceConvertedValue, ++ SourcePrecision); ++ ++ // Issue constant integer to float precision loss warning. ++ S.DiagRuntimeBehavior( ++ E->getExprLoc(), E, ++ S.PDiag(diag::warn_impcast_integer_float_precision_constant) ++ << PrettySourceValue << PrettySourceConvertedValue ++ << E->getType() << T ++ << E->getSourceRange() << clang::SourceRange(CC)); ++ } else { ++ // Issue integer variable to float precision may loss warning. ++ DiagnoseImpCast(S, E, T, CC, ++ diag::warn_impcast_integer_float_precision); ++ } ++ } ++ } ++ + DiagnoseNullConversion(S, E, T, CC); + + S.DiscardMisalignedMemberAddress(Target, 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; + + IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); + IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); + + if (SourceRange.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 = Value.toString(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() << clang::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 > SourceRange.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 == SourceRange.Width && !TargetRange.NonNegative && + SourceRange.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 = Value.toString(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() << clang::SourceRange(CC)); + return; + } + } + + // Fall through for non-constants to give a sign conversion warning. + } + + if ((TargetRange.NonNegative && !SourceRange.NonNegative) || + (!TargetRange.NonNegative && SourceRange.NonNegative && + SourceRange.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, ConditionalOperator *E, + SourceLocation CC, QualType T); + + static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, + SourceLocation CC, bool &ICContext) { + E = E->IgnoreParenImpCasts(); + + if (isa(E)) + return CheckConditionalOperator(S, cast(E), CC, T); + + AnalyzeImplicitConversions(S, E, CC); + if (E->getType() != T) + return CheckImplicitConversion(S, E, T, CC, &ICContext); + } + + static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, + SourceLocation CC, QualType T) { + AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); + + bool Suspicious = false; + CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); + CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); + + // 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, E->getTrueExpr()->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); + } + + /// 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) { + QualType T = OrigE->getType(); + Expr *E = OrigE->IgnoreParenImpCasts(); + + if (E->isTypeDependent() || E->isValueDependent()) + return; + + // For conditional operators, we analyze the arguments as if they + // were being fed directly into the output. + if (isa(E)) { + ConditionalOperator *CO = cast(E); + CheckConditionalOperator(S, CO, CC, T); + return; + } + + // Check implicit argument conversions for function calls. + if (CallExpr *Call = dyn_cast(E)) + 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 (E->getType() != T) + CheckImplicitConversion(S, E, T, CC); + + // 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)) + AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); + } + + // 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); + return AnalyzeImplicitConversions(S, E, CC); + } + + 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; + AnalyzeImplicitConversions(S, ChildExpr, CC); + } + + 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); + } + } + } + + /// 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 EvaluatedExprVisitor { + using Base = EvaluatedExprVisitor; + + /// 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 = 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 + }; + + struct Usage { + Expr *Use; + SequenceTree::Seq Seq; + + Usage() : Use(nullptr), Seq() {} + }; + + struct UsageInfo { + Usage Uses[UK_Count]; + + /// Have we issued a diagnostic for this variable 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 (auto &M : llvm::reverse(ModAsSideEffect)) { + UsageInfo &U = Self.UsageMap[M.first]; + auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; + Self.addUsage(U, M.first, SideEffectUsage.Use, 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(Expr *E, bool Mod) const { + E = E->IgnoreParenCasts(); + if (UnaryOperator *UO = dyn_cast(E)) { + if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) + return getObject(UO->getSubExpr(), Mod); + } else if (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 (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 (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 was modified or used by an expression. + void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { + Usage &U = UI.Uses[UK]; + if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { + if (UK == UK_ModAsSideEffect && ModAsSideEffect) + ModAsSideEffect->push_back(std::make_pair(O, U)); + U.Use = Ref; + U.Seq = Region; + } + } + + /// Check whether a modification or use conflicts with a prior usage. + void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, + bool IsModMod) { + if (UI.Diagnosed) + return; + + const Usage &U = UI.Uses[OtherKind]; + if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) + return; + + Expr *Mod = U.Use; + Expr *ModOrUse = Ref; + 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; + } + + void notePreUse(Object O, Expr *Use) { + UsageInfo &U = UsageMap[O]; + // Uses conflict with other modifications. + checkUsage(O, U, Use, UK_ModAsValue, false); + } + + void notePostUse(Object O, Expr *Use) { + UsageInfo &U = UsageMap[O]; + checkUsage(O, U, Use, UK_ModAsSideEffect, false); + addUsage(U, O, Use, UK_Use); + } + + void notePreMod(Object O, Expr *Mod) { + UsageInfo &U = UsageMap[O]; + // Modifications conflict with other modifications and with uses. + checkUsage(O, U, Mod, UK_ModAsValue, true); + checkUsage(O, U, Mod, UK_Use, false); + } + + void notePostMod(Object O, Expr *Use, UsageKind UK) { + UsageInfo &U = UsageMap[O]; + checkUsage(O, U, Use, UK_ModAsSideEffect, true); + addUsage(U, O, Use, UK); + } + + public: + SequenceChecker(Sema &S, Expr *E, SmallVectorImpl &WorkList) + : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { + Visit(E); + } + + void VisitStmt(Stmt *S) { + // Skip all statements which aren't expressions for now. + } + + void VisitExpr(Expr *E) { + // By default, just recurse to evaluated subexpressions. + Base::VisitStmt(E); + } + + void VisitCastExpr(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(Expr *SequencedBefore, 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(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 + Base::VisitStmt(ASE); + } + + void VisitBinComma(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(BinaryOperator *BO) { + // The modification is sequenced after the value computation of the LHS + // and RHS, so check it before inspecting the operands and update the + // map afterwards. + Object O = getObject(BO->getLHS(), true); + if (!O) + return VisitExpr(BO); + + notePreMod(O, BO); + + // C++11 [expr.ass]p7: + // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated + // only once. + // + // Therefore, for a compound assignment operator, O is considered used + // everywhere except within the evaluation of E1 itself. + if (isa(BO)) + notePreUse(O, BO); + + Visit(BO->getLHS()); + + if (isa(BO)) + notePostUse(O, BO); + + 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. + notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue + : UK_ModAsSideEffect); + } + + void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { + VisitBinAssign(CAO); + } + + void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } + void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } + void VisitUnaryPreIncDec(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(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } + void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } + void VisitUnaryPostIncDec(UnaryOperator *UO) { + Object O = getObject(UO->getSubExpr(), true); + if (!O) + return VisitExpr(UO); + + notePreMod(O, UO); + Visit(UO->getSubExpr()); + notePostMod(O, UO, UK_ModAsSideEffect); + } + + /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. + void VisitBinLOr(BinaryOperator *BO) { + // The side-effects of the LHS of an '&&' are sequenced before the + // value computation of the RHS, and hence before the value computation + // of the '&&' itself, unless the LHS evaluates to zero. We treat them + // as if they were unconditionally sequenced. + EvaluationTracker Eval(*this); + { + SequencedSubexpression Sequenced(*this); + Visit(BO->getLHS()); + } + + bool Result; + if (Eval.evaluate(BO->getLHS(), Result)) { + if (!Result) + Visit(BO->getRHS()); + } else { + // Check for unsequenced operations in the RHS, treating it as an + // entirely separate evaluation. + // + // FIXME: If there are operations in the RHS which are unsequenced + // with respect to operations outside the RHS, and those operations + // are unconditionally evaluated, diagnose them. + WorkList.push_back(BO->getRHS()); + } + } + void VisitBinLAnd(BinaryOperator *BO) { + EvaluationTracker Eval(*this); + { + SequencedSubexpression Sequenced(*this); + Visit(BO->getLHS()); + } + + bool Result; + if (Eval.evaluate(BO->getLHS(), Result)) { + if (Result) + Visit(BO->getRHS()); + } else { + WorkList.push_back(BO->getRHS()); + } + } + + // Only visit the condition, unless we can be sure which subexpression will + // be chosen. + void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { + EvaluationTracker Eval(*this); + { + SequencedSubexpression Sequenced(*this); + Visit(CO->getCond()); + } + + bool Result; + if (Eval.evaluate(CO->getCond(), Result)) + Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); + else { + WorkList.push_back(CO->getTrueExpr()); + WorkList.push_back(CO->getFalseExpr()); + } + } + + void VisitCallExpr(CallExpr *CE) { + // 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); + Base::VisitCallExpr(CE); + + // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. + } + + void VisitCXXConstructExpr(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::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(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) { + 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(Expr *E) { + SmallVector WorkList; + WorkList.push_back(E); + while (!WorkList.empty()) { + 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) + Diag(Param->getLocation(), diag::err_parameter_name_omitted); + + // 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; + } + + /// A helper function to get the alignment of a Decl referred to by DeclRefExpr + /// or MemberExpr. + static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, + ASTContext &Context) { + if (const auto *DRE = dyn_cast(E)) + return Context.getDeclAlign(DRE->getDecl()); + + if (const auto *ME = dyn_cast(E)) + return Context.getDeclAlign(ME->getMemberDecl()); + + return TypeAlign; + } + + /// 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(); + + // Whitelist casts from cv void*. We already implicitly + // whitelisted casts to cv void*, since they have alignment 1. + // Also whitelist casts involving incomplete types, which implicitly + // includes 'void'. + if (SrcPointee->isIncompleteType()) return; + + CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); + + if (auto *CE = dyn_cast(Op)) { + if (CE->getCastKind() == CK_ArrayToPointerDecay) + SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); + } else if (auto *UO = dyn_cast(Op)) { + if (UO->getOpcode() == UO_AddrOf) + SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); + } + + 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()); + + if (!ArrayTy) + return; + + const Type *BaseType = ArrayTy->getElementType().getTypePtr(); + if (EffectiveType->isDependentType() || BaseType->isDependentType()) + return; + + Expr::EvalResult Result; + if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) + return; + + llvm::APSInt index = Result.Val.getInt(); + if (IndexNegated) + 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 (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 = diag::warn_ptr_arith_exceeds_bounds; + if (ASE) + DiagID = diag::warn_array_index_exceeds_bounds; + + DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, + PDiag(DiagID) << index.toString(10, true) + << size.toString(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) << index.toString(10, true) + << IndexExpr->getSourceRange()); + } + + if (!ND) { + // Try harder to find a NamedDecl to point at in the note. + while (const ArraySubscriptExpr *ASE = + dyn_cast(BaseExpr)) + BaseExpr = ASE->getBase()->IgnoreParenCasts(); + if (const DeclRefExpr *DRE = dyn_cast(BaseExpr)) + ND = DRE->getDecl(); + if (const MemberExpr *ME = dyn_cast(BaseExpr)) + ND = ME->getMemberDecl(); + } + + if (ND) + DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, + PDiag(diag::note_array_index_out_of_bounds) + << ND->getDeclName()); + } + + 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(); + llvm::APSInt Value; + VarWillBeReased = + (RHS && RHS->isIntegerConstantExpr(Value, 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 whitelist '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 & ObjCPropertyDecl::OBJC_PR_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 & ObjCPropertyDecl::OBJC_PR_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 & ObjCPropertyDecl::OBJC_PR_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 wether 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 wether 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 (ME->isArrow()) + BaseType = BaseType->getPointeeType(); + RecordDecl *RD = BaseType->getAs()->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)); + } +diff --git a/clang/test/Sema/conversion.c b/clang/test/Sema/conversion.c +index 07b22a8a648..a07c48735ef 100644 +--- a/clang/test/Sema/conversion.c ++++ b/clang/test/Sema/conversion.c +@@ -1,450 +1,450 @@ + // RUN: %clang_cc1 -fsyntax-only -verify -Wconversion \ + // RUN: -nostdsysteminc -nobuiltininc -isystem %S/Inputs \ + // RUN: -triple x86_64-apple-darwin %s -Wno-unreachable-code + + #include + + #define BIG 0x7f7f7f7f7f7f7f7fL + + void test0(char c, short s, int i, long l, long long ll) { + c = c; + c = s; // expected-warning {{implicit conversion loses integer precision}} + c = i; // expected-warning {{implicit conversion loses integer precision}} + c = l; // expected-warning {{implicit conversion loses integer precision}} + s = c; + s = s; + s = i; // expected-warning {{implicit conversion loses integer precision}} + s = l; // expected-warning {{implicit conversion loses integer precision}} + i = c; + i = s; + i = i; + i = l; // expected-warning {{implicit conversion loses integer precision}} + l = c; + l = s; + l = i; + l = l; + + c = (char) 0; + c = (short) 0; + c = (int) 0; + c = (long) 0; + s = (char) 0; + s = (short) 0; + s = (int) 0; + s = (long) 0; + i = (char) 0; + i = (short) 0; + i = (int) 0; + i = (long) 0; + l = (char) 0; + l = (short) 0; + l = (int) 0; + l = (long) 0; + + c = (char) BIG; + c = (short) BIG; // expected-warning {{implicit conversion from 'short' to 'char' changes value}} + c = (int) BIG; // expected-warning {{implicit conversion from 'int' to 'char' changes value}} + c = (long) BIG; // expected-warning {{implicit conversion from 'long' to 'char' changes value}} + s = (char) BIG; + s = (short) BIG; + s = (int) BIG; // expected-warning {{implicit conversion from 'int' to 'short' changes value}} + s = (long) BIG; // expected-warning {{implicit conversion from 'long' to 'short' changes value}} + i = (char) BIG; + i = (short) BIG; + i = (int) BIG; + i = (long) BIG; // expected-warning {{implicit conversion from 'long' to 'int' changes value}} + l = (char) BIG; + l = (short) BIG; + l = (int) BIG; + l = (long) BIG; + } + + char test1(long long ll) { + return (long long) ll; // expected-warning {{implicit conversion loses integer precision}} + } + char test1_a(long long ll) { + return (long) ll; // expected-warning {{implicit conversion loses integer precision}} + } + char test1_b(long long ll) { + return (int) ll; // expected-warning {{implicit conversion loses integer precision}} + } + char test1_c(long long ll) { + return (short) ll; // expected-warning {{implicit conversion loses integer precision}} + } + char test1_d(long long ll) { + return (char) ll; + } + char test1_e(long long ll) { + return (long long) BIG; // expected-warning {{implicit conversion from 'long long' to 'char' changes value}} + } + char test1_f(long long ll) { + return (long) BIG; // expected-warning {{implicit conversion from 'long' to 'char' changes value}} + } + char test1_g(long long ll) { + return (int) BIG; // expected-warning {{implicit conversion from 'int' to 'char' changes value}} + } + char test1_h(long long ll) { + return (short) BIG; // expected-warning {{implicit conversion from 'short' to 'char' changes value}} + } + char test1_i(long long ll) { + return (char) BIG; + } + + short test2(long long ll) { + return (long long) ll; // expected-warning {{implicit conversion loses integer precision}} + } + short test2_a(long long ll) { + return (long) ll; // expected-warning {{implicit conversion loses integer precision}} + } + short test2_b(long long ll) { + return (int) ll; // expected-warning {{implicit conversion loses integer precision}} + } + short test2_c(long long ll) { + return (short) ll; + } + short test2_d(long long ll) { + return (char) ll; + } + short test2_e(long long ll) { + return (long long) BIG; // expected-warning {{implicit conversion from 'long long' to 'short' changes value}} + } + short test2_f(long long ll) { + return (long) BIG; // expected-warning {{implicit conversion from 'long' to 'short' changes value}} + } + short test2_g(long long ll) { + return (int) BIG; // expected-warning {{implicit conversion from 'int' to 'short' changes value}} + } + short test2_h(long long ll) { + return (short) BIG; + } + short test2_i(long long ll) { + return (char) BIG; + } + + int test3(long long ll) { + return (long long) ll; // expected-warning {{implicit conversion loses integer precision}} + } + int test3_b(long long ll) { + return (long) ll; // expected-warning {{implicit conversion loses integer precision}} + } + int test3_c(long long ll) { + return (int) ll; + } + int test3_d(long long ll) { + return (short) ll; + } + int test3_e(long long ll) { + return (char) ll; + } + int test3_f(long long ll) { + return (long long) BIG; // expected-warning {{implicit conversion from 'long long' to 'int' changes value}} + } + int test3_g(long long ll) { + return (long) BIG; // expected-warning {{implicit conversion from 'long' to 'int' changes value}} + } + int test3_h(long long ll) { + return (int) BIG; + } + int test3_i(long long ll) { + return (short) BIG; + } + int test3_j(long long ll) { + return (char) BIG; + } + + long test4(long long ll) { + return (long long) ll; + } + long test4_a(long long ll) { + return (long) ll; + } + long test4_b(long long ll) { + return (int) ll; + } + long test4_c(long long ll) { + return (short) ll; + } + long test4_d(long long ll) { + return (char) ll; + } + long test4_e(long long ll) { + return (long long) BIG; + } + long test4_f(long long ll) { + return (long) BIG; + } + long test4_g(long long ll) { + return (int) BIG; + } + long test4_h(long long ll) { + return (short) BIG; + } + long test4_i(long long ll) { + return (char) BIG; + } + + long long test5(long long ll) { + return (long long) ll; + return (long) ll; + return (int) ll; + return (short) ll; + return (char) ll; + return (long long) BIG; + return (long) BIG; + return (int) BIG; + return (short) BIG; + return (char) BIG; + } + + void takes_char(char); + void takes_short(short); + void takes_int(int); + void takes_long(long); + void takes_longlong(long long); + void takes_float(float); + void takes_double(double); + void takes_longdouble(long double); + + void test6(char v) { + takes_char(v); + takes_short(v); + takes_int(v); + takes_long(v); + takes_longlong(v); + takes_float(v); + takes_double(v); + takes_longdouble(v); + } + + void test7(short v) { + takes_char(v); // expected-warning {{implicit conversion loses integer precision}} + takes_short(v); + takes_int(v); + takes_long(v); + takes_longlong(v); + takes_float(v); + takes_double(v); + takes_longdouble(v); + } + + void test8(int v) { + takes_char(v); // expected-warning {{implicit conversion loses integer precision}} + takes_short(v); // expected-warning {{implicit conversion loses integer precision}} + takes_int(v); + takes_long(v); + takes_longlong(v); +- takes_float(v); ++ takes_float(v); // expected-warning {{implicit conversion from 'int' to 'float' may loses integer precision}} + takes_double(v); + takes_longdouble(v); + } + + void test9(long v) { + takes_char(v); // expected-warning {{implicit conversion loses integer precision}} + takes_short(v); // expected-warning {{implicit conversion loses integer precision}} + takes_int(v); // expected-warning {{implicit conversion loses integer precision}} + takes_long(v); + takes_longlong(v); +- takes_float(v); +- takes_double(v); ++ takes_float(v); // expected-warning {{implicit conversion from 'long' to 'float' may loses integer precision}} ++ takes_double(v); // expected-warning {{implicit conversion from 'long' to 'double' may loses integer precision}} + takes_longdouble(v); + } + + void test10(long long v) { + takes_char(v); // expected-warning {{implicit conversion loses integer precision}} + takes_short(v); // expected-warning {{implicit conversion loses integer precision}} + takes_int(v); // expected-warning {{implicit conversion loses integer precision}} + takes_long(v); + takes_longlong(v); +- takes_float(v); +- takes_double(v); ++ takes_float(v); // expected-warning {{implicit conversion from 'long long' to 'float' may loses integer precision}} ++ takes_double(v); // expected-warning {{implicit conversion from 'long long' to 'double' may loses integer precision}} + takes_longdouble(v); + } + + void test11(float v) { + takes_char(v); // expected-warning {{implicit conversion turns floating-point number into integer}} + takes_short(v); // expected-warning {{implicit conversion turns floating-point number into integer}} + takes_int(v); // expected-warning {{implicit conversion turns floating-point number into integer}} + takes_long(v); // expected-warning {{implicit conversion turns floating-point number into integer}} + takes_longlong(v); // expected-warning {{implicit conversion turns floating-point number into integer}} + takes_float(v); + takes_double(v); + takes_longdouble(v); + } + + void test12(double v) { + takes_char(v); // expected-warning {{implicit conversion turns floating-point number into integer}} + takes_short(v); // expected-warning {{implicit conversion turns floating-point number into integer}} + takes_int(v); // expected-warning {{implicit conversion turns floating-point number into integer}} + takes_long(v); // expected-warning {{implicit conversion turns floating-point number into integer}} + takes_longlong(v); // expected-warning {{implicit conversion turns floating-point number into integer}} + takes_float(v); // expected-warning {{implicit conversion loses floating-point precision}} + takes_double(v); + takes_longdouble(v); + } + + void test13(long double v) { + takes_char(v); // expected-warning {{implicit conversion turns floating-point number into integer}} + takes_short(v); // expected-warning {{implicit conversion turns floating-point number into integer}} + takes_int(v); // expected-warning {{implicit conversion turns floating-point number into integer}} + takes_long(v); // expected-warning {{implicit conversion turns floating-point number into integer}} + takes_longlong(v); // expected-warning {{implicit conversion turns floating-point number into integer}} + takes_float(v); // expected-warning {{implicit conversion loses floating-point precision}} + takes_double(v); // expected-warning {{implicit conversion loses floating-point precision}} + takes_longdouble(v); + } + + void test14(long l) { + // Fine because of the boolean whitelist. + char c; + c = (l == 4); + c = ((l <= 4) && (l >= 0)); + c = ((l <= 4) && (l >= 0)) || (l > 20); + } + + void test15(char c) { + c = c + 1 + c * 2; + c = (short) c + 1 + c * 2; // expected-warning {{implicit conversion loses integer precision}} + } + + // PR 5422 + extern void *test16_external; + void test16(void) { + int a = (unsigned long) &test16_external; // expected-warning {{implicit conversion loses integer precision}} + } + + // PR 5938 + void test17() { + union { + unsigned long long a : 8; + unsigned long long b : 32; + unsigned long long c; + } U; + + unsigned int x; + x = U.a; + x = U.b; + x = U.c; // expected-warning {{implicit conversion loses integer precision}} + } + + // PR 5939 + void test18() { + union { + unsigned long long a : 1; + unsigned long long b; + } U; + + int x; + x = (U.a ? 0 : 1); + x = (U.b ? 0 : 1); + } + + // None of these should warn. + unsigned char test19(unsigned long u64) { + unsigned char x1 = u64 & 0xff; + unsigned char x2 = u64 >> 56; + + unsigned char mask = 0xee; + unsigned char x3 = u64 & mask; + return x1 + x2 + x3; + } + + // + void test_7631400(void) { + // This should show up despite the caret being inside a macro substitution + char s = LONG_MAX; // expected-warning {{implicit conversion from 'long' to 'char' changes value}} + } + + // : assertion for compound operators with non-integral RHS + void f7676608(int); + void test_7676608(void) { + float q = 0.7f; + char c = 5; + f7676608(c *= q); // expected-warning {{conversion}} + } + + // + void test_7904686(void) { + const int i = -1; + unsigned u1 = i; // expected-warning {{implicit conversion changes signedness}} + u1 = i; // expected-warning {{implicit conversion changes signedness}} + + unsigned u2 = -1; // expected-warning {{implicit conversion changes signedness}} + u2 = -1; // expected-warning {{implicit conversion changes signedness}} + } + + // : don't warn about conversions required by + // contexts in system headers + void test_8232669(void) { + unsigned bitset[20]; + SETBIT(bitset, 0); + + unsigned y = 50; + SETBIT(bitset, y); + + #define USER_SETBIT(set,bit) do { int i = bit; set[i/(8*sizeof(set[0]))] |= (1 << (i%(8*sizeof(set)))); } while(0) + USER_SETBIT(bitset, 0); // expected-warning 2 {{implicit conversion changes signedness}} + } + + // + enum E8559831a { E8559831a_val }; + enum E8559831b { E8559831b_val }; + typedef enum { E8559831c_val } E8559831c; + enum { E8559831d_val } value_d; + + void test_8559831_a(enum E8559831a value); + void test_8559831(enum E8559831b value_a, E8559831c value_c) { + test_8559831_a(value_a); // expected-warning{{implicit conversion from enumeration type 'enum E8559831b' to different enumeration type 'enum E8559831a'}} + enum E8559831a a1 = value_a; // expected-warning{{implicit conversion from enumeration type 'enum E8559831b' to different enumeration type 'enum E8559831a'}} + a1 = value_a; // expected-warning{{implicit conversion from enumeration type 'enum E8559831b' to different enumeration type 'enum E8559831a'}} + + test_8559831_a(E8559831b_val); // expected-warning{{implicit conversion from enumeration type 'enum E8559831b' to different enumeration type 'enum E8559831a'}} + enum E8559831a a1a = E8559831b_val; // expected-warning{{implicit conversion from enumeration type 'enum E8559831b' to different enumeration type 'enum E8559831a'}} + a1 = E8559831b_val; // expected-warning{{implicit conversion from enumeration type 'enum E8559831b' to different enumeration type 'enum E8559831a'}} + + test_8559831_a(value_c); // expected-warning{{implicit conversion from enumeration type 'E8559831c' to different enumeration type 'enum E8559831a'}} + enum E8559831a a2 = value_c; // expected-warning{{implicit conversion from enumeration type 'E8559831c' to different enumeration type 'enum E8559831a'}} + a2 = value_c; // expected-warning{{implicit conversion from enumeration type 'E8559831c' to different enumeration type 'enum E8559831a'}} + + test_8559831_a(value_d); + enum E8559831a a3 = value_d; + a3 = value_d; + } + + void test26(int si, long sl) { + si = sl % sl; // expected-warning {{implicit conversion loses integer precision: 'long' to 'int'}} + si = sl % si; + si = si % sl; + si = si / sl; + si = sl / si; // expected-warning {{implicit conversion loses integer precision: 'long' to 'int'}} + } + + // rdar://16502418 + typedef unsigned short uint16_t; + typedef unsigned int uint32_t; + typedef __attribute__ ((ext_vector_type(16),__aligned__(32))) uint16_t ushort16; + typedef __attribute__ ((ext_vector_type( 8),__aligned__( 32))) uint32_t uint8; + + void test27(ushort16 constants) { + uint8 pairedConstants = (uint8) constants; + ushort16 crCbScale = pairedConstants.s4; // expected-warning {{implicit conversion loses integer precision: 'uint32_t' (aka 'unsigned int') to 'ushort16'}} + ushort16 brBias = pairedConstants.s6; // expected-warning {{implicit conversion loses integer precision: 'uint32_t' (aka 'unsigned int') to 'ushort16'}} + } + + + float double2float_test1(double a) { + return a; // expected-warning {{implicit conversion loses floating-point precision: 'double' to 'float'}} + } + + void double2float_test2(double a, float *b) { + *b += a; // expected-warning {{implicit conversion when assigning computation result loses floating-point precision: 'double' to 'float'}} + } + + float sinf (float x); + double double2float_test3(double a) { + return sinf(a); // expected-warning {{implicit conversion loses floating-point precision: 'double' to 'float'}} + } + + float double2float_test4(double a, float b) { + b -= a; // expected-warning {{implicit conversion when assigning computation result loses floating-point precision: 'double' to 'float'}} + return b; + } +diff --git a/clang/test/Sema/ext_vector_casts.c b/clang/test/Sema/ext_vector_casts.c +index 6aaedbe7fd1..f647c17d181 100644 +--- a/clang/test/Sema/ext_vector_casts.c ++++ b/clang/test/Sema/ext_vector_casts.c +@@ -1,126 +1,126 @@ + // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -fsyntax-only -verify -fno-lax-vector-conversions -Wconversion %s + + typedef __attribute__((ext_vector_type(8))) _Bool BoolVector; // expected-error {{invalid vector element type '_Bool'}} + + typedef __attribute__(( ext_vector_type(2) )) float float2; + typedef __attribute__(( ext_vector_type(3) )) float float3; + typedef __attribute__(( ext_vector_type(4) )) int int4; + typedef __attribute__(( ext_vector_type(8) )) short short8; + typedef __attribute__(( ext_vector_type(4) )) float float4; + typedef float t3 __attribute__ ((vector_size (16))); + typedef __typeof__(sizeof(int)) size_t; + typedef unsigned long ulong2 __attribute__ ((ext_vector_type(2))); + typedef size_t stride4 __attribute__((ext_vector_type(4))); + + static void test() { + float2 vec2; + float3 vec3; + float4 vec4, vec4_2; + int4 ivec4; + short8 ish8; + t3 vec4_3; + int *ptr; + int i; + + vec3 += vec2; // expected-error {{cannot convert between vector values of different size}} + vec4 += vec3; // expected-error {{cannot convert between vector values of different size}} + + vec4 = 5.0f; + vec4 = (float4)5.0f; + vec4 = (float4)5; + vec4 = (float4)vec4_3; + + ivec4 = (int4)5.0f; + ivec4 = (int4)5; + ivec4 = (int4)vec4_3; + + i = (int)ivec4; // expected-error {{invalid conversion between vector type 'int4' (vector of 4 'int' values) and integer type 'int' of different size}} + i = ivec4; // expected-error {{assigning to 'int' from incompatible type 'int4' (vector of 4 'int' values)}} + + ivec4 = (int4)ptr; // expected-error {{invalid conversion between vector type 'int4' (vector of 4 'int' values) and scalar type 'int *'}} + + vec4 = (float4)vec2; // expected-error {{invalid conversion between ext-vector type 'float4' (vector of 4 'float' values) and 'float2' (vector of 2 'float' values)}} + + ish8 += 5; + ivec4 *= 5; + vec4 /= 5.2f; + vec4 %= 4; // expected-error {{invalid operands to binary expression ('float4' (vector of 4 'float' values) and 'int')}} + ivec4 %= 4; + ivec4 += vec4; // expected-error {{cannot convert between vector values of different size ('int4' (vector of 4 'int' values) and 'float4' (vector of 4 'float' values))}} + ivec4 += (int4)vec4; + ivec4 -= ivec4; + ivec4 |= ivec4; + ivec4 += ptr; // expected-error {{cannot convert between vector and non-scalar values ('int4' (vector of 4 'int' values) and 'int *')}} + } + + typedef __attribute__(( ext_vector_type(2) )) float2 vecfloat2; // expected-error{{invalid vector element type 'float2' (vector of 2 'float' values)}} + + void inc(float2 f2) { + f2++; // expected-error{{cannot increment value of type 'float2' (vector of 2 'float' values)}} + __real f2; // expected-error{{invalid type 'float2' (vector of 2 'float' values) to __real operator}} + } + + typedef enum + { + uchar_stride = 1, + uchar4_stride = 4, + ushort4_stride = 8, + short4_stride = 8, + uint4_stride = 16, + int4_stride = 16, + float4_stride = 16, + } PixelByteStride; + + stride4 RDar15091442_get_stride4(int4 x, PixelByteStride pixelByteStride); + stride4 RDar15091442_get_stride4(int4 x, PixelByteStride pixelByteStride) + { + stride4 stride; + // This previously caused an assertion failure. + stride.lo = ((ulong2) x) * pixelByteStride; // no-warning + return stride; + } + + // rdar://16196902 + typedef __attribute__((ext_vector_type(4))) float float32x4_t; + + typedef float C3DVector3 __attribute__((ext_vector_type(3))); + + extern float32x4_t vabsq_f32(float32x4_t __a); + + C3DVector3 Func(const C3DVector3 a) { + return (C3DVector3)vabsq_f32((float32x4_t)a); // expected-error {{invalid conversion between ext-vector type 'float32x4_t' (vector of 4 'float' values) and 'C3DVector3' (vector of 3 'float' values)}} + } + + // rdar://16350802 + typedef double double2 __attribute__ ((ext_vector_type(2))); + + static void splats(int i, long l, __uint128_t t, float f, double d) { + short8 vs = 0; + int4 vi = i; + ulong2 vl = (unsigned long)l; + float2 vf = f; + double2 vd = d; + + vs = 65536 + vs; // expected-warning {{implicit conversion from 'int' to 'short8' (vector of 8 'short' values) changes value from 65536 to 0}} + vs = vs + i; // expected-warning {{implicit conversion loses integer precision}} + vs = vs + 1; + vs = vs + 1.f; // expected-error {{cannot convert between vector values of different size}} + + vi = l + vi; // expected-warning {{implicit conversion loses integer precision}} + vi = 1 + vi; + vi = vi + 2.0; // expected-error {{cannot convert between vector values of different size}} + vi = vi + 0xffffffff; // expected-warning {{implicit conversion changes signedness}} + + vl = l + vl; // expected-warning {{implicit conversion changes signedness}} + vl = vl + t; // expected-warning {{implicit conversion loses integer precision}} + + vf = 1 + vf; +- vf = l + vf; ++ vf = l + vf; // expected-warning {{implicit conversion from 'long' to 'float2' (vector of 2 'float' values) may loses integer precision}} + vf = 2.0 + vf; + vf = d + vf; // expected-warning {{implicit conversion loses floating-point precision}} +- vf = vf + 0xffffffff; ++ vf = vf + 0xffffffff; // expected-warning {{implicit conversion from 'unsigned int' to 'float2' (vector of 2 'float' values) changes value}} + vf = vf + 2.1; // expected-warning {{implicit conversion loses floating-point precision}} + +- vd = l + vd; +- vd = vd + t; ++ vd = l + vd; // expected-warning {{implicit conversion from 'long' to 'double2' (vector of 2 'double' values) may loses integer precision}} ++ vd = vd + t; // expected-warning {{implicit conversion from '__uint128_t' (aka 'unsigned __int128') to 'double2' (vector of 2 'double' values) may loses integer precision}} + } +diff --git a/clang/test/Sema/implicit-float-conversion.c b/clang/test/Sema/implicit-float-conversion.c +new file mode 100644 +index 00000000000..8456dca4de4 +--- /dev/null ++++ b/clang/test/Sema/implicit-float-conversion.c +@@ -0,0 +1,30 @@ ++// RUN: %clang_cc1 %s -verify -Wno-conversion -Wimplicit-float-conversion ++ ++ ++long testReturn(long a, float b) { ++ return a + b; // expected-warning {{implicit conversion from 'long' to 'float' may loses integer precision}} ++} ++ ++ ++void testAssignment() { ++ float f = 222222; ++ double b = 222222222222L; ++ ++ float ff = 222222222222L; // expected-warning {{implicit conversion from 'long' to 'float' changes value}} ++ ++ long l = 222222222222L; ++ float fff = l; // expected-warning {{implicit conversion from 'long' to 'float' may loses integer precision}} ++} ++ ++ ++void testExpression() { ++ float a = 0.0f; ++ float b = 222222222222L + a; // expected-warning {{implicit conversion from 'long' to 'float' changes value}} ++ float c = 22222222 + 22222223; // expected-warning {{implicit conversion from 'int' to 'float' changes value}} ++ ++ int i = 0; ++ float d = i + a; // expected-warning {{implicit conversion from 'int' to 'float' may loses integer precision}} ++ ++ double e = 0.0; ++ double f = i + e; ++}