+ if (V->getType() == DestTy) return (Constant*)V;
+
+ if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
+ if (CE->getOpcode() == Instruction::Cast) {
+ Constant *Op = (Constant*)cast<Constant>(CE->getOperand(0));
+ // Try to not produce a cast of a cast, which is almost always redundant.
+ if (!Op->getType()->isFloatingPoint() &&
+ !CE->getType()->isFloatingPoint() &&
+ !DestTy->getType()->isFloatingPoint()) {
+ unsigned S1 = getSize(Op->getType()), S2 = getSize(CE->getType());
+ unsigned S3 = getSize(DestTy);
+ if (Op->getType() == DestTy && S3 >= S2)
+ return Op;
+ if (S1 >= S2 && S2 >= S3)
+ return ConstantExpr::getCast(Op, DestTy);
+ if (S1 <= S2 && S2 >= S3 && S1 <= S3)
+ return ConstantExpr::getCast(Op, DestTy);
+ }
+ }
+