[cfe-commits] r136181 - in /cfe/trunk: include/clang/Basic/DiagnosticGroups.td include/clang/Basic/DiagnosticSemaKinds.td include/clang/Sema/Initialization.h include/clang/Sema/Sema.h lib/Sema/SemaInit.cpp test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x-fixits.cpp test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x.cpp
Jeffrey Yasskin
jyasskin at google.com
Tue Jul 26 16:20:31 PDT 2011
Author: jyasskin
Date: Tue Jul 26 18:20:30 2011
New Revision: 136181
URL: http://llvm.org/viewvc/llvm-project?rev=136181&view=rev
Log:
This patch implements as much of the narrowing conversion error specified by
[dcl.init.list] as is possible without generalized initializer lists or full
constant expression support, and adds a c++0x-compat warning in C++98 mode.
The FixIt currently uses a typedef's basename without qualification, which is
likely to be incorrect on some code. If it's incorrect on too much code, we
should write a function to get the string that refers to a type from a
particular context.
The warning is currently off by default. I'll fix LLVM and clang before turning
it on.
Added:
cfe/trunk/test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x-fixits.cpp
cfe/trunk/test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x.cpp
Modified:
cfe/trunk/include/clang/Basic/DiagnosticGroups.td
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/include/clang/Sema/Initialization.h
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Sema/SemaInit.cpp
Modified: cfe/trunk/include/clang/Basic/DiagnosticGroups.td
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?rev=136181&r1=136180&r2=136181&view=diff
==============================================================================
--- cfe/trunk/include/clang/Basic/DiagnosticGroups.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticGroups.td Tue Jul 26 18:20:30 2011
@@ -55,8 +55,9 @@
def FormatZeroLength : DiagGroup<"format-zero-length">;
def CXXHexFloats : DiagGroup<"c++-hex-floats">;
+def CXX0xNarrowing : DiagGroup<"c++0x-narrowing">;
-def CXX0xCompat : DiagGroup<"c++0x-compat", [CXXHexFloats]>;
+def CXX0xCompat : DiagGroup<"c++0x-compat", [CXXHexFloats, CXX0xNarrowing]>;
def : DiagGroup<"effc++">;
def ExitTimeDestructors : DiagGroup<"exit-time-destructors">;
def FourByteMultiChar : DiagGroup<"four-char-constants">;
Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=136181&r1=136180&r2=136181&view=diff
==============================================================================
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Tue Jul 26 18:20:30 2011
@@ -2464,6 +2464,21 @@
def err_illegal_initializer : Error<
"illegal initializer (only variables can be initialized)">;
def err_illegal_initializer_type : Error<"illegal initializer type %0">;
+def err_init_list_variable_narrowing : Error<
+ "non-constant-expression cannot be narrowed from type %0 to %1 in "
+ "initializer list">;
+def err_init_list_constant_narrowing : Error<
+ "constant expression evaluates to %0 which cannot be narrowed to type %1">;
+def warn_init_list_variable_narrowing : Warning<
+ "non-constant-expression cannot be narrowed from type %0 to %1 in "
+ "initializer list in C++0x">,
+ InGroup<CXX0xNarrowing>, DefaultIgnore;
+def warn_init_list_constant_narrowing : Warning<
+ "constant expression evaluates to %0 which cannot be narrowed to type %1 in "
+ "C++0x">,
+ InGroup<CXX0xNarrowing>, DefaultIgnore;
+def note_init_list_narrowing_override : Note<
+ "override this message by inserting an explicit cast">;
def err_init_objc_class : Error<
"cannot initialize Objective-C class type %0">;
def err_implicit_empty_initializer : Error<
Modified: cfe/trunk/include/clang/Sema/Initialization.h
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Initialization.h?rev=136181&r1=136180&r2=136181&view=diff
==============================================================================
--- cfe/trunk/include/clang/Sema/Initialization.h (original)
+++ cfe/trunk/include/clang/Sema/Initialization.h Tue Jul 26 18:20:30 2011
@@ -732,7 +732,18 @@
/// \brief Determine whether this initialization is direct call to a
/// constructor.
bool isConstructorInitialization() const;
-
+
+ // \brief Returns whether the last step in this initialization sequence is a
+ // narrowing conversion, defined by C++0x [dcl.init.list]p7.
+ //
+ // If this function returns true, *isInitializerConstant will be set to
+ // describe whether *Initializer was a constant expression. If
+ // *isInitializerConstant is set to true, *ConstantValue will be set to the
+ // evaluated value of *Initializer.
+ bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
+ bool *isInitializerConstant,
+ APValue *ConstantValue) const;
+
/// \brief Add a new step in the initialization that resolves the address
/// of an overloaded function to a specific function declaration.
///
Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=136181&r1=136180&r2=136181&view=diff
==============================================================================
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Tue Jul 26 18:20:30 2011
@@ -1342,7 +1342,8 @@
ExprResult Init);
ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
SourceLocation EqualLoc,
- ExprResult Init);
+ ExprResult Init,
+ bool TopLevelOfInitList = false);
ExprResult PerformObjectArgumentInitialization(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=136181&r1=136180&r2=136181&view=diff
==============================================================================
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Tue Jul 26 18:20:30 2011
@@ -24,6 +24,7 @@
#include "clang/AST/ExprObjC.h"
#include "clang/AST/TypeLoc.h"
#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/raw_ostream.h"
#include <map>
using namespace clang;
@@ -778,7 +779,8 @@
// We cannot initialize this element, so let
// PerformCopyInitialization produce the appropriate diagnostic.
SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
- SemaRef.Owned(expr));
+ SemaRef.Owned(expr),
+ /*TopLevelOfInitList=*/true);
hadError = true;
++Index;
++StructuredIndex;
@@ -820,7 +822,8 @@
ExprResult Result =
SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
- SemaRef.Owned(expr));
+ SemaRef.Owned(expr),
+ /*TopLevelOfInitList=*/true);
Expr *ResultExpr = 0;
@@ -859,7 +862,8 @@
ExprResult Result =
SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
- SemaRef.Owned(expr));
+ SemaRef.Owned(expr),
+ /*TopLevelOfInitList=*/true);
if (Result.isInvalid())
hadError = true;
@@ -908,7 +912,8 @@
if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
ExprResult Result =
SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
- SemaRef.Owned(Init));
+ SemaRef.Owned(Init),
+ /*TopLevelOfInitList=*/true);
Expr *ResultExpr = 0;
if (Result.isInvalid())
@@ -2197,6 +2202,158 @@
return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
}
+bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
+ const Expr *Initializer,
+ bool *isInitializerConstant,
+ APValue *ConstantValue) const {
+ if (Steps.empty() || Initializer->isValueDependent())
+ return false;
+
+ const Step &LastStep = Steps.back();
+ if (LastStep.Kind != SK_ConversionSequence)
+ return false;
+
+ const ImplicitConversionSequence &ICS = *LastStep.ICS;
+ const StandardConversionSequence *SCS = NULL;
+ switch (ICS.getKind()) {
+ case ImplicitConversionSequence::StandardConversion:
+ SCS = &ICS.Standard;
+ break;
+ case ImplicitConversionSequence::UserDefinedConversion:
+ SCS = &ICS.UserDefined.After;
+ break;
+ case ImplicitConversionSequence::AmbiguousConversion:
+ case ImplicitConversionSequence::EllipsisConversion:
+ case ImplicitConversionSequence::BadConversion:
+ return false;
+ }
+
+ // Check if SCS represents a narrowing conversion, according to C++0x
+ // [dcl.init.list]p7:
+ //
+ // A narrowing conversion is an implicit conversion ...
+ ImplicitConversionKind PossibleNarrowing = SCS->Second;
+ QualType FromType = SCS->getToType(0);
+ QualType ToType = SCS->getToType(1);
+ switch (PossibleNarrowing) {
+ // * from a floating-point type to an integer type, or
+ //
+ // * from an integer type or unscoped enumeration type to a floating-point
+ // type, except where the source is a constant expression and the actual
+ // value after conversion will fit into the target type and will produce
+ // the original value when converted back to the original type, or
+ case ICK_Floating_Integral:
+ if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
+ *isInitializerConstant = false;
+ return true;
+ } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
+ llvm::APSInt IntConstantValue;
+ if (Initializer &&
+ Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
+ // Convert the integer to the floating type.
+ llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
+ Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
+ llvm::APFloat::rmNearestTiesToEven);
+ // And back.
+ llvm::APSInt ConvertedValue = IntConstantValue;
+ bool ignored;
+ Result.convertToInteger(ConvertedValue,
+ llvm::APFloat::rmTowardZero, &ignored);
+ // If the resulting value is different, this was a narrowing conversion.
+ if (IntConstantValue != ConvertedValue) {
+ *isInitializerConstant = true;
+ *ConstantValue = APValue(IntConstantValue);
+ return true;
+ }
+ } else {
+ // Variables are always narrowings.
+ *isInitializerConstant = false;
+ return true;
+ }
+ }
+ return false;
+
+ // * from long double to double or float, or from double to float, except
+ // where the source is a constant expression and the actual value after
+ // conversion is within the range of values that can be represented (even
+ // if it cannot be represented exactly), or
+ case ICK_Floating_Conversion:
+ if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
+ // FromType is larger than ToType.
+ Expr::EvalResult InitializerValue;
+ // FIXME: Check whether Initializer is a constant expression according
+ // to C++0x [expr.const], rather than just whether it can be folded.
+ if (Initializer->Evaluate(InitializerValue, Ctx) &&
+ !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
+ // Constant! (Except for FIXME above.)
+ llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
+ // Convert the source value into the target type.
+ bool ignored;
+ llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
+ Ctx.getFloatTypeSemantics(ToType),
+ llvm::APFloat::rmNearestTiesToEven, &ignored);
+ // If there was no overflow, the source value is within the range of
+ // values that can be represented.
+ if (ConvertStatus & llvm::APFloat::opOverflow) {
+ *isInitializerConstant = true;
+ *ConstantValue = InitializerValue.Val;
+ return true;
+ }
+ } else {
+ *isInitializerConstant = false;
+ return true;
+ }
+ }
+ return false;
+
+ // * from an integer type or unscoped enumeration type to an integer type
+ // that cannot represent all the values of the original type, except where
+ // the source is a constant expression and the actual value after
+ // conversion will fit into the target type and will produce the original
+ // value when converted back to the original type.
+ case ICK_Integral_Conversion: {
+ assert(FromType->isIntegralOrUnscopedEnumerationType());
+ assert(ToType->isIntegralOrUnscopedEnumerationType());
+ const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
+ const unsigned FromWidth = Ctx.getIntWidth(FromType);
+ const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
+ const unsigned ToWidth = Ctx.getIntWidth(ToType);
+
+ if (FromWidth > ToWidth ||
+ (FromWidth == ToWidth && FromSigned != ToSigned)) {
+ // Not all values of FromType can be represented in ToType.
+ llvm::APSInt InitializerValue;
+ if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
+ *isInitializerConstant = true;
+ *ConstantValue = APValue(InitializerValue);
+
+ // Add a bit to the InitializerValue so we don't have to worry about
+ // signed vs. unsigned comparisons.
+ InitializerValue = InitializerValue.extend(
+ InitializerValue.getBitWidth() + 1);
+ // Convert the initializer to and from the target width and signed-ness.
+ llvm::APSInt ConvertedValue = InitializerValue;
+ ConvertedValue = ConvertedValue.trunc(ToWidth);
+ ConvertedValue.setIsSigned(ToSigned);
+ ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
+ ConvertedValue.setIsSigned(InitializerValue.isSigned());
+ // If the result is different, this was a narrowing conversion.
+ return ConvertedValue != InitializerValue;
+ } else {
+ // Variables are always narrowings.
+ *isInitializerConstant = false;
+ return true;
+ }
+ }
+ return false;
+ }
+
+ default:
+ // Other kinds of conversions are not narrowings.
+ return false;
+ }
+}
+
void InitializationSequence::AddAddressOverloadResolutionStep(
FunctionDecl *Function,
DeclAccessPair Found) {
@@ -4972,6 +5129,51 @@
dump(llvm::errs());
}
+static void DiagnoseNarrowingInInitList(
+ Sema& S, QualType EntityType, const Expr *InitE,
+ bool Constant, const APValue &ConstantValue) {
+ if (Constant) {
+ S.Diag(InitE->getLocStart(),
+ S.getLangOptions().CPlusPlus0x
+ ? diag::err_init_list_constant_narrowing
+ : diag::warn_init_list_constant_narrowing)
+ << InitE->getSourceRange()
+ << ConstantValue
+ << EntityType;
+ } else
+ S.Diag(InitE->getLocStart(),
+ S.getLangOptions().CPlusPlus0x
+ ? diag::err_init_list_variable_narrowing
+ : diag::warn_init_list_variable_narrowing)
+ << InitE->getSourceRange()
+ << InitE->getType()
+ << EntityType;
+
+ llvm::SmallString<128> StaticCast;
+ llvm::raw_svector_ostream OS(StaticCast);
+ OS << "static_cast<";
+ if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
+ // It's important to use the typedef's name if there is one so that the
+ // fixit doesn't break code using types like int64_t.
+ //
+ // FIXME: This will break if the typedef requires qualification. But
+ // getQualifiedNameAsString() includes non-machine-parsable components.
+ OS << TT->getDecl();
+ } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
+ OS << BT->getName(S.getLangOptions());
+ else {
+ // Oops, we didn't find the actual type of the variable. Don't emit a fixit
+ // with a broken cast.
+ return;
+ }
+ OS << ">(";
+ S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
+ << InitE->getSourceRange()
+ << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
+ << FixItHint::CreateInsertion(
+ S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
+}
+
//===----------------------------------------------------------------------===//
// Initialization helper functions
//===----------------------------------------------------------------------===//
@@ -4993,7 +5195,8 @@
ExprResult
Sema::PerformCopyInitialization(const InitializedEntity &Entity,
SourceLocation EqualLoc,
- ExprResult Init) {
+ ExprResult Init,
+ bool TopLevelOfInitList) {
if (Init.isInvalid())
return ExprError();
@@ -5007,5 +5210,13 @@
EqualLoc);
InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Init.release();
+
+ bool Constant = false;
+ APValue Result;
+ if (TopLevelOfInitList &&
+ Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
+ DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
+ Constant, Result);
+ }
return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
}
Added: cfe/trunk/test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x-fixits.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x-fixits.cpp?rev=136181&view=auto
==============================================================================
--- cfe/trunk/test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x-fixits.cpp (added)
+++ cfe/trunk/test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x-fixits.cpp Tue Jul 26 18:20:30 2011
@@ -0,0 +1,33 @@
+// RUN: %clang_cc1 -fsyntax-only -Wc++0x-compat -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s
+
+// Verify that the appropriate fixits are emitted for narrowing conversions in
+// initializer lists.
+
+typedef short int16_t;
+
+void fixits() {
+ int x = 999;
+ struct {char c;} c2 = {x};
+ // CHECK: warning:{{.*}} cannot be narrowed
+ // CHECK: fix-it:{{.*}}:26}:"static_cast<char>("
+ // CHECK: fix-it:{{.*}}:27}:")"
+ struct {int16_t i;} i16 = {70000};
+ // CHECK: warning:{{.*}} cannot be narrowed
+ // CHECK: fix-it:{{.*}}:30}:"static_cast<int16_t>("
+ // CHECK: fix-it:{{.*}}:35}:")"
+}
+
+template<typename T>
+void maybe_shrink_int(T t) {
+ struct {T t;} t2 = {700};
+}
+
+void test_template() {
+ maybe_shrink_int((char)3);
+ // CHECK: warning:{{.*}} cannot be narrowed
+ // CHECK: note:{{.*}} in instantiation
+ // CHECK: note:{{.*}} override
+ // FIXME: This should be static_cast<T>.
+ // CHECK: fix-it:{{.*}}"static_cast<char>("
+ // CHECK: fix-it:{{.*}}")"
+}
Added: cfe/trunk/test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x.cpp?rev=136181&view=auto
==============================================================================
--- cfe/trunk/test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x.cpp (added)
+++ cfe/trunk/test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x.cpp Tue Jul 26 18:20:30 2011
@@ -0,0 +1,156 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++0x -triple x86_64-apple-macosx10.6.7 -verify %s
+
+// Verify that narrowing conversions in initializer lists cause errors in C++0x
+// mode.
+
+void std_example() {
+ int x = 999; // x is not a constant expression
+ const int y = 999;
+ const int z = 99;
+ char c1 = x; // OK, though it might narrow (in this case, it does narrow)
+ char c2{x}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ char c3{y}; // expected-error {{ cannot be narrowed }} expected-note {{override}} expected-warning {{changes value}}
+ char c4{z}; // OK: no narrowing needed
+ unsigned char uc1 = {5}; // OK: no narrowing needed
+ unsigned char uc2 = {-1}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ unsigned int ui1 = {-1}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ signed int si1 =
+ { (unsigned int)-1 }; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ int ii = {2.0}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ float f1 { x }; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ float f2 { 7 }; // OK: 7 can be exactly represented as a float
+ int f(int);
+ int a[] =
+ { 2, f(2), f(2.0) }; // OK: the double-to-int conversion is not at the top level
+}
+
+// Test each rule individually.
+
+template<typename T>
+struct Agg {
+ T t;
+};
+
+// C++0x [dcl.init.list]p7: A narrowing conversion is an implicit conversion
+//
+// * from a floating-point type to an integer type, or
+
+void float_to_int() {
+ Agg<char> a1 = {1.0F}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ Agg<char> a2 = {1.0}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ Agg<char> a3 = {1.0L}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+
+ float f = 1.0;
+ double d = 1.0;
+ long double ld = 1.0;
+ Agg<char> a4 = {f}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ Agg<char> a5 = {d}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ Agg<char> a6 = {ld}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+}
+
+// * from long double to double or float, or from double to float, except where
+// the source is a constant expression and the actual value after conversion
+// is within the range of values that can be represented (even if it cannot be
+// represented exactly), or
+
+void shrink_float() {
+ // These aren't constant expressions.
+ float f = 1.0;
+ double d = 1.0;
+ long double ld = 1.0;
+
+ // Variables.
+ Agg<float> f1 = {f}; // OK (no-op)
+ Agg<float> f2 = {d}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ Agg<float> f3 = {ld}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ // Exact constants.
+ Agg<float> f4 = {1.0}; // OK (double constant represented exactly)
+ Agg<float> f5 = {1.0L}; // OK (long double constant represented exactly)
+ // Inexact but in-range constants.
+ Agg<float> f6 = {0.1}; // OK (double constant in range but rounded)
+ Agg<float> f7 = {0.1L}; // OK (long double constant in range but rounded)
+ // Out of range constants.
+ Agg<float> f8 = {1E50}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ Agg<float> f9 = {1E50L}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ // More complex constant expression.
+ constexpr long double e40 = 1E40L, e30 = 1E30L, e39 = 1E39L;
+ Agg<float> f10 = {e40 - 5 * e39 + e30 - 5 * e39}; // OK
+
+ // Variables.
+ Agg<double> d1 = {f}; // OK (widening)
+ Agg<double> d2 = {d}; // OK (no-op)
+ Agg<double> d3 = {ld}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ // Exact constant.
+ Agg<double> d4 = {1.0L}; // OK (long double constant represented exactly)
+ // Inexact but in-range constant.
+ Agg<double> d5 = {0.1L}; // OK (long double constant in range but rounded)
+ // Out of range constant.
+ Agg<double> d6 = {1E315L}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ // More complex constant expression.
+ constexpr long double e315 = 1E315L, e305 = 1E305L, e314 = 1E314L;
+ Agg<double> d7 = {e315 - 5 * e314 + e305 - 5 * e314}; // OK
+}
+
+// * from an integer type or unscoped enumeration type to a floating-point type,
+// except where the source is a constant expression and the actual value after
+// conversion will fit into the target type and will produce the original
+// value when converted back to the original type, or
+void int_to_float() {
+ // Not a constant expression.
+ char c = 1;
+
+ // Variables. Yes, even though all char's will fit into any floating type.
+ Agg<float> f1 = {c}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ Agg<double> f2 = {c}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ Agg<long double> f3 = {c}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+
+ // Constants.
+ Agg<float> f4 = {12345678}; // OK (exactly fits in a float)
+ Agg<float> f5 = {123456789}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+}
+
+// * from an integer type or unscoped enumeration type to an integer type that
+// cannot represent all the values of the original type, except where the
+// source is a constant expression and the actual value after conversion will
+// fit into the target type and will produce the original value when converted
+// back to the original type.
+void shrink_int() {
+ // Not a constant expression.
+ short s = 1;
+ unsigned short us = 1;
+ Agg<char> c1 = {s}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ Agg<unsigned short> s1 = {s}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ Agg<short> s2 = {us}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+
+ // "that cannot represent all the values of the original type" means that the
+ // validity of the program depends on the relative sizes of integral types.
+ // This test compiles with -m64, so sizeof(int)<sizeof(long)==sizeof(long
+ // long).
+ long l1 = 1;
+ Agg<int> i1 = {l1}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ long long ll = 1;
+ Agg<long> l2 = {ll}; // OK
+
+ // Constants.
+ Agg<char> c2 = {127}; // OK
+ Agg<char> c3 = {300}; // expected-error {{ cannot be narrowed }} expected-note {{override}} expected-warning {{changes value}}
+
+ Agg<int> i2 = {0x7FFFFFFFU}; // OK
+ Agg<int> i3 = {0x80000000U}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ Agg<unsigned int> i4 = {-0x80000000L}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+}
+
+// Be sure that type- and value-dependent expressions in templates get the error
+// too.
+
+template<int I, typename T>
+void maybe_shrink_int(T t) {
+ Agg<short> s1 = {t}; // expected-error {{ cannot be narrowed }} expected-note {{override}}
+ Agg<short> s2 = {I}; // expected-error {{ cannot be narrowed }} expected-note {{override}} expected-warning {{changes value}}
+ Agg<T> t2 = {700}; // expected-error {{ cannot be narrowed }} expected-note {{override}} expected-warning {{changes value}}
+}
+
+void test_template() {
+ maybe_shrink_int<15>((int)3); // expected-note {{in instantiation}}
+ maybe_shrink_int<70000>((char)3); // expected-note {{in instantiation}}
+}
More information about the cfe-commits
mailing list