Skip to content

Commit f6267d3

Browse files
[clang][CGExprConstant] handle implicit widening/narrowing Int-to-Int casts
Consider the following statements: long x = 1; short y = 1; With the following AST: |-VarDecl 0x55d289973730 <x.c:1:1, col:10> col:6 x 'long' cinit | `-ImplicitCastExpr 0x55d289973800 <col:10> 'long' <IntegralCast> | `-IntegerLiteral 0x55d2899737e0 <col:10> 'int' 1 `-VarDecl 0x55d289973830 <line:2:1, col:11> col:7 y 'short' cinit `-ImplicitCastExpr 0x55d2899738b8 <col:11> 'short' <IntegralCast> `-IntegerLiteral 0x55d289973898 <col:11> 'int' 1 Sign or Zero extend or truncate based on the source signedness and destination width. Reviewed By: efriedma Differential Revision: https://reviews.llvm.org/D156466
1 parent 1e15d79 commit f6267d3

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

clang/lib/CodeGen/CGExprConstant.cpp

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1139,6 +1139,24 @@ class ConstExprEmitter :
11391139
case CK_IntToOCLSampler:
11401140
llvm_unreachable("global sampler variables are not generated");
11411141

1142+
case CK_IntegralCast: {
1143+
QualType FromType = subExpr->getType();
1144+
// See also HandleIntToIntCast in ExprConstant.cpp
1145+
if (FromType->isIntegerType())
1146+
if (llvm::Constant *C = Visit(subExpr, FromType))
1147+
if (auto *CI = dyn_cast<llvm::ConstantInt>(C)) {
1148+
unsigned SrcWidth = CGM.getContext().getIntWidth(FromType);
1149+
unsigned DstWidth = CGM.getContext().getIntWidth(destType);
1150+
if (DstWidth == SrcWidth)
1151+
return CI;
1152+
llvm::APInt A = FromType->isSignedIntegerType()
1153+
? CI->getValue().sextOrTrunc(DstWidth)
1154+
: CI->getValue().zextOrTrunc(DstWidth);
1155+
return llvm::ConstantInt::get(CGM.getLLVMContext(), A);
1156+
}
1157+
return nullptr;
1158+
}
1159+
11421160
case CK_Dependent: llvm_unreachable("saw dependent cast!");
11431161

11441162
case CK_BuiltinFnToFnPtr:
@@ -1191,7 +1209,6 @@ class ConstExprEmitter :
11911209
case CK_IntegralComplexToFloatingComplex:
11921210
case CK_PointerToIntegral:
11931211
case CK_PointerToBoolean:
1194-
case CK_IntegralCast:
11951212
case CK_BooleanToSignedIntegral:
11961213
case CK_IntegralToPointer:
11971214
case CK_IntegralToBoolean:

clang/test/CodeGen/global-init.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ struct K {
4949
// CHECK: @yuv_types ={{.*}} global [4 x [6 x i8]] {{\[}}[6 x i8] c"4:0:0\00", [6 x i8] c"4:2:0\00", [6 x i8] c"4:2:2\00", [6 x i8] c"4:4:4\00"]
5050
char yuv_types[4][6]= {"4:0:0","4:2:0","4:2:2","4:4:4"};
5151

52+
unsigned long long x = -1000;
53+
// CHECK: @x ={{.*}} global i64 -1000
54+
unsigned long long uint_max = 4294967295u;
55+
// CHECK: @uint_max ={{.*}} global i64 4294967295
56+
5257

5358
// NOTE: tentative definitions are processed at the end of the translation unit.
5459

0 commit comments

Comments
 (0)