Skip to content

Commit 7cffb63

Browse files
committed
emit diagnostic when casting a ptr to a small int when doing static initialization (addresses Eli's comments I believe)
llvm-svn: 63562
1 parent e862b3d commit 7cffb63

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

clang/lib/Sema/SemaDecl.cpp

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2055,14 +2055,23 @@ bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
20552055
}
20562056
case Expr::ImplicitCastExprClass:
20572057
case Expr::CStyleCastExprClass: {
2058-
const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
2058+
const CastExpr *CE = cast<CastExpr>(Init);
2059+
const Expr *SubExpr = CE->getSubExpr();
2060+
20592061
if (SubExpr->getType()->isArithmeticType())
20602062
return CheckArithmeticConstantExpression(SubExpr);
20612063

20622064
if (SubExpr->getType()->isPointerType()) {
20632065
const Expr* Base = FindExpressionBaseAddress(SubExpr);
2064-
// If the pointer has a null base, this is an offsetof-like construct
2065-
return Base ? false : CheckAddressConstantExpression(SubExpr);
2066+
if (Base) {
2067+
// the cast is only valid if done to a wide enough type
2068+
if (Context.getTypeSize(CE->getType()) >=
2069+
Context.getTypeSize(SubExpr->getType()))
2070+
return false;
2071+
} else {
2072+
// If the pointer has a null base, this is an offsetof-like construct
2073+
return CheckAddressConstantExpression(SubExpr);
2074+
}
20662075
}
20672076

20682077
InitializerElementNotConstant(Init);

clang/test/Sema/static-init.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,5 @@ struct foo {
1616
};
1717

1818
union bar u[1];
19-
struct foo x = {(int) u}; // no-error
19+
struct foo x = {(long) u}; // no-error
20+
struct foo y = {(char) u}; // expected-error {{initializer element is not a compile-time constant}}

0 commit comments

Comments
 (0)