1*9880d681SAndroid Build Coastguard Worker //===- InstCombineCasts.cpp -----------------------------------------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker // The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This file implements the visit functions for cast operations.
11*9880d681SAndroid Build Coastguard Worker //
12*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
13*9880d681SAndroid Build Coastguard Worker
14*9880d681SAndroid Build Coastguard Worker #include "InstCombineInternal.h"
15*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ConstantFolding.h"
16*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/PatternMatch.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetLibraryInfo.h"
19*9880d681SAndroid Build Coastguard Worker using namespace llvm;
20*9880d681SAndroid Build Coastguard Worker using namespace PatternMatch;
21*9880d681SAndroid Build Coastguard Worker
22*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "instcombine"
23*9880d681SAndroid Build Coastguard Worker
24*9880d681SAndroid Build Coastguard Worker /// Analyze 'Val', seeing if it is a simple linear expression.
25*9880d681SAndroid Build Coastguard Worker /// If so, decompose it, returning some value X, such that Val is
26*9880d681SAndroid Build Coastguard Worker /// X*Scale+Offset.
27*9880d681SAndroid Build Coastguard Worker ///
decomposeSimpleLinearExpr(Value * Val,unsigned & Scale,uint64_t & Offset)28*9880d681SAndroid Build Coastguard Worker static Value *decomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
29*9880d681SAndroid Build Coastguard Worker uint64_t &Offset) {
30*9880d681SAndroid Build Coastguard Worker if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
31*9880d681SAndroid Build Coastguard Worker Offset = CI->getZExtValue();
32*9880d681SAndroid Build Coastguard Worker Scale = 0;
33*9880d681SAndroid Build Coastguard Worker return ConstantInt::get(Val->getType(), 0);
34*9880d681SAndroid Build Coastguard Worker }
35*9880d681SAndroid Build Coastguard Worker
36*9880d681SAndroid Build Coastguard Worker if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
37*9880d681SAndroid Build Coastguard Worker // Cannot look past anything that might overflow.
38*9880d681SAndroid Build Coastguard Worker OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
39*9880d681SAndroid Build Coastguard Worker if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) {
40*9880d681SAndroid Build Coastguard Worker Scale = 1;
41*9880d681SAndroid Build Coastguard Worker Offset = 0;
42*9880d681SAndroid Build Coastguard Worker return Val;
43*9880d681SAndroid Build Coastguard Worker }
44*9880d681SAndroid Build Coastguard Worker
45*9880d681SAndroid Build Coastguard Worker if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
46*9880d681SAndroid Build Coastguard Worker if (I->getOpcode() == Instruction::Shl) {
47*9880d681SAndroid Build Coastguard Worker // This is a value scaled by '1 << the shift amt'.
48*9880d681SAndroid Build Coastguard Worker Scale = UINT64_C(1) << RHS->getZExtValue();
49*9880d681SAndroid Build Coastguard Worker Offset = 0;
50*9880d681SAndroid Build Coastguard Worker return I->getOperand(0);
51*9880d681SAndroid Build Coastguard Worker }
52*9880d681SAndroid Build Coastguard Worker
53*9880d681SAndroid Build Coastguard Worker if (I->getOpcode() == Instruction::Mul) {
54*9880d681SAndroid Build Coastguard Worker // This value is scaled by 'RHS'.
55*9880d681SAndroid Build Coastguard Worker Scale = RHS->getZExtValue();
56*9880d681SAndroid Build Coastguard Worker Offset = 0;
57*9880d681SAndroid Build Coastguard Worker return I->getOperand(0);
58*9880d681SAndroid Build Coastguard Worker }
59*9880d681SAndroid Build Coastguard Worker
60*9880d681SAndroid Build Coastguard Worker if (I->getOpcode() == Instruction::Add) {
61*9880d681SAndroid Build Coastguard Worker // We have X+C. Check to see if we really have (X*C2)+C1,
62*9880d681SAndroid Build Coastguard Worker // where C1 is divisible by C2.
63*9880d681SAndroid Build Coastguard Worker unsigned SubScale;
64*9880d681SAndroid Build Coastguard Worker Value *SubVal =
65*9880d681SAndroid Build Coastguard Worker decomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
66*9880d681SAndroid Build Coastguard Worker Offset += RHS->getZExtValue();
67*9880d681SAndroid Build Coastguard Worker Scale = SubScale;
68*9880d681SAndroid Build Coastguard Worker return SubVal;
69*9880d681SAndroid Build Coastguard Worker }
70*9880d681SAndroid Build Coastguard Worker }
71*9880d681SAndroid Build Coastguard Worker }
72*9880d681SAndroid Build Coastguard Worker
73*9880d681SAndroid Build Coastguard Worker // Otherwise, we can't look past this.
74*9880d681SAndroid Build Coastguard Worker Scale = 1;
75*9880d681SAndroid Build Coastguard Worker Offset = 0;
76*9880d681SAndroid Build Coastguard Worker return Val;
77*9880d681SAndroid Build Coastguard Worker }
78*9880d681SAndroid Build Coastguard Worker
79*9880d681SAndroid Build Coastguard Worker /// If we find a cast of an allocation instruction, try to eliminate the cast by
80*9880d681SAndroid Build Coastguard Worker /// moving the type information into the alloc.
PromoteCastOfAllocation(BitCastInst & CI,AllocaInst & AI)81*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
82*9880d681SAndroid Build Coastguard Worker AllocaInst &AI) {
83*9880d681SAndroid Build Coastguard Worker PointerType *PTy = cast<PointerType>(CI.getType());
84*9880d681SAndroid Build Coastguard Worker
85*9880d681SAndroid Build Coastguard Worker BuilderTy AllocaBuilder(*Builder);
86*9880d681SAndroid Build Coastguard Worker AllocaBuilder.SetInsertPoint(&AI);
87*9880d681SAndroid Build Coastguard Worker
88*9880d681SAndroid Build Coastguard Worker // Get the type really allocated and the type casted to.
89*9880d681SAndroid Build Coastguard Worker Type *AllocElTy = AI.getAllocatedType();
90*9880d681SAndroid Build Coastguard Worker Type *CastElTy = PTy->getElementType();
91*9880d681SAndroid Build Coastguard Worker if (!AllocElTy->isSized() || !CastElTy->isSized()) return nullptr;
92*9880d681SAndroid Build Coastguard Worker
93*9880d681SAndroid Build Coastguard Worker unsigned AllocElTyAlign = DL.getABITypeAlignment(AllocElTy);
94*9880d681SAndroid Build Coastguard Worker unsigned CastElTyAlign = DL.getABITypeAlignment(CastElTy);
95*9880d681SAndroid Build Coastguard Worker if (CastElTyAlign < AllocElTyAlign) return nullptr;
96*9880d681SAndroid Build Coastguard Worker
97*9880d681SAndroid Build Coastguard Worker // If the allocation has multiple uses, only promote it if we are strictly
98*9880d681SAndroid Build Coastguard Worker // increasing the alignment of the resultant allocation. If we keep it the
99*9880d681SAndroid Build Coastguard Worker // same, we open the door to infinite loops of various kinds.
100*9880d681SAndroid Build Coastguard Worker if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return nullptr;
101*9880d681SAndroid Build Coastguard Worker
102*9880d681SAndroid Build Coastguard Worker uint64_t AllocElTySize = DL.getTypeAllocSize(AllocElTy);
103*9880d681SAndroid Build Coastguard Worker uint64_t CastElTySize = DL.getTypeAllocSize(CastElTy);
104*9880d681SAndroid Build Coastguard Worker if (CastElTySize == 0 || AllocElTySize == 0) return nullptr;
105*9880d681SAndroid Build Coastguard Worker
106*9880d681SAndroid Build Coastguard Worker // If the allocation has multiple uses, only promote it if we're not
107*9880d681SAndroid Build Coastguard Worker // shrinking the amount of memory being allocated.
108*9880d681SAndroid Build Coastguard Worker uint64_t AllocElTyStoreSize = DL.getTypeStoreSize(AllocElTy);
109*9880d681SAndroid Build Coastguard Worker uint64_t CastElTyStoreSize = DL.getTypeStoreSize(CastElTy);
110*9880d681SAndroid Build Coastguard Worker if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return nullptr;
111*9880d681SAndroid Build Coastguard Worker
112*9880d681SAndroid Build Coastguard Worker // See if we can satisfy the modulus by pulling a scale out of the array
113*9880d681SAndroid Build Coastguard Worker // size argument.
114*9880d681SAndroid Build Coastguard Worker unsigned ArraySizeScale;
115*9880d681SAndroid Build Coastguard Worker uint64_t ArrayOffset;
116*9880d681SAndroid Build Coastguard Worker Value *NumElements = // See if the array size is a decomposable linear expr.
117*9880d681SAndroid Build Coastguard Worker decomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
118*9880d681SAndroid Build Coastguard Worker
119*9880d681SAndroid Build Coastguard Worker // If we can now satisfy the modulus, by using a non-1 scale, we really can
120*9880d681SAndroid Build Coastguard Worker // do the xform.
121*9880d681SAndroid Build Coastguard Worker if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
122*9880d681SAndroid Build Coastguard Worker (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return nullptr;
123*9880d681SAndroid Build Coastguard Worker
124*9880d681SAndroid Build Coastguard Worker unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
125*9880d681SAndroid Build Coastguard Worker Value *Amt = nullptr;
126*9880d681SAndroid Build Coastguard Worker if (Scale == 1) {
127*9880d681SAndroid Build Coastguard Worker Amt = NumElements;
128*9880d681SAndroid Build Coastguard Worker } else {
129*9880d681SAndroid Build Coastguard Worker Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
130*9880d681SAndroid Build Coastguard Worker // Insert before the alloca, not before the cast.
131*9880d681SAndroid Build Coastguard Worker Amt = AllocaBuilder.CreateMul(Amt, NumElements);
132*9880d681SAndroid Build Coastguard Worker }
133*9880d681SAndroid Build Coastguard Worker
134*9880d681SAndroid Build Coastguard Worker if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
135*9880d681SAndroid Build Coastguard Worker Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
136*9880d681SAndroid Build Coastguard Worker Offset, true);
137*9880d681SAndroid Build Coastguard Worker Amt = AllocaBuilder.CreateAdd(Amt, Off);
138*9880d681SAndroid Build Coastguard Worker }
139*9880d681SAndroid Build Coastguard Worker
140*9880d681SAndroid Build Coastguard Worker AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
141*9880d681SAndroid Build Coastguard Worker New->setAlignment(AI.getAlignment());
142*9880d681SAndroid Build Coastguard Worker New->takeName(&AI);
143*9880d681SAndroid Build Coastguard Worker New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
144*9880d681SAndroid Build Coastguard Worker
145*9880d681SAndroid Build Coastguard Worker // If the allocation has multiple real uses, insert a cast and change all
146*9880d681SAndroid Build Coastguard Worker // things that used it to use the new cast. This will also hack on CI, but it
147*9880d681SAndroid Build Coastguard Worker // will die soon.
148*9880d681SAndroid Build Coastguard Worker if (!AI.hasOneUse()) {
149*9880d681SAndroid Build Coastguard Worker // New is the allocation instruction, pointer typed. AI is the original
150*9880d681SAndroid Build Coastguard Worker // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
151*9880d681SAndroid Build Coastguard Worker Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
152*9880d681SAndroid Build Coastguard Worker replaceInstUsesWith(AI, NewCast);
153*9880d681SAndroid Build Coastguard Worker }
154*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(CI, New);
155*9880d681SAndroid Build Coastguard Worker }
156*9880d681SAndroid Build Coastguard Worker
157*9880d681SAndroid Build Coastguard Worker /// Given an expression that CanEvaluateTruncated or CanEvaluateSExtd returns
158*9880d681SAndroid Build Coastguard Worker /// true for, actually insert the code to evaluate the expression.
EvaluateInDifferentType(Value * V,Type * Ty,bool isSigned)159*9880d681SAndroid Build Coastguard Worker Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
160*9880d681SAndroid Build Coastguard Worker bool isSigned) {
161*9880d681SAndroid Build Coastguard Worker if (Constant *C = dyn_cast<Constant>(V)) {
162*9880d681SAndroid Build Coastguard Worker C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
163*9880d681SAndroid Build Coastguard Worker // If we got a constantexpr back, try to simplify it with DL info.
164*9880d681SAndroid Build Coastguard Worker if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
165*9880d681SAndroid Build Coastguard Worker C = ConstantFoldConstantExpression(CE, DL, TLI);
166*9880d681SAndroid Build Coastguard Worker return C;
167*9880d681SAndroid Build Coastguard Worker }
168*9880d681SAndroid Build Coastguard Worker
169*9880d681SAndroid Build Coastguard Worker // Otherwise, it must be an instruction.
170*9880d681SAndroid Build Coastguard Worker Instruction *I = cast<Instruction>(V);
171*9880d681SAndroid Build Coastguard Worker Instruction *Res = nullptr;
172*9880d681SAndroid Build Coastguard Worker unsigned Opc = I->getOpcode();
173*9880d681SAndroid Build Coastguard Worker switch (Opc) {
174*9880d681SAndroid Build Coastguard Worker case Instruction::Add:
175*9880d681SAndroid Build Coastguard Worker case Instruction::Sub:
176*9880d681SAndroid Build Coastguard Worker case Instruction::Mul:
177*9880d681SAndroid Build Coastguard Worker case Instruction::And:
178*9880d681SAndroid Build Coastguard Worker case Instruction::Or:
179*9880d681SAndroid Build Coastguard Worker case Instruction::Xor:
180*9880d681SAndroid Build Coastguard Worker case Instruction::AShr:
181*9880d681SAndroid Build Coastguard Worker case Instruction::LShr:
182*9880d681SAndroid Build Coastguard Worker case Instruction::Shl:
183*9880d681SAndroid Build Coastguard Worker case Instruction::UDiv:
184*9880d681SAndroid Build Coastguard Worker case Instruction::URem: {
185*9880d681SAndroid Build Coastguard Worker Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
186*9880d681SAndroid Build Coastguard Worker Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
187*9880d681SAndroid Build Coastguard Worker Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
188*9880d681SAndroid Build Coastguard Worker break;
189*9880d681SAndroid Build Coastguard Worker }
190*9880d681SAndroid Build Coastguard Worker case Instruction::Trunc:
191*9880d681SAndroid Build Coastguard Worker case Instruction::ZExt:
192*9880d681SAndroid Build Coastguard Worker case Instruction::SExt:
193*9880d681SAndroid Build Coastguard Worker // If the source type of the cast is the type we're trying for then we can
194*9880d681SAndroid Build Coastguard Worker // just return the source. There's no need to insert it because it is not
195*9880d681SAndroid Build Coastguard Worker // new.
196*9880d681SAndroid Build Coastguard Worker if (I->getOperand(0)->getType() == Ty)
197*9880d681SAndroid Build Coastguard Worker return I->getOperand(0);
198*9880d681SAndroid Build Coastguard Worker
199*9880d681SAndroid Build Coastguard Worker // Otherwise, must be the same type of cast, so just reinsert a new one.
200*9880d681SAndroid Build Coastguard Worker // This also handles the case of zext(trunc(x)) -> zext(x).
201*9880d681SAndroid Build Coastguard Worker Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
202*9880d681SAndroid Build Coastguard Worker Opc == Instruction::SExt);
203*9880d681SAndroid Build Coastguard Worker break;
204*9880d681SAndroid Build Coastguard Worker case Instruction::Select: {
205*9880d681SAndroid Build Coastguard Worker Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
206*9880d681SAndroid Build Coastguard Worker Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
207*9880d681SAndroid Build Coastguard Worker Res = SelectInst::Create(I->getOperand(0), True, False);
208*9880d681SAndroid Build Coastguard Worker break;
209*9880d681SAndroid Build Coastguard Worker }
210*9880d681SAndroid Build Coastguard Worker case Instruction::PHI: {
211*9880d681SAndroid Build Coastguard Worker PHINode *OPN = cast<PHINode>(I);
212*9880d681SAndroid Build Coastguard Worker PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
213*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
214*9880d681SAndroid Build Coastguard Worker Value *V =
215*9880d681SAndroid Build Coastguard Worker EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
216*9880d681SAndroid Build Coastguard Worker NPN->addIncoming(V, OPN->getIncomingBlock(i));
217*9880d681SAndroid Build Coastguard Worker }
218*9880d681SAndroid Build Coastguard Worker Res = NPN;
219*9880d681SAndroid Build Coastguard Worker break;
220*9880d681SAndroid Build Coastguard Worker }
221*9880d681SAndroid Build Coastguard Worker default:
222*9880d681SAndroid Build Coastguard Worker // TODO: Can handle more cases here.
223*9880d681SAndroid Build Coastguard Worker llvm_unreachable("Unreachable!");
224*9880d681SAndroid Build Coastguard Worker }
225*9880d681SAndroid Build Coastguard Worker
226*9880d681SAndroid Build Coastguard Worker Res->takeName(I);
227*9880d681SAndroid Build Coastguard Worker return InsertNewInstWith(Res, *I);
228*9880d681SAndroid Build Coastguard Worker }
229*9880d681SAndroid Build Coastguard Worker
230*9880d681SAndroid Build Coastguard Worker
231*9880d681SAndroid Build Coastguard Worker /// This function is a wrapper around CastInst::isEliminableCastPair. It
232*9880d681SAndroid Build Coastguard Worker /// simply extracts arguments and returns what that function returns.
233*9880d681SAndroid Build Coastguard Worker static Instruction::CastOps
isEliminableCastPair(const CastInst * CI,unsigned opcode,Type * DstTy,const DataLayout & DL)234*9880d681SAndroid Build Coastguard Worker isEliminableCastPair(const CastInst *CI, ///< First cast instruction
235*9880d681SAndroid Build Coastguard Worker unsigned opcode, ///< Opcode for the second cast
236*9880d681SAndroid Build Coastguard Worker Type *DstTy, ///< Target type for the second cast
237*9880d681SAndroid Build Coastguard Worker const DataLayout &DL) {
238*9880d681SAndroid Build Coastguard Worker Type *SrcTy = CI->getOperand(0)->getType(); // A from above
239*9880d681SAndroid Build Coastguard Worker Type *MidTy = CI->getType(); // B from above
240*9880d681SAndroid Build Coastguard Worker
241*9880d681SAndroid Build Coastguard Worker // Get the opcodes of the two Cast instructions
242*9880d681SAndroid Build Coastguard Worker Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
243*9880d681SAndroid Build Coastguard Worker Instruction::CastOps secondOp = Instruction::CastOps(opcode);
244*9880d681SAndroid Build Coastguard Worker Type *SrcIntPtrTy =
245*9880d681SAndroid Build Coastguard Worker SrcTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(SrcTy) : nullptr;
246*9880d681SAndroid Build Coastguard Worker Type *MidIntPtrTy =
247*9880d681SAndroid Build Coastguard Worker MidTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(MidTy) : nullptr;
248*9880d681SAndroid Build Coastguard Worker Type *DstIntPtrTy =
249*9880d681SAndroid Build Coastguard Worker DstTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(DstTy) : nullptr;
250*9880d681SAndroid Build Coastguard Worker unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
251*9880d681SAndroid Build Coastguard Worker DstTy, SrcIntPtrTy, MidIntPtrTy,
252*9880d681SAndroid Build Coastguard Worker DstIntPtrTy);
253*9880d681SAndroid Build Coastguard Worker
254*9880d681SAndroid Build Coastguard Worker // We don't want to form an inttoptr or ptrtoint that converts to an integer
255*9880d681SAndroid Build Coastguard Worker // type that differs from the pointer size.
256*9880d681SAndroid Build Coastguard Worker if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
257*9880d681SAndroid Build Coastguard Worker (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
258*9880d681SAndroid Build Coastguard Worker Res = 0;
259*9880d681SAndroid Build Coastguard Worker
260*9880d681SAndroid Build Coastguard Worker return Instruction::CastOps(Res);
261*9880d681SAndroid Build Coastguard Worker }
262*9880d681SAndroid Build Coastguard Worker
263*9880d681SAndroid Build Coastguard Worker /// Return true if the cast from "V to Ty" actually results in any code being
264*9880d681SAndroid Build Coastguard Worker /// generated and is interesting to optimize out.
265*9880d681SAndroid Build Coastguard Worker /// If the cast can be eliminated by some other simple transformation, we prefer
266*9880d681SAndroid Build Coastguard Worker /// to do the simplification first.
ShouldOptimizeCast(Instruction::CastOps opc,const Value * V,Type * Ty)267*9880d681SAndroid Build Coastguard Worker bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
268*9880d681SAndroid Build Coastguard Worker Type *Ty) {
269*9880d681SAndroid Build Coastguard Worker // Noop casts and casts of constants should be eliminated trivially.
270*9880d681SAndroid Build Coastguard Worker if (V->getType() == Ty || isa<Constant>(V)) return false;
271*9880d681SAndroid Build Coastguard Worker
272*9880d681SAndroid Build Coastguard Worker // If this is another cast that can be eliminated, we prefer to have it
273*9880d681SAndroid Build Coastguard Worker // eliminated.
274*9880d681SAndroid Build Coastguard Worker if (const CastInst *CI = dyn_cast<CastInst>(V))
275*9880d681SAndroid Build Coastguard Worker if (isEliminableCastPair(CI, opc, Ty, DL))
276*9880d681SAndroid Build Coastguard Worker return false;
277*9880d681SAndroid Build Coastguard Worker
278*9880d681SAndroid Build Coastguard Worker // If this is a vector sext from a compare, then we don't want to break the
279*9880d681SAndroid Build Coastguard Worker // idiom where each element of the extended vector is either zero or all ones.
280*9880d681SAndroid Build Coastguard Worker if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
281*9880d681SAndroid Build Coastguard Worker return false;
282*9880d681SAndroid Build Coastguard Worker
283*9880d681SAndroid Build Coastguard Worker return true;
284*9880d681SAndroid Build Coastguard Worker }
285*9880d681SAndroid Build Coastguard Worker
286*9880d681SAndroid Build Coastguard Worker
287*9880d681SAndroid Build Coastguard Worker /// @brief Implement the transforms common to all CastInst visitors.
commonCastTransforms(CastInst & CI)288*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
289*9880d681SAndroid Build Coastguard Worker Value *Src = CI.getOperand(0);
290*9880d681SAndroid Build Coastguard Worker
291*9880d681SAndroid Build Coastguard Worker // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
292*9880d681SAndroid Build Coastguard Worker // eliminate it now.
293*9880d681SAndroid Build Coastguard Worker if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
294*9880d681SAndroid Build Coastguard Worker if (Instruction::CastOps opc =
295*9880d681SAndroid Build Coastguard Worker isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), DL)) {
296*9880d681SAndroid Build Coastguard Worker // The first cast (CSrc) is eliminable so we need to fix up or replace
297*9880d681SAndroid Build Coastguard Worker // the second cast (CI). CSrc will then have a good chance of being dead.
298*9880d681SAndroid Build Coastguard Worker return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
299*9880d681SAndroid Build Coastguard Worker }
300*9880d681SAndroid Build Coastguard Worker }
301*9880d681SAndroid Build Coastguard Worker
302*9880d681SAndroid Build Coastguard Worker // If we are casting a select then fold the cast into the select
303*9880d681SAndroid Build Coastguard Worker if (SelectInst *SI = dyn_cast<SelectInst>(Src))
304*9880d681SAndroid Build Coastguard Worker if (Instruction *NV = FoldOpIntoSelect(CI, SI))
305*9880d681SAndroid Build Coastguard Worker return NV;
306*9880d681SAndroid Build Coastguard Worker
307*9880d681SAndroid Build Coastguard Worker // If we are casting a PHI then fold the cast into the PHI
308*9880d681SAndroid Build Coastguard Worker if (isa<PHINode>(Src)) {
309*9880d681SAndroid Build Coastguard Worker // We don't do this if this would create a PHI node with an illegal type if
310*9880d681SAndroid Build Coastguard Worker // it is currently legal.
311*9880d681SAndroid Build Coastguard Worker if (!Src->getType()->isIntegerTy() || !CI.getType()->isIntegerTy() ||
312*9880d681SAndroid Build Coastguard Worker ShouldChangeType(CI.getType(), Src->getType()))
313*9880d681SAndroid Build Coastguard Worker if (Instruction *NV = FoldOpIntoPhi(CI))
314*9880d681SAndroid Build Coastguard Worker return NV;
315*9880d681SAndroid Build Coastguard Worker }
316*9880d681SAndroid Build Coastguard Worker
317*9880d681SAndroid Build Coastguard Worker return nullptr;
318*9880d681SAndroid Build Coastguard Worker }
319*9880d681SAndroid Build Coastguard Worker
320*9880d681SAndroid Build Coastguard Worker /// Return true if we can evaluate the specified expression tree as type Ty
321*9880d681SAndroid Build Coastguard Worker /// instead of its larger type, and arrive with the same value.
322*9880d681SAndroid Build Coastguard Worker /// This is used by code that tries to eliminate truncates.
323*9880d681SAndroid Build Coastguard Worker ///
324*9880d681SAndroid Build Coastguard Worker /// Ty will always be a type smaller than V. We should return true if trunc(V)
325*9880d681SAndroid Build Coastguard Worker /// can be computed by computing V in the smaller type. If V is an instruction,
326*9880d681SAndroid Build Coastguard Worker /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
327*9880d681SAndroid Build Coastguard Worker /// makes sense if x and y can be efficiently truncated.
328*9880d681SAndroid Build Coastguard Worker ///
329*9880d681SAndroid Build Coastguard Worker /// This function works on both vectors and scalars.
330*9880d681SAndroid Build Coastguard Worker ///
canEvaluateTruncated(Value * V,Type * Ty,InstCombiner & IC,Instruction * CxtI)331*9880d681SAndroid Build Coastguard Worker static bool canEvaluateTruncated(Value *V, Type *Ty, InstCombiner &IC,
332*9880d681SAndroid Build Coastguard Worker Instruction *CxtI) {
333*9880d681SAndroid Build Coastguard Worker // We can always evaluate constants in another type.
334*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(V))
335*9880d681SAndroid Build Coastguard Worker return true;
336*9880d681SAndroid Build Coastguard Worker
337*9880d681SAndroid Build Coastguard Worker Instruction *I = dyn_cast<Instruction>(V);
338*9880d681SAndroid Build Coastguard Worker if (!I) return false;
339*9880d681SAndroid Build Coastguard Worker
340*9880d681SAndroid Build Coastguard Worker Type *OrigTy = V->getType();
341*9880d681SAndroid Build Coastguard Worker
342*9880d681SAndroid Build Coastguard Worker // If this is an extension from the dest type, we can eliminate it, even if it
343*9880d681SAndroid Build Coastguard Worker // has multiple uses.
344*9880d681SAndroid Build Coastguard Worker if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
345*9880d681SAndroid Build Coastguard Worker I->getOperand(0)->getType() == Ty)
346*9880d681SAndroid Build Coastguard Worker return true;
347*9880d681SAndroid Build Coastguard Worker
348*9880d681SAndroid Build Coastguard Worker // We can't extend or shrink something that has multiple uses: doing so would
349*9880d681SAndroid Build Coastguard Worker // require duplicating the instruction in general, which isn't profitable.
350*9880d681SAndroid Build Coastguard Worker if (!I->hasOneUse()) return false;
351*9880d681SAndroid Build Coastguard Worker
352*9880d681SAndroid Build Coastguard Worker unsigned Opc = I->getOpcode();
353*9880d681SAndroid Build Coastguard Worker switch (Opc) {
354*9880d681SAndroid Build Coastguard Worker case Instruction::Add:
355*9880d681SAndroid Build Coastguard Worker case Instruction::Sub:
356*9880d681SAndroid Build Coastguard Worker case Instruction::Mul:
357*9880d681SAndroid Build Coastguard Worker case Instruction::And:
358*9880d681SAndroid Build Coastguard Worker case Instruction::Or:
359*9880d681SAndroid Build Coastguard Worker case Instruction::Xor:
360*9880d681SAndroid Build Coastguard Worker // These operators can all arbitrarily be extended or truncated.
361*9880d681SAndroid Build Coastguard Worker return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
362*9880d681SAndroid Build Coastguard Worker canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
363*9880d681SAndroid Build Coastguard Worker
364*9880d681SAndroid Build Coastguard Worker case Instruction::UDiv:
365*9880d681SAndroid Build Coastguard Worker case Instruction::URem: {
366*9880d681SAndroid Build Coastguard Worker // UDiv and URem can be truncated if all the truncated bits are zero.
367*9880d681SAndroid Build Coastguard Worker uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
368*9880d681SAndroid Build Coastguard Worker uint32_t BitWidth = Ty->getScalarSizeInBits();
369*9880d681SAndroid Build Coastguard Worker if (BitWidth < OrigBitWidth) {
370*9880d681SAndroid Build Coastguard Worker APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
371*9880d681SAndroid Build Coastguard Worker if (IC.MaskedValueIsZero(I->getOperand(0), Mask, 0, CxtI) &&
372*9880d681SAndroid Build Coastguard Worker IC.MaskedValueIsZero(I->getOperand(1), Mask, 0, CxtI)) {
373*9880d681SAndroid Build Coastguard Worker return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
374*9880d681SAndroid Build Coastguard Worker canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
375*9880d681SAndroid Build Coastguard Worker }
376*9880d681SAndroid Build Coastguard Worker }
377*9880d681SAndroid Build Coastguard Worker break;
378*9880d681SAndroid Build Coastguard Worker }
379*9880d681SAndroid Build Coastguard Worker case Instruction::Shl:
380*9880d681SAndroid Build Coastguard Worker // If we are truncating the result of this SHL, and if it's a shift of a
381*9880d681SAndroid Build Coastguard Worker // constant amount, we can always perform a SHL in a smaller type.
382*9880d681SAndroid Build Coastguard Worker if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
383*9880d681SAndroid Build Coastguard Worker uint32_t BitWidth = Ty->getScalarSizeInBits();
384*9880d681SAndroid Build Coastguard Worker if (CI->getLimitedValue(BitWidth) < BitWidth)
385*9880d681SAndroid Build Coastguard Worker return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
386*9880d681SAndroid Build Coastguard Worker }
387*9880d681SAndroid Build Coastguard Worker break;
388*9880d681SAndroid Build Coastguard Worker case Instruction::LShr:
389*9880d681SAndroid Build Coastguard Worker // If this is a truncate of a logical shr, we can truncate it to a smaller
390*9880d681SAndroid Build Coastguard Worker // lshr iff we know that the bits we would otherwise be shifting in are
391*9880d681SAndroid Build Coastguard Worker // already zeros.
392*9880d681SAndroid Build Coastguard Worker if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
393*9880d681SAndroid Build Coastguard Worker uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
394*9880d681SAndroid Build Coastguard Worker uint32_t BitWidth = Ty->getScalarSizeInBits();
395*9880d681SAndroid Build Coastguard Worker if (IC.MaskedValueIsZero(I->getOperand(0),
396*9880d681SAndroid Build Coastguard Worker APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth), 0, CxtI) &&
397*9880d681SAndroid Build Coastguard Worker CI->getLimitedValue(BitWidth) < BitWidth) {
398*9880d681SAndroid Build Coastguard Worker return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
399*9880d681SAndroid Build Coastguard Worker }
400*9880d681SAndroid Build Coastguard Worker }
401*9880d681SAndroid Build Coastguard Worker break;
402*9880d681SAndroid Build Coastguard Worker case Instruction::Trunc:
403*9880d681SAndroid Build Coastguard Worker // trunc(trunc(x)) -> trunc(x)
404*9880d681SAndroid Build Coastguard Worker return true;
405*9880d681SAndroid Build Coastguard Worker case Instruction::ZExt:
406*9880d681SAndroid Build Coastguard Worker case Instruction::SExt:
407*9880d681SAndroid Build Coastguard Worker // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
408*9880d681SAndroid Build Coastguard Worker // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
409*9880d681SAndroid Build Coastguard Worker return true;
410*9880d681SAndroid Build Coastguard Worker case Instruction::Select: {
411*9880d681SAndroid Build Coastguard Worker SelectInst *SI = cast<SelectInst>(I);
412*9880d681SAndroid Build Coastguard Worker return canEvaluateTruncated(SI->getTrueValue(), Ty, IC, CxtI) &&
413*9880d681SAndroid Build Coastguard Worker canEvaluateTruncated(SI->getFalseValue(), Ty, IC, CxtI);
414*9880d681SAndroid Build Coastguard Worker }
415*9880d681SAndroid Build Coastguard Worker case Instruction::PHI: {
416*9880d681SAndroid Build Coastguard Worker // We can change a phi if we can change all operands. Note that we never
417*9880d681SAndroid Build Coastguard Worker // get into trouble with cyclic PHIs here because we only consider
418*9880d681SAndroid Build Coastguard Worker // instructions with a single use.
419*9880d681SAndroid Build Coastguard Worker PHINode *PN = cast<PHINode>(I);
420*9880d681SAndroid Build Coastguard Worker for (Value *IncValue : PN->incoming_values())
421*9880d681SAndroid Build Coastguard Worker if (!canEvaluateTruncated(IncValue, Ty, IC, CxtI))
422*9880d681SAndroid Build Coastguard Worker return false;
423*9880d681SAndroid Build Coastguard Worker return true;
424*9880d681SAndroid Build Coastguard Worker }
425*9880d681SAndroid Build Coastguard Worker default:
426*9880d681SAndroid Build Coastguard Worker // TODO: Can handle more cases here.
427*9880d681SAndroid Build Coastguard Worker break;
428*9880d681SAndroid Build Coastguard Worker }
429*9880d681SAndroid Build Coastguard Worker
430*9880d681SAndroid Build Coastguard Worker return false;
431*9880d681SAndroid Build Coastguard Worker }
432*9880d681SAndroid Build Coastguard Worker
433*9880d681SAndroid Build Coastguard Worker /// Given a vector that is bitcast to an integer, optionally logically
434*9880d681SAndroid Build Coastguard Worker /// right-shifted, and truncated, convert it to an extractelement.
435*9880d681SAndroid Build Coastguard Worker /// Example (big endian):
436*9880d681SAndroid Build Coastguard Worker /// trunc (lshr (bitcast <4 x i32> %X to i128), 32) to i32
437*9880d681SAndroid Build Coastguard Worker /// --->
438*9880d681SAndroid Build Coastguard Worker /// extractelement <4 x i32> %X, 1
foldVecTruncToExtElt(TruncInst & Trunc,InstCombiner & IC,const DataLayout & DL)439*9880d681SAndroid Build Coastguard Worker static Instruction *foldVecTruncToExtElt(TruncInst &Trunc, InstCombiner &IC,
440*9880d681SAndroid Build Coastguard Worker const DataLayout &DL) {
441*9880d681SAndroid Build Coastguard Worker Value *TruncOp = Trunc.getOperand(0);
442*9880d681SAndroid Build Coastguard Worker Type *DestType = Trunc.getType();
443*9880d681SAndroid Build Coastguard Worker if (!TruncOp->hasOneUse() || !isa<IntegerType>(DestType))
444*9880d681SAndroid Build Coastguard Worker return nullptr;
445*9880d681SAndroid Build Coastguard Worker
446*9880d681SAndroid Build Coastguard Worker Value *VecInput = nullptr;
447*9880d681SAndroid Build Coastguard Worker ConstantInt *ShiftVal = nullptr;
448*9880d681SAndroid Build Coastguard Worker if (!match(TruncOp, m_CombineOr(m_BitCast(m_Value(VecInput)),
449*9880d681SAndroid Build Coastguard Worker m_LShr(m_BitCast(m_Value(VecInput)),
450*9880d681SAndroid Build Coastguard Worker m_ConstantInt(ShiftVal)))) ||
451*9880d681SAndroid Build Coastguard Worker !isa<VectorType>(VecInput->getType()))
452*9880d681SAndroid Build Coastguard Worker return nullptr;
453*9880d681SAndroid Build Coastguard Worker
454*9880d681SAndroid Build Coastguard Worker VectorType *VecType = cast<VectorType>(VecInput->getType());
455*9880d681SAndroid Build Coastguard Worker unsigned VecWidth = VecType->getPrimitiveSizeInBits();
456*9880d681SAndroid Build Coastguard Worker unsigned DestWidth = DestType->getPrimitiveSizeInBits();
457*9880d681SAndroid Build Coastguard Worker unsigned ShiftAmount = ShiftVal ? ShiftVal->getZExtValue() : 0;
458*9880d681SAndroid Build Coastguard Worker
459*9880d681SAndroid Build Coastguard Worker if ((VecWidth % DestWidth != 0) || (ShiftAmount % DestWidth != 0))
460*9880d681SAndroid Build Coastguard Worker return nullptr;
461*9880d681SAndroid Build Coastguard Worker
462*9880d681SAndroid Build Coastguard Worker // If the element type of the vector doesn't match the result type,
463*9880d681SAndroid Build Coastguard Worker // bitcast it to a vector type that we can extract from.
464*9880d681SAndroid Build Coastguard Worker unsigned NumVecElts = VecWidth / DestWidth;
465*9880d681SAndroid Build Coastguard Worker if (VecType->getElementType() != DestType) {
466*9880d681SAndroid Build Coastguard Worker VecType = VectorType::get(DestType, NumVecElts);
467*9880d681SAndroid Build Coastguard Worker VecInput = IC.Builder->CreateBitCast(VecInput, VecType, "bc");
468*9880d681SAndroid Build Coastguard Worker }
469*9880d681SAndroid Build Coastguard Worker
470*9880d681SAndroid Build Coastguard Worker unsigned Elt = ShiftAmount / DestWidth;
471*9880d681SAndroid Build Coastguard Worker if (DL.isBigEndian())
472*9880d681SAndroid Build Coastguard Worker Elt = NumVecElts - 1 - Elt;
473*9880d681SAndroid Build Coastguard Worker
474*9880d681SAndroid Build Coastguard Worker return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
475*9880d681SAndroid Build Coastguard Worker }
476*9880d681SAndroid Build Coastguard Worker
visitTrunc(TruncInst & CI)477*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
478*9880d681SAndroid Build Coastguard Worker if (Instruction *Result = commonCastTransforms(CI))
479*9880d681SAndroid Build Coastguard Worker return Result;
480*9880d681SAndroid Build Coastguard Worker
481*9880d681SAndroid Build Coastguard Worker // Test if the trunc is the user of a select which is part of a
482*9880d681SAndroid Build Coastguard Worker // minimum or maximum operation. If so, don't do any more simplification.
483*9880d681SAndroid Build Coastguard Worker // Even simplifying demanded bits can break the canonical form of a
484*9880d681SAndroid Build Coastguard Worker // min/max.
485*9880d681SAndroid Build Coastguard Worker Value *LHS, *RHS;
486*9880d681SAndroid Build Coastguard Worker if (SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0)))
487*9880d681SAndroid Build Coastguard Worker if (matchSelectPattern(SI, LHS, RHS).Flavor != SPF_UNKNOWN)
488*9880d681SAndroid Build Coastguard Worker return nullptr;
489*9880d681SAndroid Build Coastguard Worker
490*9880d681SAndroid Build Coastguard Worker // See if we can simplify any instructions used by the input whose sole
491*9880d681SAndroid Build Coastguard Worker // purpose is to compute bits we don't care about.
492*9880d681SAndroid Build Coastguard Worker if (SimplifyDemandedInstructionBits(CI))
493*9880d681SAndroid Build Coastguard Worker return &CI;
494*9880d681SAndroid Build Coastguard Worker
495*9880d681SAndroid Build Coastguard Worker Value *Src = CI.getOperand(0);
496*9880d681SAndroid Build Coastguard Worker Type *DestTy = CI.getType(), *SrcTy = Src->getType();
497*9880d681SAndroid Build Coastguard Worker
498*9880d681SAndroid Build Coastguard Worker // Attempt to truncate the entire input expression tree to the destination
499*9880d681SAndroid Build Coastguard Worker // type. Only do this if the dest type is a simple type, don't convert the
500*9880d681SAndroid Build Coastguard Worker // expression tree to something weird like i93 unless the source is also
501*9880d681SAndroid Build Coastguard Worker // strange.
502*9880d681SAndroid Build Coastguard Worker if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
503*9880d681SAndroid Build Coastguard Worker canEvaluateTruncated(Src, DestTy, *this, &CI)) {
504*9880d681SAndroid Build Coastguard Worker
505*9880d681SAndroid Build Coastguard Worker // If this cast is a truncate, evaluting in a different type always
506*9880d681SAndroid Build Coastguard Worker // eliminates the cast, so it is always a win.
507*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
508*9880d681SAndroid Build Coastguard Worker " to avoid cast: " << CI << '\n');
509*9880d681SAndroid Build Coastguard Worker Value *Res = EvaluateInDifferentType(Src, DestTy, false);
510*9880d681SAndroid Build Coastguard Worker assert(Res->getType() == DestTy);
511*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(CI, Res);
512*9880d681SAndroid Build Coastguard Worker }
513*9880d681SAndroid Build Coastguard Worker
514*9880d681SAndroid Build Coastguard Worker // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
515*9880d681SAndroid Build Coastguard Worker if (DestTy->getScalarSizeInBits() == 1) {
516*9880d681SAndroid Build Coastguard Worker Constant *One = ConstantInt::get(SrcTy, 1);
517*9880d681SAndroid Build Coastguard Worker Src = Builder->CreateAnd(Src, One);
518*9880d681SAndroid Build Coastguard Worker Value *Zero = Constant::getNullValue(Src->getType());
519*9880d681SAndroid Build Coastguard Worker return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
520*9880d681SAndroid Build Coastguard Worker }
521*9880d681SAndroid Build Coastguard Worker
522*9880d681SAndroid Build Coastguard Worker // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
523*9880d681SAndroid Build Coastguard Worker Value *A = nullptr; ConstantInt *Cst = nullptr;
524*9880d681SAndroid Build Coastguard Worker if (Src->hasOneUse() &&
525*9880d681SAndroid Build Coastguard Worker match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
526*9880d681SAndroid Build Coastguard Worker // We have three types to worry about here, the type of A, the source of
527*9880d681SAndroid Build Coastguard Worker // the truncate (MidSize), and the destination of the truncate. We know that
528*9880d681SAndroid Build Coastguard Worker // ASize < MidSize and MidSize > ResultSize, but don't know the relation
529*9880d681SAndroid Build Coastguard Worker // between ASize and ResultSize.
530*9880d681SAndroid Build Coastguard Worker unsigned ASize = A->getType()->getPrimitiveSizeInBits();
531*9880d681SAndroid Build Coastguard Worker
532*9880d681SAndroid Build Coastguard Worker // If the shift amount is larger than the size of A, then the result is
533*9880d681SAndroid Build Coastguard Worker // known to be zero because all the input bits got shifted out.
534*9880d681SAndroid Build Coastguard Worker if (Cst->getZExtValue() >= ASize)
535*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(CI, Constant::getNullValue(DestTy));
536*9880d681SAndroid Build Coastguard Worker
537*9880d681SAndroid Build Coastguard Worker // Since we're doing an lshr and a zero extend, and know that the shift
538*9880d681SAndroid Build Coastguard Worker // amount is smaller than ASize, it is always safe to do the shift in A's
539*9880d681SAndroid Build Coastguard Worker // type, then zero extend or truncate to the result.
540*9880d681SAndroid Build Coastguard Worker Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
541*9880d681SAndroid Build Coastguard Worker Shift->takeName(Src);
542*9880d681SAndroid Build Coastguard Worker return CastInst::CreateIntegerCast(Shift, DestTy, false);
543*9880d681SAndroid Build Coastguard Worker }
544*9880d681SAndroid Build Coastguard Worker
545*9880d681SAndroid Build Coastguard Worker // Transform trunc(lshr (sext A), Cst) to ashr A, Cst to eliminate type
546*9880d681SAndroid Build Coastguard Worker // conversion.
547*9880d681SAndroid Build Coastguard Worker // It works because bits coming from sign extension have the same value as
548*9880d681SAndroid Build Coastguard Worker // the sign bit of the original value; performing ashr instead of lshr
549*9880d681SAndroid Build Coastguard Worker // generates bits of the same value as the sign bit.
550*9880d681SAndroid Build Coastguard Worker if (Src->hasOneUse() &&
551*9880d681SAndroid Build Coastguard Worker match(Src, m_LShr(m_SExt(m_Value(A)), m_ConstantInt(Cst))) &&
552*9880d681SAndroid Build Coastguard Worker cast<Instruction>(Src)->getOperand(0)->hasOneUse()) {
553*9880d681SAndroid Build Coastguard Worker const unsigned ASize = A->getType()->getPrimitiveSizeInBits();
554*9880d681SAndroid Build Coastguard Worker // This optimization can be only performed when zero bits generated by
555*9880d681SAndroid Build Coastguard Worker // the original lshr aren't pulled into the value after truncation, so we
556*9880d681SAndroid Build Coastguard Worker // can only shift by values smaller than the size of destination type (in
557*9880d681SAndroid Build Coastguard Worker // bits).
558*9880d681SAndroid Build Coastguard Worker if (Cst->getValue().ult(ASize)) {
559*9880d681SAndroid Build Coastguard Worker Value *Shift = Builder->CreateAShr(A, Cst->getZExtValue());
560*9880d681SAndroid Build Coastguard Worker Shift->takeName(Src);
561*9880d681SAndroid Build Coastguard Worker return CastInst::CreateIntegerCast(Shift, CI.getType(), true);
562*9880d681SAndroid Build Coastguard Worker }
563*9880d681SAndroid Build Coastguard Worker }
564*9880d681SAndroid Build Coastguard Worker
565*9880d681SAndroid Build Coastguard Worker // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
566*9880d681SAndroid Build Coastguard Worker // type isn't non-native.
567*9880d681SAndroid Build Coastguard Worker if (Src->hasOneUse() && isa<IntegerType>(SrcTy) &&
568*9880d681SAndroid Build Coastguard Worker ShouldChangeType(SrcTy, DestTy) &&
569*9880d681SAndroid Build Coastguard Worker match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
570*9880d681SAndroid Build Coastguard Worker Value *NewTrunc = Builder->CreateTrunc(A, DestTy, A->getName() + ".tr");
571*9880d681SAndroid Build Coastguard Worker return BinaryOperator::CreateAnd(NewTrunc,
572*9880d681SAndroid Build Coastguard Worker ConstantExpr::getTrunc(Cst, DestTy));
573*9880d681SAndroid Build Coastguard Worker }
574*9880d681SAndroid Build Coastguard Worker
575*9880d681SAndroid Build Coastguard Worker if (Instruction *I = foldVecTruncToExtElt(CI, *this, DL))
576*9880d681SAndroid Build Coastguard Worker return I;
577*9880d681SAndroid Build Coastguard Worker
578*9880d681SAndroid Build Coastguard Worker return nullptr;
579*9880d681SAndroid Build Coastguard Worker }
580*9880d681SAndroid Build Coastguard Worker
581*9880d681SAndroid Build Coastguard Worker /// Transform (zext icmp) to bitwise / integer operations in order to eliminate
582*9880d681SAndroid Build Coastguard Worker /// the icmp.
transformZExtICmp(ICmpInst * ICI,Instruction & CI,bool DoXform)583*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
584*9880d681SAndroid Build Coastguard Worker bool DoXform) {
585*9880d681SAndroid Build Coastguard Worker // If we are just checking for a icmp eq of a single bit and zext'ing it
586*9880d681SAndroid Build Coastguard Worker // to an integer, then shift the bit to the appropriate place and then
587*9880d681SAndroid Build Coastguard Worker // cast to integer to avoid the comparison.
588*9880d681SAndroid Build Coastguard Worker if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
589*9880d681SAndroid Build Coastguard Worker const APInt &Op1CV = Op1C->getValue();
590*9880d681SAndroid Build Coastguard Worker
591*9880d681SAndroid Build Coastguard Worker // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
592*9880d681SAndroid Build Coastguard Worker // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
593*9880d681SAndroid Build Coastguard Worker if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
594*9880d681SAndroid Build Coastguard Worker (ICI->getPredicate() == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
595*9880d681SAndroid Build Coastguard Worker if (!DoXform) return ICI;
596*9880d681SAndroid Build Coastguard Worker
597*9880d681SAndroid Build Coastguard Worker Value *In = ICI->getOperand(0);
598*9880d681SAndroid Build Coastguard Worker Value *Sh = ConstantInt::get(In->getType(),
599*9880d681SAndroid Build Coastguard Worker In->getType()->getScalarSizeInBits() - 1);
600*9880d681SAndroid Build Coastguard Worker In = Builder->CreateLShr(In, Sh, In->getName() + ".lobit");
601*9880d681SAndroid Build Coastguard Worker if (In->getType() != CI.getType())
602*9880d681SAndroid Build Coastguard Worker In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
603*9880d681SAndroid Build Coastguard Worker
604*9880d681SAndroid Build Coastguard Worker if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
605*9880d681SAndroid Build Coastguard Worker Constant *One = ConstantInt::get(In->getType(), 1);
606*9880d681SAndroid Build Coastguard Worker In = Builder->CreateXor(In, One, In->getName() + ".not");
607*9880d681SAndroid Build Coastguard Worker }
608*9880d681SAndroid Build Coastguard Worker
609*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(CI, In);
610*9880d681SAndroid Build Coastguard Worker }
611*9880d681SAndroid Build Coastguard Worker
612*9880d681SAndroid Build Coastguard Worker // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
613*9880d681SAndroid Build Coastguard Worker // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
614*9880d681SAndroid Build Coastguard Worker // zext (X == 1) to i32 --> X iff X has only the low bit set.
615*9880d681SAndroid Build Coastguard Worker // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
616*9880d681SAndroid Build Coastguard Worker // zext (X != 0) to i32 --> X iff X has only the low bit set.
617*9880d681SAndroid Build Coastguard Worker // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
618*9880d681SAndroid Build Coastguard Worker // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
619*9880d681SAndroid Build Coastguard Worker // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
620*9880d681SAndroid Build Coastguard Worker if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
621*9880d681SAndroid Build Coastguard Worker // This only works for EQ and NE
622*9880d681SAndroid Build Coastguard Worker ICI->isEquality()) {
623*9880d681SAndroid Build Coastguard Worker // If Op1C some other power of two, convert:
624*9880d681SAndroid Build Coastguard Worker uint32_t BitWidth = Op1C->getType()->getBitWidth();
625*9880d681SAndroid Build Coastguard Worker APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
626*9880d681SAndroid Build Coastguard Worker computeKnownBits(ICI->getOperand(0), KnownZero, KnownOne, 0, &CI);
627*9880d681SAndroid Build Coastguard Worker
628*9880d681SAndroid Build Coastguard Worker APInt KnownZeroMask(~KnownZero);
629*9880d681SAndroid Build Coastguard Worker if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
630*9880d681SAndroid Build Coastguard Worker if (!DoXform) return ICI;
631*9880d681SAndroid Build Coastguard Worker
632*9880d681SAndroid Build Coastguard Worker bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
633*9880d681SAndroid Build Coastguard Worker if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
634*9880d681SAndroid Build Coastguard Worker // (X&4) == 2 --> false
635*9880d681SAndroid Build Coastguard Worker // (X&4) != 2 --> true
636*9880d681SAndroid Build Coastguard Worker Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
637*9880d681SAndroid Build Coastguard Worker isNE);
638*9880d681SAndroid Build Coastguard Worker Res = ConstantExpr::getZExt(Res, CI.getType());
639*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(CI, Res);
640*9880d681SAndroid Build Coastguard Worker }
641*9880d681SAndroid Build Coastguard Worker
642*9880d681SAndroid Build Coastguard Worker uint32_t ShAmt = KnownZeroMask.logBase2();
643*9880d681SAndroid Build Coastguard Worker Value *In = ICI->getOperand(0);
644*9880d681SAndroid Build Coastguard Worker if (ShAmt) {
645*9880d681SAndroid Build Coastguard Worker // Perform a logical shr by shiftamt.
646*9880d681SAndroid Build Coastguard Worker // Insert the shift to put the result in the low bit.
647*9880d681SAndroid Build Coastguard Worker In = Builder->CreateLShr(In, ConstantInt::get(In->getType(), ShAmt),
648*9880d681SAndroid Build Coastguard Worker In->getName() + ".lobit");
649*9880d681SAndroid Build Coastguard Worker }
650*9880d681SAndroid Build Coastguard Worker
651*9880d681SAndroid Build Coastguard Worker if ((Op1CV != 0) == isNE) { // Toggle the low bit.
652*9880d681SAndroid Build Coastguard Worker Constant *One = ConstantInt::get(In->getType(), 1);
653*9880d681SAndroid Build Coastguard Worker In = Builder->CreateXor(In, One);
654*9880d681SAndroid Build Coastguard Worker }
655*9880d681SAndroid Build Coastguard Worker
656*9880d681SAndroid Build Coastguard Worker if (CI.getType() == In->getType())
657*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(CI, In);
658*9880d681SAndroid Build Coastguard Worker return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
659*9880d681SAndroid Build Coastguard Worker }
660*9880d681SAndroid Build Coastguard Worker }
661*9880d681SAndroid Build Coastguard Worker }
662*9880d681SAndroid Build Coastguard Worker
663*9880d681SAndroid Build Coastguard Worker // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
664*9880d681SAndroid Build Coastguard Worker // It is also profitable to transform icmp eq into not(xor(A, B)) because that
665*9880d681SAndroid Build Coastguard Worker // may lead to additional simplifications.
666*9880d681SAndroid Build Coastguard Worker if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
667*9880d681SAndroid Build Coastguard Worker if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
668*9880d681SAndroid Build Coastguard Worker uint32_t BitWidth = ITy->getBitWidth();
669*9880d681SAndroid Build Coastguard Worker Value *LHS = ICI->getOperand(0);
670*9880d681SAndroid Build Coastguard Worker Value *RHS = ICI->getOperand(1);
671*9880d681SAndroid Build Coastguard Worker
672*9880d681SAndroid Build Coastguard Worker APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
673*9880d681SAndroid Build Coastguard Worker APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
674*9880d681SAndroid Build Coastguard Worker computeKnownBits(LHS, KnownZeroLHS, KnownOneLHS, 0, &CI);
675*9880d681SAndroid Build Coastguard Worker computeKnownBits(RHS, KnownZeroRHS, KnownOneRHS, 0, &CI);
676*9880d681SAndroid Build Coastguard Worker
677*9880d681SAndroid Build Coastguard Worker if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
678*9880d681SAndroid Build Coastguard Worker APInt KnownBits = KnownZeroLHS | KnownOneLHS;
679*9880d681SAndroid Build Coastguard Worker APInt UnknownBit = ~KnownBits;
680*9880d681SAndroid Build Coastguard Worker if (UnknownBit.countPopulation() == 1) {
681*9880d681SAndroid Build Coastguard Worker if (!DoXform) return ICI;
682*9880d681SAndroid Build Coastguard Worker
683*9880d681SAndroid Build Coastguard Worker Value *Result = Builder->CreateXor(LHS, RHS);
684*9880d681SAndroid Build Coastguard Worker
685*9880d681SAndroid Build Coastguard Worker // Mask off any bits that are set and won't be shifted away.
686*9880d681SAndroid Build Coastguard Worker if (KnownOneLHS.uge(UnknownBit))
687*9880d681SAndroid Build Coastguard Worker Result = Builder->CreateAnd(Result,
688*9880d681SAndroid Build Coastguard Worker ConstantInt::get(ITy, UnknownBit));
689*9880d681SAndroid Build Coastguard Worker
690*9880d681SAndroid Build Coastguard Worker // Shift the bit we're testing down to the lsb.
691*9880d681SAndroid Build Coastguard Worker Result = Builder->CreateLShr(
692*9880d681SAndroid Build Coastguard Worker Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
693*9880d681SAndroid Build Coastguard Worker
694*9880d681SAndroid Build Coastguard Worker if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
695*9880d681SAndroid Build Coastguard Worker Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
696*9880d681SAndroid Build Coastguard Worker Result->takeName(ICI);
697*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(CI, Result);
698*9880d681SAndroid Build Coastguard Worker }
699*9880d681SAndroid Build Coastguard Worker }
700*9880d681SAndroid Build Coastguard Worker }
701*9880d681SAndroid Build Coastguard Worker }
702*9880d681SAndroid Build Coastguard Worker
703*9880d681SAndroid Build Coastguard Worker return nullptr;
704*9880d681SAndroid Build Coastguard Worker }
705*9880d681SAndroid Build Coastguard Worker
706*9880d681SAndroid Build Coastguard Worker /// Determine if the specified value can be computed in the specified wider type
707*9880d681SAndroid Build Coastguard Worker /// and produce the same low bits. If not, return false.
708*9880d681SAndroid Build Coastguard Worker ///
709*9880d681SAndroid Build Coastguard Worker /// If this function returns true, it can also return a non-zero number of bits
710*9880d681SAndroid Build Coastguard Worker /// (in BitsToClear) which indicates that the value it computes is correct for
711*9880d681SAndroid Build Coastguard Worker /// the zero extend, but that the additional BitsToClear bits need to be zero'd
712*9880d681SAndroid Build Coastguard Worker /// out. For example, to promote something like:
713*9880d681SAndroid Build Coastguard Worker ///
714*9880d681SAndroid Build Coastguard Worker /// %B = trunc i64 %A to i32
715*9880d681SAndroid Build Coastguard Worker /// %C = lshr i32 %B, 8
716*9880d681SAndroid Build Coastguard Worker /// %E = zext i32 %C to i64
717*9880d681SAndroid Build Coastguard Worker ///
718*9880d681SAndroid Build Coastguard Worker /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
719*9880d681SAndroid Build Coastguard Worker /// set to 8 to indicate that the promoted value needs to have bits 24-31
720*9880d681SAndroid Build Coastguard Worker /// cleared in addition to bits 32-63. Since an 'and' will be generated to
721*9880d681SAndroid Build Coastguard Worker /// clear the top bits anyway, doing this has no extra cost.
722*9880d681SAndroid Build Coastguard Worker ///
723*9880d681SAndroid Build Coastguard Worker /// This function works on both vectors and scalars.
canEvaluateZExtd(Value * V,Type * Ty,unsigned & BitsToClear,InstCombiner & IC,Instruction * CxtI)724*9880d681SAndroid Build Coastguard Worker static bool canEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear,
725*9880d681SAndroid Build Coastguard Worker InstCombiner &IC, Instruction *CxtI) {
726*9880d681SAndroid Build Coastguard Worker BitsToClear = 0;
727*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(V))
728*9880d681SAndroid Build Coastguard Worker return true;
729*9880d681SAndroid Build Coastguard Worker
730*9880d681SAndroid Build Coastguard Worker Instruction *I = dyn_cast<Instruction>(V);
731*9880d681SAndroid Build Coastguard Worker if (!I) return false;
732*9880d681SAndroid Build Coastguard Worker
733*9880d681SAndroid Build Coastguard Worker // If the input is a truncate from the destination type, we can trivially
734*9880d681SAndroid Build Coastguard Worker // eliminate it.
735*9880d681SAndroid Build Coastguard Worker if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
736*9880d681SAndroid Build Coastguard Worker return true;
737*9880d681SAndroid Build Coastguard Worker
738*9880d681SAndroid Build Coastguard Worker // We can't extend or shrink something that has multiple uses: doing so would
739*9880d681SAndroid Build Coastguard Worker // require duplicating the instruction in general, which isn't profitable.
740*9880d681SAndroid Build Coastguard Worker if (!I->hasOneUse()) return false;
741*9880d681SAndroid Build Coastguard Worker
742*9880d681SAndroid Build Coastguard Worker unsigned Opc = I->getOpcode(), Tmp;
743*9880d681SAndroid Build Coastguard Worker switch (Opc) {
744*9880d681SAndroid Build Coastguard Worker case Instruction::ZExt: // zext(zext(x)) -> zext(x).
745*9880d681SAndroid Build Coastguard Worker case Instruction::SExt: // zext(sext(x)) -> sext(x).
746*9880d681SAndroid Build Coastguard Worker case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
747*9880d681SAndroid Build Coastguard Worker return true;
748*9880d681SAndroid Build Coastguard Worker case Instruction::And:
749*9880d681SAndroid Build Coastguard Worker case Instruction::Or:
750*9880d681SAndroid Build Coastguard Worker case Instruction::Xor:
751*9880d681SAndroid Build Coastguard Worker case Instruction::Add:
752*9880d681SAndroid Build Coastguard Worker case Instruction::Sub:
753*9880d681SAndroid Build Coastguard Worker case Instruction::Mul:
754*9880d681SAndroid Build Coastguard Worker if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI) ||
755*9880d681SAndroid Build Coastguard Worker !canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI))
756*9880d681SAndroid Build Coastguard Worker return false;
757*9880d681SAndroid Build Coastguard Worker // These can all be promoted if neither operand has 'bits to clear'.
758*9880d681SAndroid Build Coastguard Worker if (BitsToClear == 0 && Tmp == 0)
759*9880d681SAndroid Build Coastguard Worker return true;
760*9880d681SAndroid Build Coastguard Worker
761*9880d681SAndroid Build Coastguard Worker // If the operation is an AND/OR/XOR and the bits to clear are zero in the
762*9880d681SAndroid Build Coastguard Worker // other side, BitsToClear is ok.
763*9880d681SAndroid Build Coastguard Worker if (Tmp == 0 &&
764*9880d681SAndroid Build Coastguard Worker (Opc == Instruction::And || Opc == Instruction::Or ||
765*9880d681SAndroid Build Coastguard Worker Opc == Instruction::Xor)) {
766*9880d681SAndroid Build Coastguard Worker // We use MaskedValueIsZero here for generality, but the case we care
767*9880d681SAndroid Build Coastguard Worker // about the most is constant RHS.
768*9880d681SAndroid Build Coastguard Worker unsigned VSize = V->getType()->getScalarSizeInBits();
769*9880d681SAndroid Build Coastguard Worker if (IC.MaskedValueIsZero(I->getOperand(1),
770*9880d681SAndroid Build Coastguard Worker APInt::getHighBitsSet(VSize, BitsToClear),
771*9880d681SAndroid Build Coastguard Worker 0, CxtI))
772*9880d681SAndroid Build Coastguard Worker return true;
773*9880d681SAndroid Build Coastguard Worker }
774*9880d681SAndroid Build Coastguard Worker
775*9880d681SAndroid Build Coastguard Worker // Otherwise, we don't know how to analyze this BitsToClear case yet.
776*9880d681SAndroid Build Coastguard Worker return false;
777*9880d681SAndroid Build Coastguard Worker
778*9880d681SAndroid Build Coastguard Worker case Instruction::Shl:
779*9880d681SAndroid Build Coastguard Worker // We can promote shl(x, cst) if we can promote x. Since shl overwrites the
780*9880d681SAndroid Build Coastguard Worker // upper bits we can reduce BitsToClear by the shift amount.
781*9880d681SAndroid Build Coastguard Worker if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
782*9880d681SAndroid Build Coastguard Worker if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
783*9880d681SAndroid Build Coastguard Worker return false;
784*9880d681SAndroid Build Coastguard Worker uint64_t ShiftAmt = Amt->getZExtValue();
785*9880d681SAndroid Build Coastguard Worker BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
786*9880d681SAndroid Build Coastguard Worker return true;
787*9880d681SAndroid Build Coastguard Worker }
788*9880d681SAndroid Build Coastguard Worker return false;
789*9880d681SAndroid Build Coastguard Worker case Instruction::LShr:
790*9880d681SAndroid Build Coastguard Worker // We can promote lshr(x, cst) if we can promote x. This requires the
791*9880d681SAndroid Build Coastguard Worker // ultimate 'and' to clear out the high zero bits we're clearing out though.
792*9880d681SAndroid Build Coastguard Worker if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
793*9880d681SAndroid Build Coastguard Worker if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
794*9880d681SAndroid Build Coastguard Worker return false;
795*9880d681SAndroid Build Coastguard Worker BitsToClear += Amt->getZExtValue();
796*9880d681SAndroid Build Coastguard Worker if (BitsToClear > V->getType()->getScalarSizeInBits())
797*9880d681SAndroid Build Coastguard Worker BitsToClear = V->getType()->getScalarSizeInBits();
798*9880d681SAndroid Build Coastguard Worker return true;
799*9880d681SAndroid Build Coastguard Worker }
800*9880d681SAndroid Build Coastguard Worker // Cannot promote variable LSHR.
801*9880d681SAndroid Build Coastguard Worker return false;
802*9880d681SAndroid Build Coastguard Worker case Instruction::Select:
803*9880d681SAndroid Build Coastguard Worker if (!canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI) ||
804*9880d681SAndroid Build Coastguard Worker !canEvaluateZExtd(I->getOperand(2), Ty, BitsToClear, IC, CxtI) ||
805*9880d681SAndroid Build Coastguard Worker // TODO: If important, we could handle the case when the BitsToClear are
806*9880d681SAndroid Build Coastguard Worker // known zero in the disagreeing side.
807*9880d681SAndroid Build Coastguard Worker Tmp != BitsToClear)
808*9880d681SAndroid Build Coastguard Worker return false;
809*9880d681SAndroid Build Coastguard Worker return true;
810*9880d681SAndroid Build Coastguard Worker
811*9880d681SAndroid Build Coastguard Worker case Instruction::PHI: {
812*9880d681SAndroid Build Coastguard Worker // We can change a phi if we can change all operands. Note that we never
813*9880d681SAndroid Build Coastguard Worker // get into trouble with cyclic PHIs here because we only consider
814*9880d681SAndroid Build Coastguard Worker // instructions with a single use.
815*9880d681SAndroid Build Coastguard Worker PHINode *PN = cast<PHINode>(I);
816*9880d681SAndroid Build Coastguard Worker if (!canEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear, IC, CxtI))
817*9880d681SAndroid Build Coastguard Worker return false;
818*9880d681SAndroid Build Coastguard Worker for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
819*9880d681SAndroid Build Coastguard Worker if (!canEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) ||
820*9880d681SAndroid Build Coastguard Worker // TODO: If important, we could handle the case when the BitsToClear
821*9880d681SAndroid Build Coastguard Worker // are known zero in the disagreeing input.
822*9880d681SAndroid Build Coastguard Worker Tmp != BitsToClear)
823*9880d681SAndroid Build Coastguard Worker return false;
824*9880d681SAndroid Build Coastguard Worker return true;
825*9880d681SAndroid Build Coastguard Worker }
826*9880d681SAndroid Build Coastguard Worker default:
827*9880d681SAndroid Build Coastguard Worker // TODO: Can handle more cases here.
828*9880d681SAndroid Build Coastguard Worker return false;
829*9880d681SAndroid Build Coastguard Worker }
830*9880d681SAndroid Build Coastguard Worker }
831*9880d681SAndroid Build Coastguard Worker
visitZExt(ZExtInst & CI)832*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
833*9880d681SAndroid Build Coastguard Worker // If this zero extend is only used by a truncate, let the truncate be
834*9880d681SAndroid Build Coastguard Worker // eliminated before we try to optimize this zext.
835*9880d681SAndroid Build Coastguard Worker if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
836*9880d681SAndroid Build Coastguard Worker return nullptr;
837*9880d681SAndroid Build Coastguard Worker
838*9880d681SAndroid Build Coastguard Worker // If one of the common conversion will work, do it.
839*9880d681SAndroid Build Coastguard Worker if (Instruction *Result = commonCastTransforms(CI))
840*9880d681SAndroid Build Coastguard Worker return Result;
841*9880d681SAndroid Build Coastguard Worker
842*9880d681SAndroid Build Coastguard Worker // See if we can simplify any instructions used by the input whose sole
843*9880d681SAndroid Build Coastguard Worker // purpose is to compute bits we don't care about.
844*9880d681SAndroid Build Coastguard Worker if (SimplifyDemandedInstructionBits(CI))
845*9880d681SAndroid Build Coastguard Worker return &CI;
846*9880d681SAndroid Build Coastguard Worker
847*9880d681SAndroid Build Coastguard Worker Value *Src = CI.getOperand(0);
848*9880d681SAndroid Build Coastguard Worker Type *SrcTy = Src->getType(), *DestTy = CI.getType();
849*9880d681SAndroid Build Coastguard Worker
850*9880d681SAndroid Build Coastguard Worker // Attempt to extend the entire input expression tree to the destination
851*9880d681SAndroid Build Coastguard Worker // type. Only do this if the dest type is a simple type, don't convert the
852*9880d681SAndroid Build Coastguard Worker // expression tree to something weird like i93 unless the source is also
853*9880d681SAndroid Build Coastguard Worker // strange.
854*9880d681SAndroid Build Coastguard Worker unsigned BitsToClear;
855*9880d681SAndroid Build Coastguard Worker if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
856*9880d681SAndroid Build Coastguard Worker canEvaluateZExtd(Src, DestTy, BitsToClear, *this, &CI)) {
857*9880d681SAndroid Build Coastguard Worker assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
858*9880d681SAndroid Build Coastguard Worker "Unreasonable BitsToClear");
859*9880d681SAndroid Build Coastguard Worker
860*9880d681SAndroid Build Coastguard Worker // Okay, we can transform this! Insert the new expression now.
861*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
862*9880d681SAndroid Build Coastguard Worker " to avoid zero extend: " << CI << '\n');
863*9880d681SAndroid Build Coastguard Worker Value *Res = EvaluateInDifferentType(Src, DestTy, false);
864*9880d681SAndroid Build Coastguard Worker assert(Res->getType() == DestTy);
865*9880d681SAndroid Build Coastguard Worker
866*9880d681SAndroid Build Coastguard Worker uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
867*9880d681SAndroid Build Coastguard Worker uint32_t DestBitSize = DestTy->getScalarSizeInBits();
868*9880d681SAndroid Build Coastguard Worker
869*9880d681SAndroid Build Coastguard Worker // If the high bits are already filled with zeros, just replace this
870*9880d681SAndroid Build Coastguard Worker // cast with the result.
871*9880d681SAndroid Build Coastguard Worker if (MaskedValueIsZero(Res,
872*9880d681SAndroid Build Coastguard Worker APInt::getHighBitsSet(DestBitSize,
873*9880d681SAndroid Build Coastguard Worker DestBitSize-SrcBitsKept),
874*9880d681SAndroid Build Coastguard Worker 0, &CI))
875*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(CI, Res);
876*9880d681SAndroid Build Coastguard Worker
877*9880d681SAndroid Build Coastguard Worker // We need to emit an AND to clear the high bits.
878*9880d681SAndroid Build Coastguard Worker Constant *C = ConstantInt::get(Res->getType(),
879*9880d681SAndroid Build Coastguard Worker APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
880*9880d681SAndroid Build Coastguard Worker return BinaryOperator::CreateAnd(Res, C);
881*9880d681SAndroid Build Coastguard Worker }
882*9880d681SAndroid Build Coastguard Worker
883*9880d681SAndroid Build Coastguard Worker // If this is a TRUNC followed by a ZEXT then we are dealing with integral
884*9880d681SAndroid Build Coastguard Worker // types and if the sizes are just right we can convert this into a logical
885*9880d681SAndroid Build Coastguard Worker // 'and' which will be much cheaper than the pair of casts.
886*9880d681SAndroid Build Coastguard Worker if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
887*9880d681SAndroid Build Coastguard Worker // TODO: Subsume this into EvaluateInDifferentType.
888*9880d681SAndroid Build Coastguard Worker
889*9880d681SAndroid Build Coastguard Worker // Get the sizes of the types involved. We know that the intermediate type
890*9880d681SAndroid Build Coastguard Worker // will be smaller than A or C, but don't know the relation between A and C.
891*9880d681SAndroid Build Coastguard Worker Value *A = CSrc->getOperand(0);
892*9880d681SAndroid Build Coastguard Worker unsigned SrcSize = A->getType()->getScalarSizeInBits();
893*9880d681SAndroid Build Coastguard Worker unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
894*9880d681SAndroid Build Coastguard Worker unsigned DstSize = CI.getType()->getScalarSizeInBits();
895*9880d681SAndroid Build Coastguard Worker // If we're actually extending zero bits, then if
896*9880d681SAndroid Build Coastguard Worker // SrcSize < DstSize: zext(a & mask)
897*9880d681SAndroid Build Coastguard Worker // SrcSize == DstSize: a & mask
898*9880d681SAndroid Build Coastguard Worker // SrcSize > DstSize: trunc(a) & mask
899*9880d681SAndroid Build Coastguard Worker if (SrcSize < DstSize) {
900*9880d681SAndroid Build Coastguard Worker APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
901*9880d681SAndroid Build Coastguard Worker Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
902*9880d681SAndroid Build Coastguard Worker Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
903*9880d681SAndroid Build Coastguard Worker return new ZExtInst(And, CI.getType());
904*9880d681SAndroid Build Coastguard Worker }
905*9880d681SAndroid Build Coastguard Worker
906*9880d681SAndroid Build Coastguard Worker if (SrcSize == DstSize) {
907*9880d681SAndroid Build Coastguard Worker APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
908*9880d681SAndroid Build Coastguard Worker return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
909*9880d681SAndroid Build Coastguard Worker AndValue));
910*9880d681SAndroid Build Coastguard Worker }
911*9880d681SAndroid Build Coastguard Worker if (SrcSize > DstSize) {
912*9880d681SAndroid Build Coastguard Worker Value *Trunc = Builder->CreateTrunc(A, CI.getType());
913*9880d681SAndroid Build Coastguard Worker APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
914*9880d681SAndroid Build Coastguard Worker return BinaryOperator::CreateAnd(Trunc,
915*9880d681SAndroid Build Coastguard Worker ConstantInt::get(Trunc->getType(),
916*9880d681SAndroid Build Coastguard Worker AndValue));
917*9880d681SAndroid Build Coastguard Worker }
918*9880d681SAndroid Build Coastguard Worker }
919*9880d681SAndroid Build Coastguard Worker
920*9880d681SAndroid Build Coastguard Worker if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
921*9880d681SAndroid Build Coastguard Worker return transformZExtICmp(ICI, CI);
922*9880d681SAndroid Build Coastguard Worker
923*9880d681SAndroid Build Coastguard Worker BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
924*9880d681SAndroid Build Coastguard Worker if (SrcI && SrcI->getOpcode() == Instruction::Or) {
925*9880d681SAndroid Build Coastguard Worker // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
926*9880d681SAndroid Build Coastguard Worker // of the (zext icmp) will be transformed.
927*9880d681SAndroid Build Coastguard Worker ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
928*9880d681SAndroid Build Coastguard Worker ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
929*9880d681SAndroid Build Coastguard Worker if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
930*9880d681SAndroid Build Coastguard Worker (transformZExtICmp(LHS, CI, false) ||
931*9880d681SAndroid Build Coastguard Worker transformZExtICmp(RHS, CI, false))) {
932*9880d681SAndroid Build Coastguard Worker Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
933*9880d681SAndroid Build Coastguard Worker Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
934*9880d681SAndroid Build Coastguard Worker return BinaryOperator::Create(Instruction::Or, LCast, RCast);
935*9880d681SAndroid Build Coastguard Worker }
936*9880d681SAndroid Build Coastguard Worker }
937*9880d681SAndroid Build Coastguard Worker
938*9880d681SAndroid Build Coastguard Worker // zext(trunc(X) & C) -> (X & zext(C)).
939*9880d681SAndroid Build Coastguard Worker Constant *C;
940*9880d681SAndroid Build Coastguard Worker Value *X;
941*9880d681SAndroid Build Coastguard Worker if (SrcI &&
942*9880d681SAndroid Build Coastguard Worker match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) &&
943*9880d681SAndroid Build Coastguard Worker X->getType() == CI.getType())
944*9880d681SAndroid Build Coastguard Worker return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType()));
945*9880d681SAndroid Build Coastguard Worker
946*9880d681SAndroid Build Coastguard Worker // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)).
947*9880d681SAndroid Build Coastguard Worker Value *And;
948*9880d681SAndroid Build Coastguard Worker if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) &&
949*9880d681SAndroid Build Coastguard Worker match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) &&
950*9880d681SAndroid Build Coastguard Worker X->getType() == CI.getType()) {
951*9880d681SAndroid Build Coastguard Worker Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
952*9880d681SAndroid Build Coastguard Worker return BinaryOperator::CreateXor(Builder->CreateAnd(X, ZC), ZC);
953*9880d681SAndroid Build Coastguard Worker }
954*9880d681SAndroid Build Coastguard Worker
955*9880d681SAndroid Build Coastguard Worker // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
956*9880d681SAndroid Build Coastguard Worker if (SrcI && SrcI->hasOneUse() &&
957*9880d681SAndroid Build Coastguard Worker SrcI->getType()->getScalarType()->isIntegerTy(1) &&
958*9880d681SAndroid Build Coastguard Worker match(SrcI, m_Not(m_Value(X))) && (!X->hasOneUse() || !isa<CmpInst>(X))) {
959*9880d681SAndroid Build Coastguard Worker Value *New = Builder->CreateZExt(X, CI.getType());
960*9880d681SAndroid Build Coastguard Worker return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
961*9880d681SAndroid Build Coastguard Worker }
962*9880d681SAndroid Build Coastguard Worker
963*9880d681SAndroid Build Coastguard Worker return nullptr;
964*9880d681SAndroid Build Coastguard Worker }
965*9880d681SAndroid Build Coastguard Worker
966*9880d681SAndroid Build Coastguard Worker /// Transform (sext icmp) to bitwise / integer operations to eliminate the icmp.
transformSExtICmp(ICmpInst * ICI,Instruction & CI)967*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
968*9880d681SAndroid Build Coastguard Worker Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
969*9880d681SAndroid Build Coastguard Worker ICmpInst::Predicate Pred = ICI->getPredicate();
970*9880d681SAndroid Build Coastguard Worker
971*9880d681SAndroid Build Coastguard Worker // Don't bother if Op1 isn't of vector or integer type.
972*9880d681SAndroid Build Coastguard Worker if (!Op1->getType()->isIntOrIntVectorTy())
973*9880d681SAndroid Build Coastguard Worker return nullptr;
974*9880d681SAndroid Build Coastguard Worker
975*9880d681SAndroid Build Coastguard Worker if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
976*9880d681SAndroid Build Coastguard Worker // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative
977*9880d681SAndroid Build Coastguard Worker // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive
978*9880d681SAndroid Build Coastguard Worker if ((Pred == ICmpInst::ICMP_SLT && Op1C->isNullValue()) ||
979*9880d681SAndroid Build Coastguard Worker (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
980*9880d681SAndroid Build Coastguard Worker
981*9880d681SAndroid Build Coastguard Worker Value *Sh = ConstantInt::get(Op0->getType(),
982*9880d681SAndroid Build Coastguard Worker Op0->getType()->getScalarSizeInBits()-1);
983*9880d681SAndroid Build Coastguard Worker Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
984*9880d681SAndroid Build Coastguard Worker if (In->getType() != CI.getType())
985*9880d681SAndroid Build Coastguard Worker In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
986*9880d681SAndroid Build Coastguard Worker
987*9880d681SAndroid Build Coastguard Worker if (Pred == ICmpInst::ICMP_SGT)
988*9880d681SAndroid Build Coastguard Worker In = Builder->CreateNot(In, In->getName()+".not");
989*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(CI, In);
990*9880d681SAndroid Build Coastguard Worker }
991*9880d681SAndroid Build Coastguard Worker }
992*9880d681SAndroid Build Coastguard Worker
993*9880d681SAndroid Build Coastguard Worker if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
994*9880d681SAndroid Build Coastguard Worker // If we know that only one bit of the LHS of the icmp can be set and we
995*9880d681SAndroid Build Coastguard Worker // have an equality comparison with zero or a power of 2, we can transform
996*9880d681SAndroid Build Coastguard Worker // the icmp and sext into bitwise/integer operations.
997*9880d681SAndroid Build Coastguard Worker if (ICI->hasOneUse() &&
998*9880d681SAndroid Build Coastguard Worker ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
999*9880d681SAndroid Build Coastguard Worker unsigned BitWidth = Op1C->getType()->getBitWidth();
1000*9880d681SAndroid Build Coastguard Worker APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1001*9880d681SAndroid Build Coastguard Worker computeKnownBits(Op0, KnownZero, KnownOne, 0, &CI);
1002*9880d681SAndroid Build Coastguard Worker
1003*9880d681SAndroid Build Coastguard Worker APInt KnownZeroMask(~KnownZero);
1004*9880d681SAndroid Build Coastguard Worker if (KnownZeroMask.isPowerOf2()) {
1005*9880d681SAndroid Build Coastguard Worker Value *In = ICI->getOperand(0);
1006*9880d681SAndroid Build Coastguard Worker
1007*9880d681SAndroid Build Coastguard Worker // If the icmp tests for a known zero bit we can constant fold it.
1008*9880d681SAndroid Build Coastguard Worker if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
1009*9880d681SAndroid Build Coastguard Worker Value *V = Pred == ICmpInst::ICMP_NE ?
1010*9880d681SAndroid Build Coastguard Worker ConstantInt::getAllOnesValue(CI.getType()) :
1011*9880d681SAndroid Build Coastguard Worker ConstantInt::getNullValue(CI.getType());
1012*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(CI, V);
1013*9880d681SAndroid Build Coastguard Worker }
1014*9880d681SAndroid Build Coastguard Worker
1015*9880d681SAndroid Build Coastguard Worker if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
1016*9880d681SAndroid Build Coastguard Worker // sext ((x & 2^n) == 0) -> (x >> n) - 1
1017*9880d681SAndroid Build Coastguard Worker // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
1018*9880d681SAndroid Build Coastguard Worker unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
1019*9880d681SAndroid Build Coastguard Worker // Perform a right shift to place the desired bit in the LSB.
1020*9880d681SAndroid Build Coastguard Worker if (ShiftAmt)
1021*9880d681SAndroid Build Coastguard Worker In = Builder->CreateLShr(In,
1022*9880d681SAndroid Build Coastguard Worker ConstantInt::get(In->getType(), ShiftAmt));
1023*9880d681SAndroid Build Coastguard Worker
1024*9880d681SAndroid Build Coastguard Worker // At this point "In" is either 1 or 0. Subtract 1 to turn
1025*9880d681SAndroid Build Coastguard Worker // {1, 0} -> {0, -1}.
1026*9880d681SAndroid Build Coastguard Worker In = Builder->CreateAdd(In,
1027*9880d681SAndroid Build Coastguard Worker ConstantInt::getAllOnesValue(In->getType()),
1028*9880d681SAndroid Build Coastguard Worker "sext");
1029*9880d681SAndroid Build Coastguard Worker } else {
1030*9880d681SAndroid Build Coastguard Worker // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1
1031*9880d681SAndroid Build Coastguard Worker // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
1032*9880d681SAndroid Build Coastguard Worker unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
1033*9880d681SAndroid Build Coastguard Worker // Perform a left shift to place the desired bit in the MSB.
1034*9880d681SAndroid Build Coastguard Worker if (ShiftAmt)
1035*9880d681SAndroid Build Coastguard Worker In = Builder->CreateShl(In,
1036*9880d681SAndroid Build Coastguard Worker ConstantInt::get(In->getType(), ShiftAmt));
1037*9880d681SAndroid Build Coastguard Worker
1038*9880d681SAndroid Build Coastguard Worker // Distribute the bit over the whole bit width.
1039*9880d681SAndroid Build Coastguard Worker In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
1040*9880d681SAndroid Build Coastguard Worker BitWidth - 1), "sext");
1041*9880d681SAndroid Build Coastguard Worker }
1042*9880d681SAndroid Build Coastguard Worker
1043*9880d681SAndroid Build Coastguard Worker if (CI.getType() == In->getType())
1044*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(CI, In);
1045*9880d681SAndroid Build Coastguard Worker return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
1046*9880d681SAndroid Build Coastguard Worker }
1047*9880d681SAndroid Build Coastguard Worker }
1048*9880d681SAndroid Build Coastguard Worker }
1049*9880d681SAndroid Build Coastguard Worker
1050*9880d681SAndroid Build Coastguard Worker return nullptr;
1051*9880d681SAndroid Build Coastguard Worker }
1052*9880d681SAndroid Build Coastguard Worker
1053*9880d681SAndroid Build Coastguard Worker /// Return true if we can take the specified value and return it as type Ty
1054*9880d681SAndroid Build Coastguard Worker /// without inserting any new casts and without changing the value of the common
1055*9880d681SAndroid Build Coastguard Worker /// low bits. This is used by code that tries to promote integer operations to
1056*9880d681SAndroid Build Coastguard Worker /// a wider types will allow us to eliminate the extension.
1057*9880d681SAndroid Build Coastguard Worker ///
1058*9880d681SAndroid Build Coastguard Worker /// This function works on both vectors and scalars.
1059*9880d681SAndroid Build Coastguard Worker ///
canEvaluateSExtd(Value * V,Type * Ty)1060*9880d681SAndroid Build Coastguard Worker static bool canEvaluateSExtd(Value *V, Type *Ty) {
1061*9880d681SAndroid Build Coastguard Worker assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
1062*9880d681SAndroid Build Coastguard Worker "Can't sign extend type to a smaller type");
1063*9880d681SAndroid Build Coastguard Worker // If this is a constant, it can be trivially promoted.
1064*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(V))
1065*9880d681SAndroid Build Coastguard Worker return true;
1066*9880d681SAndroid Build Coastguard Worker
1067*9880d681SAndroid Build Coastguard Worker Instruction *I = dyn_cast<Instruction>(V);
1068*9880d681SAndroid Build Coastguard Worker if (!I) return false;
1069*9880d681SAndroid Build Coastguard Worker
1070*9880d681SAndroid Build Coastguard Worker // If this is a truncate from the dest type, we can trivially eliminate it.
1071*9880d681SAndroid Build Coastguard Worker if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
1072*9880d681SAndroid Build Coastguard Worker return true;
1073*9880d681SAndroid Build Coastguard Worker
1074*9880d681SAndroid Build Coastguard Worker // We can't extend or shrink something that has multiple uses: doing so would
1075*9880d681SAndroid Build Coastguard Worker // require duplicating the instruction in general, which isn't profitable.
1076*9880d681SAndroid Build Coastguard Worker if (!I->hasOneUse()) return false;
1077*9880d681SAndroid Build Coastguard Worker
1078*9880d681SAndroid Build Coastguard Worker switch (I->getOpcode()) {
1079*9880d681SAndroid Build Coastguard Worker case Instruction::SExt: // sext(sext(x)) -> sext(x)
1080*9880d681SAndroid Build Coastguard Worker case Instruction::ZExt: // sext(zext(x)) -> zext(x)
1081*9880d681SAndroid Build Coastguard Worker case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1082*9880d681SAndroid Build Coastguard Worker return true;
1083*9880d681SAndroid Build Coastguard Worker case Instruction::And:
1084*9880d681SAndroid Build Coastguard Worker case Instruction::Or:
1085*9880d681SAndroid Build Coastguard Worker case Instruction::Xor:
1086*9880d681SAndroid Build Coastguard Worker case Instruction::Add:
1087*9880d681SAndroid Build Coastguard Worker case Instruction::Sub:
1088*9880d681SAndroid Build Coastguard Worker case Instruction::Mul:
1089*9880d681SAndroid Build Coastguard Worker // These operators can all arbitrarily be extended if their inputs can.
1090*9880d681SAndroid Build Coastguard Worker return canEvaluateSExtd(I->getOperand(0), Ty) &&
1091*9880d681SAndroid Build Coastguard Worker canEvaluateSExtd(I->getOperand(1), Ty);
1092*9880d681SAndroid Build Coastguard Worker
1093*9880d681SAndroid Build Coastguard Worker //case Instruction::Shl: TODO
1094*9880d681SAndroid Build Coastguard Worker //case Instruction::LShr: TODO
1095*9880d681SAndroid Build Coastguard Worker
1096*9880d681SAndroid Build Coastguard Worker case Instruction::Select:
1097*9880d681SAndroid Build Coastguard Worker return canEvaluateSExtd(I->getOperand(1), Ty) &&
1098*9880d681SAndroid Build Coastguard Worker canEvaluateSExtd(I->getOperand(2), Ty);
1099*9880d681SAndroid Build Coastguard Worker
1100*9880d681SAndroid Build Coastguard Worker case Instruction::PHI: {
1101*9880d681SAndroid Build Coastguard Worker // We can change a phi if we can change all operands. Note that we never
1102*9880d681SAndroid Build Coastguard Worker // get into trouble with cyclic PHIs here because we only consider
1103*9880d681SAndroid Build Coastguard Worker // instructions with a single use.
1104*9880d681SAndroid Build Coastguard Worker PHINode *PN = cast<PHINode>(I);
1105*9880d681SAndroid Build Coastguard Worker for (Value *IncValue : PN->incoming_values())
1106*9880d681SAndroid Build Coastguard Worker if (!canEvaluateSExtd(IncValue, Ty)) return false;
1107*9880d681SAndroid Build Coastguard Worker return true;
1108*9880d681SAndroid Build Coastguard Worker }
1109*9880d681SAndroid Build Coastguard Worker default:
1110*9880d681SAndroid Build Coastguard Worker // TODO: Can handle more cases here.
1111*9880d681SAndroid Build Coastguard Worker break;
1112*9880d681SAndroid Build Coastguard Worker }
1113*9880d681SAndroid Build Coastguard Worker
1114*9880d681SAndroid Build Coastguard Worker return false;
1115*9880d681SAndroid Build Coastguard Worker }
1116*9880d681SAndroid Build Coastguard Worker
visitSExt(SExtInst & CI)1117*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitSExt(SExtInst &CI) {
1118*9880d681SAndroid Build Coastguard Worker // If this sign extend is only used by a truncate, let the truncate be
1119*9880d681SAndroid Build Coastguard Worker // eliminated before we try to optimize this sext.
1120*9880d681SAndroid Build Coastguard Worker if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
1121*9880d681SAndroid Build Coastguard Worker return nullptr;
1122*9880d681SAndroid Build Coastguard Worker
1123*9880d681SAndroid Build Coastguard Worker if (Instruction *I = commonCastTransforms(CI))
1124*9880d681SAndroid Build Coastguard Worker return I;
1125*9880d681SAndroid Build Coastguard Worker
1126*9880d681SAndroid Build Coastguard Worker // See if we can simplify any instructions used by the input whose sole
1127*9880d681SAndroid Build Coastguard Worker // purpose is to compute bits we don't care about.
1128*9880d681SAndroid Build Coastguard Worker if (SimplifyDemandedInstructionBits(CI))
1129*9880d681SAndroid Build Coastguard Worker return &CI;
1130*9880d681SAndroid Build Coastguard Worker
1131*9880d681SAndroid Build Coastguard Worker Value *Src = CI.getOperand(0);
1132*9880d681SAndroid Build Coastguard Worker Type *SrcTy = Src->getType(), *DestTy = CI.getType();
1133*9880d681SAndroid Build Coastguard Worker
1134*9880d681SAndroid Build Coastguard Worker // If we know that the value being extended is positive, we can use a zext
1135*9880d681SAndroid Build Coastguard Worker // instead.
1136*9880d681SAndroid Build Coastguard Worker bool KnownZero, KnownOne;
1137*9880d681SAndroid Build Coastguard Worker ComputeSignBit(Src, KnownZero, KnownOne, 0, &CI);
1138*9880d681SAndroid Build Coastguard Worker if (KnownZero) {
1139*9880d681SAndroid Build Coastguard Worker Value *ZExt = Builder->CreateZExt(Src, DestTy);
1140*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(CI, ZExt);
1141*9880d681SAndroid Build Coastguard Worker }
1142*9880d681SAndroid Build Coastguard Worker
1143*9880d681SAndroid Build Coastguard Worker // Attempt to extend the entire input expression tree to the destination
1144*9880d681SAndroid Build Coastguard Worker // type. Only do this if the dest type is a simple type, don't convert the
1145*9880d681SAndroid Build Coastguard Worker // expression tree to something weird like i93 unless the source is also
1146*9880d681SAndroid Build Coastguard Worker // strange.
1147*9880d681SAndroid Build Coastguard Worker if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
1148*9880d681SAndroid Build Coastguard Worker canEvaluateSExtd(Src, DestTy)) {
1149*9880d681SAndroid Build Coastguard Worker // Okay, we can transform this! Insert the new expression now.
1150*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1151*9880d681SAndroid Build Coastguard Worker " to avoid sign extend: " << CI << '\n');
1152*9880d681SAndroid Build Coastguard Worker Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1153*9880d681SAndroid Build Coastguard Worker assert(Res->getType() == DestTy);
1154*9880d681SAndroid Build Coastguard Worker
1155*9880d681SAndroid Build Coastguard Worker uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1156*9880d681SAndroid Build Coastguard Worker uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1157*9880d681SAndroid Build Coastguard Worker
1158*9880d681SAndroid Build Coastguard Worker // If the high bits are already filled with sign bit, just replace this
1159*9880d681SAndroid Build Coastguard Worker // cast with the result.
1160*9880d681SAndroid Build Coastguard Worker if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize)
1161*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(CI, Res);
1162*9880d681SAndroid Build Coastguard Worker
1163*9880d681SAndroid Build Coastguard Worker // We need to emit a shl + ashr to do the sign extend.
1164*9880d681SAndroid Build Coastguard Worker Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1165*9880d681SAndroid Build Coastguard Worker return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
1166*9880d681SAndroid Build Coastguard Worker ShAmt);
1167*9880d681SAndroid Build Coastguard Worker }
1168*9880d681SAndroid Build Coastguard Worker
1169*9880d681SAndroid Build Coastguard Worker // If this input is a trunc from our destination, then turn sext(trunc(x))
1170*9880d681SAndroid Build Coastguard Worker // into shifts.
1171*9880d681SAndroid Build Coastguard Worker if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1172*9880d681SAndroid Build Coastguard Worker if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1173*9880d681SAndroid Build Coastguard Worker uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1174*9880d681SAndroid Build Coastguard Worker uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1175*9880d681SAndroid Build Coastguard Worker
1176*9880d681SAndroid Build Coastguard Worker // We need to emit a shl + ashr to do the sign extend.
1177*9880d681SAndroid Build Coastguard Worker Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1178*9880d681SAndroid Build Coastguard Worker Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1179*9880d681SAndroid Build Coastguard Worker return BinaryOperator::CreateAShr(Res, ShAmt);
1180*9880d681SAndroid Build Coastguard Worker }
1181*9880d681SAndroid Build Coastguard Worker
1182*9880d681SAndroid Build Coastguard Worker if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1183*9880d681SAndroid Build Coastguard Worker return transformSExtICmp(ICI, CI);
1184*9880d681SAndroid Build Coastguard Worker
1185*9880d681SAndroid Build Coastguard Worker // If the input is a shl/ashr pair of a same constant, then this is a sign
1186*9880d681SAndroid Build Coastguard Worker // extension from a smaller value. If we could trust arbitrary bitwidth
1187*9880d681SAndroid Build Coastguard Worker // integers, we could turn this into a truncate to the smaller bit and then
1188*9880d681SAndroid Build Coastguard Worker // use a sext for the whole extension. Since we don't, look deeper and check
1189*9880d681SAndroid Build Coastguard Worker // for a truncate. If the source and dest are the same type, eliminate the
1190*9880d681SAndroid Build Coastguard Worker // trunc and extend and just do shifts. For example, turn:
1191*9880d681SAndroid Build Coastguard Worker // %a = trunc i32 %i to i8
1192*9880d681SAndroid Build Coastguard Worker // %b = shl i8 %a, 6
1193*9880d681SAndroid Build Coastguard Worker // %c = ashr i8 %b, 6
1194*9880d681SAndroid Build Coastguard Worker // %d = sext i8 %c to i32
1195*9880d681SAndroid Build Coastguard Worker // into:
1196*9880d681SAndroid Build Coastguard Worker // %a = shl i32 %i, 30
1197*9880d681SAndroid Build Coastguard Worker // %d = ashr i32 %a, 30
1198*9880d681SAndroid Build Coastguard Worker Value *A = nullptr;
1199*9880d681SAndroid Build Coastguard Worker // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
1200*9880d681SAndroid Build Coastguard Worker ConstantInt *BA = nullptr, *CA = nullptr;
1201*9880d681SAndroid Build Coastguard Worker if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
1202*9880d681SAndroid Build Coastguard Worker m_ConstantInt(CA))) &&
1203*9880d681SAndroid Build Coastguard Worker BA == CA && A->getType() == CI.getType()) {
1204*9880d681SAndroid Build Coastguard Worker unsigned MidSize = Src->getType()->getScalarSizeInBits();
1205*9880d681SAndroid Build Coastguard Worker unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1206*9880d681SAndroid Build Coastguard Worker unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1207*9880d681SAndroid Build Coastguard Worker Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1208*9880d681SAndroid Build Coastguard Worker A = Builder->CreateShl(A, ShAmtV, CI.getName());
1209*9880d681SAndroid Build Coastguard Worker return BinaryOperator::CreateAShr(A, ShAmtV);
1210*9880d681SAndroid Build Coastguard Worker }
1211*9880d681SAndroid Build Coastguard Worker
1212*9880d681SAndroid Build Coastguard Worker return nullptr;
1213*9880d681SAndroid Build Coastguard Worker }
1214*9880d681SAndroid Build Coastguard Worker
1215*9880d681SAndroid Build Coastguard Worker
1216*9880d681SAndroid Build Coastguard Worker /// Return a Constant* for the specified floating-point constant if it fits
1217*9880d681SAndroid Build Coastguard Worker /// in the specified FP type without changing its value.
fitsInFPType(ConstantFP * CFP,const fltSemantics & Sem)1218*9880d681SAndroid Build Coastguard Worker static Constant *fitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1219*9880d681SAndroid Build Coastguard Worker bool losesInfo;
1220*9880d681SAndroid Build Coastguard Worker APFloat F = CFP->getValueAPF();
1221*9880d681SAndroid Build Coastguard Worker (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1222*9880d681SAndroid Build Coastguard Worker if (!losesInfo)
1223*9880d681SAndroid Build Coastguard Worker return ConstantFP::get(CFP->getContext(), F);
1224*9880d681SAndroid Build Coastguard Worker return nullptr;
1225*9880d681SAndroid Build Coastguard Worker }
1226*9880d681SAndroid Build Coastguard Worker
1227*9880d681SAndroid Build Coastguard Worker /// If this is a floating-point extension instruction, look
1228*9880d681SAndroid Build Coastguard Worker /// through it until we get the source value.
lookThroughFPExtensions(Value * V)1229*9880d681SAndroid Build Coastguard Worker static Value *lookThroughFPExtensions(Value *V) {
1230*9880d681SAndroid Build Coastguard Worker if (Instruction *I = dyn_cast<Instruction>(V))
1231*9880d681SAndroid Build Coastguard Worker if (I->getOpcode() == Instruction::FPExt)
1232*9880d681SAndroid Build Coastguard Worker return lookThroughFPExtensions(I->getOperand(0));
1233*9880d681SAndroid Build Coastguard Worker
1234*9880d681SAndroid Build Coastguard Worker // If this value is a constant, return the constant in the smallest FP type
1235*9880d681SAndroid Build Coastguard Worker // that can accurately represent it. This allows us to turn
1236*9880d681SAndroid Build Coastguard Worker // (float)((double)X+2.0) into x+2.0f.
1237*9880d681SAndroid Build Coastguard Worker if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1238*9880d681SAndroid Build Coastguard Worker if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1239*9880d681SAndroid Build Coastguard Worker return V; // No constant folding of this.
1240*9880d681SAndroid Build Coastguard Worker // See if the value can be truncated to half and then reextended.
1241*9880d681SAndroid Build Coastguard Worker if (Value *V = fitsInFPType(CFP, APFloat::IEEEhalf))
1242*9880d681SAndroid Build Coastguard Worker return V;
1243*9880d681SAndroid Build Coastguard Worker // See if the value can be truncated to float and then reextended.
1244*9880d681SAndroid Build Coastguard Worker if (Value *V = fitsInFPType(CFP, APFloat::IEEEsingle))
1245*9880d681SAndroid Build Coastguard Worker return V;
1246*9880d681SAndroid Build Coastguard Worker if (CFP->getType()->isDoubleTy())
1247*9880d681SAndroid Build Coastguard Worker return V; // Won't shrink.
1248*9880d681SAndroid Build Coastguard Worker if (Value *V = fitsInFPType(CFP, APFloat::IEEEdouble))
1249*9880d681SAndroid Build Coastguard Worker return V;
1250*9880d681SAndroid Build Coastguard Worker // Don't try to shrink to various long double types.
1251*9880d681SAndroid Build Coastguard Worker }
1252*9880d681SAndroid Build Coastguard Worker
1253*9880d681SAndroid Build Coastguard Worker return V;
1254*9880d681SAndroid Build Coastguard Worker }
1255*9880d681SAndroid Build Coastguard Worker
visitFPTrunc(FPTruncInst & CI)1256*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1257*9880d681SAndroid Build Coastguard Worker if (Instruction *I = commonCastTransforms(CI))
1258*9880d681SAndroid Build Coastguard Worker return I;
1259*9880d681SAndroid Build Coastguard Worker // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
1260*9880d681SAndroid Build Coastguard Worker // simplify this expression to avoid one or more of the trunc/extend
1261*9880d681SAndroid Build Coastguard Worker // operations if we can do so without changing the numerical results.
1262*9880d681SAndroid Build Coastguard Worker //
1263*9880d681SAndroid Build Coastguard Worker // The exact manner in which the widths of the operands interact to limit
1264*9880d681SAndroid Build Coastguard Worker // what we can and cannot do safely varies from operation to operation, and
1265*9880d681SAndroid Build Coastguard Worker // is explained below in the various case statements.
1266*9880d681SAndroid Build Coastguard Worker BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1267*9880d681SAndroid Build Coastguard Worker if (OpI && OpI->hasOneUse()) {
1268*9880d681SAndroid Build Coastguard Worker Value *LHSOrig = lookThroughFPExtensions(OpI->getOperand(0));
1269*9880d681SAndroid Build Coastguard Worker Value *RHSOrig = lookThroughFPExtensions(OpI->getOperand(1));
1270*9880d681SAndroid Build Coastguard Worker unsigned OpWidth = OpI->getType()->getFPMantissaWidth();
1271*9880d681SAndroid Build Coastguard Worker unsigned LHSWidth = LHSOrig->getType()->getFPMantissaWidth();
1272*9880d681SAndroid Build Coastguard Worker unsigned RHSWidth = RHSOrig->getType()->getFPMantissaWidth();
1273*9880d681SAndroid Build Coastguard Worker unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
1274*9880d681SAndroid Build Coastguard Worker unsigned DstWidth = CI.getType()->getFPMantissaWidth();
1275*9880d681SAndroid Build Coastguard Worker switch (OpI->getOpcode()) {
1276*9880d681SAndroid Build Coastguard Worker default: break;
1277*9880d681SAndroid Build Coastguard Worker case Instruction::FAdd:
1278*9880d681SAndroid Build Coastguard Worker case Instruction::FSub:
1279*9880d681SAndroid Build Coastguard Worker // For addition and subtraction, the infinitely precise result can
1280*9880d681SAndroid Build Coastguard Worker // essentially be arbitrarily wide; proving that double rounding
1281*9880d681SAndroid Build Coastguard Worker // will not occur because the result of OpI is exact (as we will for
1282*9880d681SAndroid Build Coastguard Worker // FMul, for example) is hopeless. However, we *can* nonetheless
1283*9880d681SAndroid Build Coastguard Worker // frequently know that double rounding cannot occur (or that it is
1284*9880d681SAndroid Build Coastguard Worker // innocuous) by taking advantage of the specific structure of
1285*9880d681SAndroid Build Coastguard Worker // infinitely-precise results that admit double rounding.
1286*9880d681SAndroid Build Coastguard Worker //
1287*9880d681SAndroid Build Coastguard Worker // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
1288*9880d681SAndroid Build Coastguard Worker // to represent both sources, we can guarantee that the double
1289*9880d681SAndroid Build Coastguard Worker // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
1290*9880d681SAndroid Build Coastguard Worker // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
1291*9880d681SAndroid Build Coastguard Worker // for proof of this fact).
1292*9880d681SAndroid Build Coastguard Worker //
1293*9880d681SAndroid Build Coastguard Worker // Note: Figueroa does not consider the case where DstFormat !=
1294*9880d681SAndroid Build Coastguard Worker // SrcFormat. It's possible (likely even!) that this analysis
1295*9880d681SAndroid Build Coastguard Worker // could be tightened for those cases, but they are rare (the main
1296*9880d681SAndroid Build Coastguard Worker // case of interest here is (float)((double)float + float)).
1297*9880d681SAndroid Build Coastguard Worker if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
1298*9880d681SAndroid Build Coastguard Worker if (LHSOrig->getType() != CI.getType())
1299*9880d681SAndroid Build Coastguard Worker LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1300*9880d681SAndroid Build Coastguard Worker if (RHSOrig->getType() != CI.getType())
1301*9880d681SAndroid Build Coastguard Worker RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
1302*9880d681SAndroid Build Coastguard Worker Instruction *RI =
1303*9880d681SAndroid Build Coastguard Worker BinaryOperator::Create(OpI->getOpcode(), LHSOrig, RHSOrig);
1304*9880d681SAndroid Build Coastguard Worker RI->copyFastMathFlags(OpI);
1305*9880d681SAndroid Build Coastguard Worker return RI;
1306*9880d681SAndroid Build Coastguard Worker }
1307*9880d681SAndroid Build Coastguard Worker break;
1308*9880d681SAndroid Build Coastguard Worker case Instruction::FMul:
1309*9880d681SAndroid Build Coastguard Worker // For multiplication, the infinitely precise result has at most
1310*9880d681SAndroid Build Coastguard Worker // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
1311*9880d681SAndroid Build Coastguard Worker // that such a value can be exactly represented, then no double
1312*9880d681SAndroid Build Coastguard Worker // rounding can possibly occur; we can safely perform the operation
1313*9880d681SAndroid Build Coastguard Worker // in the destination format if it can represent both sources.
1314*9880d681SAndroid Build Coastguard Worker if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
1315*9880d681SAndroid Build Coastguard Worker if (LHSOrig->getType() != CI.getType())
1316*9880d681SAndroid Build Coastguard Worker LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1317*9880d681SAndroid Build Coastguard Worker if (RHSOrig->getType() != CI.getType())
1318*9880d681SAndroid Build Coastguard Worker RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
1319*9880d681SAndroid Build Coastguard Worker Instruction *RI =
1320*9880d681SAndroid Build Coastguard Worker BinaryOperator::CreateFMul(LHSOrig, RHSOrig);
1321*9880d681SAndroid Build Coastguard Worker RI->copyFastMathFlags(OpI);
1322*9880d681SAndroid Build Coastguard Worker return RI;
1323*9880d681SAndroid Build Coastguard Worker }
1324*9880d681SAndroid Build Coastguard Worker break;
1325*9880d681SAndroid Build Coastguard Worker case Instruction::FDiv:
1326*9880d681SAndroid Build Coastguard Worker // For division, we use again use the bound from Figueroa's
1327*9880d681SAndroid Build Coastguard Worker // dissertation. I am entirely certain that this bound can be
1328*9880d681SAndroid Build Coastguard Worker // tightened in the unbalanced operand case by an analysis based on
1329*9880d681SAndroid Build Coastguard Worker // the diophantine rational approximation bound, but the well-known
1330*9880d681SAndroid Build Coastguard Worker // condition used here is a good conservative first pass.
1331*9880d681SAndroid Build Coastguard Worker // TODO: Tighten bound via rigorous analysis of the unbalanced case.
1332*9880d681SAndroid Build Coastguard Worker if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
1333*9880d681SAndroid Build Coastguard Worker if (LHSOrig->getType() != CI.getType())
1334*9880d681SAndroid Build Coastguard Worker LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1335*9880d681SAndroid Build Coastguard Worker if (RHSOrig->getType() != CI.getType())
1336*9880d681SAndroid Build Coastguard Worker RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
1337*9880d681SAndroid Build Coastguard Worker Instruction *RI =
1338*9880d681SAndroid Build Coastguard Worker BinaryOperator::CreateFDiv(LHSOrig, RHSOrig);
1339*9880d681SAndroid Build Coastguard Worker RI->copyFastMathFlags(OpI);
1340*9880d681SAndroid Build Coastguard Worker return RI;
1341*9880d681SAndroid Build Coastguard Worker }
1342*9880d681SAndroid Build Coastguard Worker break;
1343*9880d681SAndroid Build Coastguard Worker case Instruction::FRem:
1344*9880d681SAndroid Build Coastguard Worker // Remainder is straightforward. Remainder is always exact, so the
1345*9880d681SAndroid Build Coastguard Worker // type of OpI doesn't enter into things at all. We simply evaluate
1346*9880d681SAndroid Build Coastguard Worker // in whichever source type is larger, then convert to the
1347*9880d681SAndroid Build Coastguard Worker // destination type.
1348*9880d681SAndroid Build Coastguard Worker if (SrcWidth == OpWidth)
1349*9880d681SAndroid Build Coastguard Worker break;
1350*9880d681SAndroid Build Coastguard Worker if (LHSWidth < SrcWidth)
1351*9880d681SAndroid Build Coastguard Worker LHSOrig = Builder->CreateFPExt(LHSOrig, RHSOrig->getType());
1352*9880d681SAndroid Build Coastguard Worker else if (RHSWidth <= SrcWidth)
1353*9880d681SAndroid Build Coastguard Worker RHSOrig = Builder->CreateFPExt(RHSOrig, LHSOrig->getType());
1354*9880d681SAndroid Build Coastguard Worker if (LHSOrig != OpI->getOperand(0) || RHSOrig != OpI->getOperand(1)) {
1355*9880d681SAndroid Build Coastguard Worker Value *ExactResult = Builder->CreateFRem(LHSOrig, RHSOrig);
1356*9880d681SAndroid Build Coastguard Worker if (Instruction *RI = dyn_cast<Instruction>(ExactResult))
1357*9880d681SAndroid Build Coastguard Worker RI->copyFastMathFlags(OpI);
1358*9880d681SAndroid Build Coastguard Worker return CastInst::CreateFPCast(ExactResult, CI.getType());
1359*9880d681SAndroid Build Coastguard Worker }
1360*9880d681SAndroid Build Coastguard Worker }
1361*9880d681SAndroid Build Coastguard Worker
1362*9880d681SAndroid Build Coastguard Worker // (fptrunc (fneg x)) -> (fneg (fptrunc x))
1363*9880d681SAndroid Build Coastguard Worker if (BinaryOperator::isFNeg(OpI)) {
1364*9880d681SAndroid Build Coastguard Worker Value *InnerTrunc = Builder->CreateFPTrunc(OpI->getOperand(1),
1365*9880d681SAndroid Build Coastguard Worker CI.getType());
1366*9880d681SAndroid Build Coastguard Worker Instruction *RI = BinaryOperator::CreateFNeg(InnerTrunc);
1367*9880d681SAndroid Build Coastguard Worker RI->copyFastMathFlags(OpI);
1368*9880d681SAndroid Build Coastguard Worker return RI;
1369*9880d681SAndroid Build Coastguard Worker }
1370*9880d681SAndroid Build Coastguard Worker }
1371*9880d681SAndroid Build Coastguard Worker
1372*9880d681SAndroid Build Coastguard Worker // (fptrunc (select cond, R1, Cst)) -->
1373*9880d681SAndroid Build Coastguard Worker // (select cond, (fptrunc R1), (fptrunc Cst))
1374*9880d681SAndroid Build Coastguard Worker //
1375*9880d681SAndroid Build Coastguard Worker // - but only if this isn't part of a min/max operation, else we'll
1376*9880d681SAndroid Build Coastguard Worker // ruin min/max canonical form which is to have the select and
1377*9880d681SAndroid Build Coastguard Worker // compare's operands be of the same type with no casts to look through.
1378*9880d681SAndroid Build Coastguard Worker Value *LHS, *RHS;
1379*9880d681SAndroid Build Coastguard Worker SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0));
1380*9880d681SAndroid Build Coastguard Worker if (SI &&
1381*9880d681SAndroid Build Coastguard Worker (isa<ConstantFP>(SI->getOperand(1)) ||
1382*9880d681SAndroid Build Coastguard Worker isa<ConstantFP>(SI->getOperand(2))) &&
1383*9880d681SAndroid Build Coastguard Worker matchSelectPattern(SI, LHS, RHS).Flavor == SPF_UNKNOWN) {
1384*9880d681SAndroid Build Coastguard Worker Value *LHSTrunc = Builder->CreateFPTrunc(SI->getOperand(1),
1385*9880d681SAndroid Build Coastguard Worker CI.getType());
1386*9880d681SAndroid Build Coastguard Worker Value *RHSTrunc = Builder->CreateFPTrunc(SI->getOperand(2),
1387*9880d681SAndroid Build Coastguard Worker CI.getType());
1388*9880d681SAndroid Build Coastguard Worker return SelectInst::Create(SI->getOperand(0), LHSTrunc, RHSTrunc);
1389*9880d681SAndroid Build Coastguard Worker }
1390*9880d681SAndroid Build Coastguard Worker
1391*9880d681SAndroid Build Coastguard Worker IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI.getOperand(0));
1392*9880d681SAndroid Build Coastguard Worker if (II) {
1393*9880d681SAndroid Build Coastguard Worker switch (II->getIntrinsicID()) {
1394*9880d681SAndroid Build Coastguard Worker default: break;
1395*9880d681SAndroid Build Coastguard Worker case Intrinsic::fabs: {
1396*9880d681SAndroid Build Coastguard Worker // (fptrunc (fabs x)) -> (fabs (fptrunc x))
1397*9880d681SAndroid Build Coastguard Worker Value *InnerTrunc = Builder->CreateFPTrunc(II->getArgOperand(0),
1398*9880d681SAndroid Build Coastguard Worker CI.getType());
1399*9880d681SAndroid Build Coastguard Worker Type *IntrinsicType[] = { CI.getType() };
1400*9880d681SAndroid Build Coastguard Worker Function *Overload = Intrinsic::getDeclaration(
1401*9880d681SAndroid Build Coastguard Worker CI.getModule(), II->getIntrinsicID(), IntrinsicType);
1402*9880d681SAndroid Build Coastguard Worker
1403*9880d681SAndroid Build Coastguard Worker SmallVector<OperandBundleDef, 1> OpBundles;
1404*9880d681SAndroid Build Coastguard Worker II->getOperandBundlesAsDefs(OpBundles);
1405*9880d681SAndroid Build Coastguard Worker
1406*9880d681SAndroid Build Coastguard Worker Value *Args[] = { InnerTrunc };
1407*9880d681SAndroid Build Coastguard Worker return CallInst::Create(Overload, Args, OpBundles, II->getName());
1408*9880d681SAndroid Build Coastguard Worker }
1409*9880d681SAndroid Build Coastguard Worker }
1410*9880d681SAndroid Build Coastguard Worker }
1411*9880d681SAndroid Build Coastguard Worker
1412*9880d681SAndroid Build Coastguard Worker return nullptr;
1413*9880d681SAndroid Build Coastguard Worker }
1414*9880d681SAndroid Build Coastguard Worker
visitFPExt(CastInst & CI)1415*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1416*9880d681SAndroid Build Coastguard Worker return commonCastTransforms(CI);
1417*9880d681SAndroid Build Coastguard Worker }
1418*9880d681SAndroid Build Coastguard Worker
1419*9880d681SAndroid Build Coastguard Worker // fpto{s/u}i({u/s}itofp(X)) --> X or zext(X) or sext(X) or trunc(X)
1420*9880d681SAndroid Build Coastguard Worker // This is safe if the intermediate type has enough bits in its mantissa to
1421*9880d681SAndroid Build Coastguard Worker // accurately represent all values of X. For example, this won't work with
1422*9880d681SAndroid Build Coastguard Worker // i64 -> float -> i64.
FoldItoFPtoI(Instruction & FI)1423*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::FoldItoFPtoI(Instruction &FI) {
1424*9880d681SAndroid Build Coastguard Worker if (!isa<UIToFPInst>(FI.getOperand(0)) && !isa<SIToFPInst>(FI.getOperand(0)))
1425*9880d681SAndroid Build Coastguard Worker return nullptr;
1426*9880d681SAndroid Build Coastguard Worker Instruction *OpI = cast<Instruction>(FI.getOperand(0));
1427*9880d681SAndroid Build Coastguard Worker
1428*9880d681SAndroid Build Coastguard Worker Value *SrcI = OpI->getOperand(0);
1429*9880d681SAndroid Build Coastguard Worker Type *FITy = FI.getType();
1430*9880d681SAndroid Build Coastguard Worker Type *OpITy = OpI->getType();
1431*9880d681SAndroid Build Coastguard Worker Type *SrcTy = SrcI->getType();
1432*9880d681SAndroid Build Coastguard Worker bool IsInputSigned = isa<SIToFPInst>(OpI);
1433*9880d681SAndroid Build Coastguard Worker bool IsOutputSigned = isa<FPToSIInst>(FI);
1434*9880d681SAndroid Build Coastguard Worker
1435*9880d681SAndroid Build Coastguard Worker // We can safely assume the conversion won't overflow the output range,
1436*9880d681SAndroid Build Coastguard Worker // because (for example) (uint8_t)18293.f is undefined behavior.
1437*9880d681SAndroid Build Coastguard Worker
1438*9880d681SAndroid Build Coastguard Worker // Since we can assume the conversion won't overflow, our decision as to
1439*9880d681SAndroid Build Coastguard Worker // whether the input will fit in the float should depend on the minimum
1440*9880d681SAndroid Build Coastguard Worker // of the input range and output range.
1441*9880d681SAndroid Build Coastguard Worker
1442*9880d681SAndroid Build Coastguard Worker // This means this is also safe for a signed input and unsigned output, since
1443*9880d681SAndroid Build Coastguard Worker // a negative input would lead to undefined behavior.
1444*9880d681SAndroid Build Coastguard Worker int InputSize = (int)SrcTy->getScalarSizeInBits() - IsInputSigned;
1445*9880d681SAndroid Build Coastguard Worker int OutputSize = (int)FITy->getScalarSizeInBits() - IsOutputSigned;
1446*9880d681SAndroid Build Coastguard Worker int ActualSize = std::min(InputSize, OutputSize);
1447*9880d681SAndroid Build Coastguard Worker
1448*9880d681SAndroid Build Coastguard Worker if (ActualSize <= OpITy->getFPMantissaWidth()) {
1449*9880d681SAndroid Build Coastguard Worker if (FITy->getScalarSizeInBits() > SrcTy->getScalarSizeInBits()) {
1450*9880d681SAndroid Build Coastguard Worker if (IsInputSigned && IsOutputSigned)
1451*9880d681SAndroid Build Coastguard Worker return new SExtInst(SrcI, FITy);
1452*9880d681SAndroid Build Coastguard Worker return new ZExtInst(SrcI, FITy);
1453*9880d681SAndroid Build Coastguard Worker }
1454*9880d681SAndroid Build Coastguard Worker if (FITy->getScalarSizeInBits() < SrcTy->getScalarSizeInBits())
1455*9880d681SAndroid Build Coastguard Worker return new TruncInst(SrcI, FITy);
1456*9880d681SAndroid Build Coastguard Worker if (SrcTy == FITy)
1457*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(FI, SrcI);
1458*9880d681SAndroid Build Coastguard Worker return new BitCastInst(SrcI, FITy);
1459*9880d681SAndroid Build Coastguard Worker }
1460*9880d681SAndroid Build Coastguard Worker return nullptr;
1461*9880d681SAndroid Build Coastguard Worker }
1462*9880d681SAndroid Build Coastguard Worker
visitFPToUI(FPToUIInst & FI)1463*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1464*9880d681SAndroid Build Coastguard Worker Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1465*9880d681SAndroid Build Coastguard Worker if (!OpI)
1466*9880d681SAndroid Build Coastguard Worker return commonCastTransforms(FI);
1467*9880d681SAndroid Build Coastguard Worker
1468*9880d681SAndroid Build Coastguard Worker if (Instruction *I = FoldItoFPtoI(FI))
1469*9880d681SAndroid Build Coastguard Worker return I;
1470*9880d681SAndroid Build Coastguard Worker
1471*9880d681SAndroid Build Coastguard Worker return commonCastTransforms(FI);
1472*9880d681SAndroid Build Coastguard Worker }
1473*9880d681SAndroid Build Coastguard Worker
visitFPToSI(FPToSIInst & FI)1474*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1475*9880d681SAndroid Build Coastguard Worker Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1476*9880d681SAndroid Build Coastguard Worker if (!OpI)
1477*9880d681SAndroid Build Coastguard Worker return commonCastTransforms(FI);
1478*9880d681SAndroid Build Coastguard Worker
1479*9880d681SAndroid Build Coastguard Worker if (Instruction *I = FoldItoFPtoI(FI))
1480*9880d681SAndroid Build Coastguard Worker return I;
1481*9880d681SAndroid Build Coastguard Worker
1482*9880d681SAndroid Build Coastguard Worker return commonCastTransforms(FI);
1483*9880d681SAndroid Build Coastguard Worker }
1484*9880d681SAndroid Build Coastguard Worker
visitUIToFP(CastInst & CI)1485*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1486*9880d681SAndroid Build Coastguard Worker return commonCastTransforms(CI);
1487*9880d681SAndroid Build Coastguard Worker }
1488*9880d681SAndroid Build Coastguard Worker
visitSIToFP(CastInst & CI)1489*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1490*9880d681SAndroid Build Coastguard Worker return commonCastTransforms(CI);
1491*9880d681SAndroid Build Coastguard Worker }
1492*9880d681SAndroid Build Coastguard Worker
visitIntToPtr(IntToPtrInst & CI)1493*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1494*9880d681SAndroid Build Coastguard Worker // If the source integer type is not the intptr_t type for this target, do a
1495*9880d681SAndroid Build Coastguard Worker // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1496*9880d681SAndroid Build Coastguard Worker // cast to be exposed to other transforms.
1497*9880d681SAndroid Build Coastguard Worker unsigned AS = CI.getAddressSpace();
1498*9880d681SAndroid Build Coastguard Worker if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
1499*9880d681SAndroid Build Coastguard Worker DL.getPointerSizeInBits(AS)) {
1500*9880d681SAndroid Build Coastguard Worker Type *Ty = DL.getIntPtrType(CI.getContext(), AS);
1501*9880d681SAndroid Build Coastguard Worker if (CI.getType()->isVectorTy()) // Handle vectors of pointers.
1502*9880d681SAndroid Build Coastguard Worker Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements());
1503*9880d681SAndroid Build Coastguard Worker
1504*9880d681SAndroid Build Coastguard Worker Value *P = Builder->CreateZExtOrTrunc(CI.getOperand(0), Ty);
1505*9880d681SAndroid Build Coastguard Worker return new IntToPtrInst(P, CI.getType());
1506*9880d681SAndroid Build Coastguard Worker }
1507*9880d681SAndroid Build Coastguard Worker
1508*9880d681SAndroid Build Coastguard Worker if (Instruction *I = commonCastTransforms(CI))
1509*9880d681SAndroid Build Coastguard Worker return I;
1510*9880d681SAndroid Build Coastguard Worker
1511*9880d681SAndroid Build Coastguard Worker return nullptr;
1512*9880d681SAndroid Build Coastguard Worker }
1513*9880d681SAndroid Build Coastguard Worker
1514*9880d681SAndroid Build Coastguard Worker /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
commonPointerCastTransforms(CastInst & CI)1515*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1516*9880d681SAndroid Build Coastguard Worker Value *Src = CI.getOperand(0);
1517*9880d681SAndroid Build Coastguard Worker
1518*9880d681SAndroid Build Coastguard Worker if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1519*9880d681SAndroid Build Coastguard Worker // If casting the result of a getelementptr instruction with no offset, turn
1520*9880d681SAndroid Build Coastguard Worker // this into a cast of the original pointer!
1521*9880d681SAndroid Build Coastguard Worker if (GEP->hasAllZeroIndices() &&
1522*9880d681SAndroid Build Coastguard Worker // If CI is an addrspacecast and GEP changes the poiner type, merging
1523*9880d681SAndroid Build Coastguard Worker // GEP into CI would undo canonicalizing addrspacecast with different
1524*9880d681SAndroid Build Coastguard Worker // pointer types, causing infinite loops.
1525*9880d681SAndroid Build Coastguard Worker (!isa<AddrSpaceCastInst>(CI) ||
1526*9880d681SAndroid Build Coastguard Worker GEP->getType() == GEP->getPointerOperand()->getType())) {
1527*9880d681SAndroid Build Coastguard Worker // Changing the cast operand is usually not a good idea but it is safe
1528*9880d681SAndroid Build Coastguard Worker // here because the pointer operand is being replaced with another
1529*9880d681SAndroid Build Coastguard Worker // pointer operand so the opcode doesn't need to change.
1530*9880d681SAndroid Build Coastguard Worker Worklist.Add(GEP);
1531*9880d681SAndroid Build Coastguard Worker CI.setOperand(0, GEP->getOperand(0));
1532*9880d681SAndroid Build Coastguard Worker return &CI;
1533*9880d681SAndroid Build Coastguard Worker }
1534*9880d681SAndroid Build Coastguard Worker }
1535*9880d681SAndroid Build Coastguard Worker
1536*9880d681SAndroid Build Coastguard Worker return commonCastTransforms(CI);
1537*9880d681SAndroid Build Coastguard Worker }
1538*9880d681SAndroid Build Coastguard Worker
visitPtrToInt(PtrToIntInst & CI)1539*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1540*9880d681SAndroid Build Coastguard Worker // If the destination integer type is not the intptr_t type for this target,
1541*9880d681SAndroid Build Coastguard Worker // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1542*9880d681SAndroid Build Coastguard Worker // to be exposed to other transforms.
1543*9880d681SAndroid Build Coastguard Worker
1544*9880d681SAndroid Build Coastguard Worker Type *Ty = CI.getType();
1545*9880d681SAndroid Build Coastguard Worker unsigned AS = CI.getPointerAddressSpace();
1546*9880d681SAndroid Build Coastguard Worker
1547*9880d681SAndroid Build Coastguard Worker if (Ty->getScalarSizeInBits() == DL.getPointerSizeInBits(AS))
1548*9880d681SAndroid Build Coastguard Worker return commonPointerCastTransforms(CI);
1549*9880d681SAndroid Build Coastguard Worker
1550*9880d681SAndroid Build Coastguard Worker Type *PtrTy = DL.getIntPtrType(CI.getContext(), AS);
1551*9880d681SAndroid Build Coastguard Worker if (Ty->isVectorTy()) // Handle vectors of pointers.
1552*9880d681SAndroid Build Coastguard Worker PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements());
1553*9880d681SAndroid Build Coastguard Worker
1554*9880d681SAndroid Build Coastguard Worker Value *P = Builder->CreatePtrToInt(CI.getOperand(0), PtrTy);
1555*9880d681SAndroid Build Coastguard Worker return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
1556*9880d681SAndroid Build Coastguard Worker }
1557*9880d681SAndroid Build Coastguard Worker
1558*9880d681SAndroid Build Coastguard Worker /// This input value (which is known to have vector type) is being zero extended
1559*9880d681SAndroid Build Coastguard Worker /// or truncated to the specified vector type.
1560*9880d681SAndroid Build Coastguard Worker /// Try to replace it with a shuffle (and vector/vector bitcast) if possible.
1561*9880d681SAndroid Build Coastguard Worker ///
1562*9880d681SAndroid Build Coastguard Worker /// The source and destination vector types may have different element types.
optimizeVectorResize(Value * InVal,VectorType * DestTy,InstCombiner & IC)1563*9880d681SAndroid Build Coastguard Worker static Instruction *optimizeVectorResize(Value *InVal, VectorType *DestTy,
1564*9880d681SAndroid Build Coastguard Worker InstCombiner &IC) {
1565*9880d681SAndroid Build Coastguard Worker // We can only do this optimization if the output is a multiple of the input
1566*9880d681SAndroid Build Coastguard Worker // element size, or the input is a multiple of the output element size.
1567*9880d681SAndroid Build Coastguard Worker // Convert the input type to have the same element type as the output.
1568*9880d681SAndroid Build Coastguard Worker VectorType *SrcTy = cast<VectorType>(InVal->getType());
1569*9880d681SAndroid Build Coastguard Worker
1570*9880d681SAndroid Build Coastguard Worker if (SrcTy->getElementType() != DestTy->getElementType()) {
1571*9880d681SAndroid Build Coastguard Worker // The input types don't need to be identical, but for now they must be the
1572*9880d681SAndroid Build Coastguard Worker // same size. There is no specific reason we couldn't handle things like
1573*9880d681SAndroid Build Coastguard Worker // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
1574*9880d681SAndroid Build Coastguard Worker // there yet.
1575*9880d681SAndroid Build Coastguard Worker if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1576*9880d681SAndroid Build Coastguard Worker DestTy->getElementType()->getPrimitiveSizeInBits())
1577*9880d681SAndroid Build Coastguard Worker return nullptr;
1578*9880d681SAndroid Build Coastguard Worker
1579*9880d681SAndroid Build Coastguard Worker SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1580*9880d681SAndroid Build Coastguard Worker InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1581*9880d681SAndroid Build Coastguard Worker }
1582*9880d681SAndroid Build Coastguard Worker
1583*9880d681SAndroid Build Coastguard Worker // Now that the element types match, get the shuffle mask and RHS of the
1584*9880d681SAndroid Build Coastguard Worker // shuffle to use, which depends on whether we're increasing or decreasing the
1585*9880d681SAndroid Build Coastguard Worker // size of the input.
1586*9880d681SAndroid Build Coastguard Worker SmallVector<uint32_t, 16> ShuffleMask;
1587*9880d681SAndroid Build Coastguard Worker Value *V2;
1588*9880d681SAndroid Build Coastguard Worker
1589*9880d681SAndroid Build Coastguard Worker if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1590*9880d681SAndroid Build Coastguard Worker // If we're shrinking the number of elements, just shuffle in the low
1591*9880d681SAndroid Build Coastguard Worker // elements from the input and use undef as the second shuffle input.
1592*9880d681SAndroid Build Coastguard Worker V2 = UndefValue::get(SrcTy);
1593*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
1594*9880d681SAndroid Build Coastguard Worker ShuffleMask.push_back(i);
1595*9880d681SAndroid Build Coastguard Worker
1596*9880d681SAndroid Build Coastguard Worker } else {
1597*9880d681SAndroid Build Coastguard Worker // If we're increasing the number of elements, shuffle in all of the
1598*9880d681SAndroid Build Coastguard Worker // elements from InVal and fill the rest of the result elements with zeros
1599*9880d681SAndroid Build Coastguard Worker // from a constant zero.
1600*9880d681SAndroid Build Coastguard Worker V2 = Constant::getNullValue(SrcTy);
1601*9880d681SAndroid Build Coastguard Worker unsigned SrcElts = SrcTy->getNumElements();
1602*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = SrcElts; i != e; ++i)
1603*9880d681SAndroid Build Coastguard Worker ShuffleMask.push_back(i);
1604*9880d681SAndroid Build Coastguard Worker
1605*9880d681SAndroid Build Coastguard Worker // The excess elements reference the first element of the zero input.
1606*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i)
1607*9880d681SAndroid Build Coastguard Worker ShuffleMask.push_back(SrcElts);
1608*9880d681SAndroid Build Coastguard Worker }
1609*9880d681SAndroid Build Coastguard Worker
1610*9880d681SAndroid Build Coastguard Worker return new ShuffleVectorInst(InVal, V2,
1611*9880d681SAndroid Build Coastguard Worker ConstantDataVector::get(V2->getContext(),
1612*9880d681SAndroid Build Coastguard Worker ShuffleMask));
1613*9880d681SAndroid Build Coastguard Worker }
1614*9880d681SAndroid Build Coastguard Worker
isMultipleOfTypeSize(unsigned Value,Type * Ty)1615*9880d681SAndroid Build Coastguard Worker static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
1616*9880d681SAndroid Build Coastguard Worker return Value % Ty->getPrimitiveSizeInBits() == 0;
1617*9880d681SAndroid Build Coastguard Worker }
1618*9880d681SAndroid Build Coastguard Worker
getTypeSizeIndex(unsigned Value,Type * Ty)1619*9880d681SAndroid Build Coastguard Worker static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
1620*9880d681SAndroid Build Coastguard Worker return Value / Ty->getPrimitiveSizeInBits();
1621*9880d681SAndroid Build Coastguard Worker }
1622*9880d681SAndroid Build Coastguard Worker
1623*9880d681SAndroid Build Coastguard Worker /// V is a value which is inserted into a vector of VecEltTy.
1624*9880d681SAndroid Build Coastguard Worker /// Look through the value to see if we can decompose it into
1625*9880d681SAndroid Build Coastguard Worker /// insertions into the vector. See the example in the comment for
1626*9880d681SAndroid Build Coastguard Worker /// OptimizeIntegerToVectorInsertions for the pattern this handles.
1627*9880d681SAndroid Build Coastguard Worker /// The type of V is always a non-zero multiple of VecEltTy's size.
1628*9880d681SAndroid Build Coastguard Worker /// Shift is the number of bits between the lsb of V and the lsb of
1629*9880d681SAndroid Build Coastguard Worker /// the vector.
1630*9880d681SAndroid Build Coastguard Worker ///
1631*9880d681SAndroid Build Coastguard Worker /// This returns false if the pattern can't be matched or true if it can,
1632*9880d681SAndroid Build Coastguard Worker /// filling in Elements with the elements found here.
collectInsertionElements(Value * V,unsigned Shift,SmallVectorImpl<Value * > & Elements,Type * VecEltTy,bool isBigEndian)1633*9880d681SAndroid Build Coastguard Worker static bool collectInsertionElements(Value *V, unsigned Shift,
1634*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<Value *> &Elements,
1635*9880d681SAndroid Build Coastguard Worker Type *VecEltTy, bool isBigEndian) {
1636*9880d681SAndroid Build Coastguard Worker assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
1637*9880d681SAndroid Build Coastguard Worker "Shift should be a multiple of the element type size");
1638*9880d681SAndroid Build Coastguard Worker
1639*9880d681SAndroid Build Coastguard Worker // Undef values never contribute useful bits to the result.
1640*9880d681SAndroid Build Coastguard Worker if (isa<UndefValue>(V)) return true;
1641*9880d681SAndroid Build Coastguard Worker
1642*9880d681SAndroid Build Coastguard Worker // If we got down to a value of the right type, we win, try inserting into the
1643*9880d681SAndroid Build Coastguard Worker // right element.
1644*9880d681SAndroid Build Coastguard Worker if (V->getType() == VecEltTy) {
1645*9880d681SAndroid Build Coastguard Worker // Inserting null doesn't actually insert any elements.
1646*9880d681SAndroid Build Coastguard Worker if (Constant *C = dyn_cast<Constant>(V))
1647*9880d681SAndroid Build Coastguard Worker if (C->isNullValue())
1648*9880d681SAndroid Build Coastguard Worker return true;
1649*9880d681SAndroid Build Coastguard Worker
1650*9880d681SAndroid Build Coastguard Worker unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
1651*9880d681SAndroid Build Coastguard Worker if (isBigEndian)
1652*9880d681SAndroid Build Coastguard Worker ElementIndex = Elements.size() - ElementIndex - 1;
1653*9880d681SAndroid Build Coastguard Worker
1654*9880d681SAndroid Build Coastguard Worker // Fail if multiple elements are inserted into this slot.
1655*9880d681SAndroid Build Coastguard Worker if (Elements[ElementIndex])
1656*9880d681SAndroid Build Coastguard Worker return false;
1657*9880d681SAndroid Build Coastguard Worker
1658*9880d681SAndroid Build Coastguard Worker Elements[ElementIndex] = V;
1659*9880d681SAndroid Build Coastguard Worker return true;
1660*9880d681SAndroid Build Coastguard Worker }
1661*9880d681SAndroid Build Coastguard Worker
1662*9880d681SAndroid Build Coastguard Worker if (Constant *C = dyn_cast<Constant>(V)) {
1663*9880d681SAndroid Build Coastguard Worker // Figure out the # elements this provides, and bitcast it or slice it up
1664*9880d681SAndroid Build Coastguard Worker // as required.
1665*9880d681SAndroid Build Coastguard Worker unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1666*9880d681SAndroid Build Coastguard Worker VecEltTy);
1667*9880d681SAndroid Build Coastguard Worker // If the constant is the size of a vector element, we just need to bitcast
1668*9880d681SAndroid Build Coastguard Worker // it to the right type so it gets properly inserted.
1669*9880d681SAndroid Build Coastguard Worker if (NumElts == 1)
1670*9880d681SAndroid Build Coastguard Worker return collectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
1671*9880d681SAndroid Build Coastguard Worker Shift, Elements, VecEltTy, isBigEndian);
1672*9880d681SAndroid Build Coastguard Worker
1673*9880d681SAndroid Build Coastguard Worker // Okay, this is a constant that covers multiple elements. Slice it up into
1674*9880d681SAndroid Build Coastguard Worker // pieces and insert each element-sized piece into the vector.
1675*9880d681SAndroid Build Coastguard Worker if (!isa<IntegerType>(C->getType()))
1676*9880d681SAndroid Build Coastguard Worker C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1677*9880d681SAndroid Build Coastguard Worker C->getType()->getPrimitiveSizeInBits()));
1678*9880d681SAndroid Build Coastguard Worker unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
1679*9880d681SAndroid Build Coastguard Worker Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
1680*9880d681SAndroid Build Coastguard Worker
1681*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i != NumElts; ++i) {
1682*9880d681SAndroid Build Coastguard Worker unsigned ShiftI = Shift+i*ElementSize;
1683*9880d681SAndroid Build Coastguard Worker Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
1684*9880d681SAndroid Build Coastguard Worker ShiftI));
1685*9880d681SAndroid Build Coastguard Worker Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
1686*9880d681SAndroid Build Coastguard Worker if (!collectInsertionElements(Piece, ShiftI, Elements, VecEltTy,
1687*9880d681SAndroid Build Coastguard Worker isBigEndian))
1688*9880d681SAndroid Build Coastguard Worker return false;
1689*9880d681SAndroid Build Coastguard Worker }
1690*9880d681SAndroid Build Coastguard Worker return true;
1691*9880d681SAndroid Build Coastguard Worker }
1692*9880d681SAndroid Build Coastguard Worker
1693*9880d681SAndroid Build Coastguard Worker if (!V->hasOneUse()) return false;
1694*9880d681SAndroid Build Coastguard Worker
1695*9880d681SAndroid Build Coastguard Worker Instruction *I = dyn_cast<Instruction>(V);
1696*9880d681SAndroid Build Coastguard Worker if (!I) return false;
1697*9880d681SAndroid Build Coastguard Worker switch (I->getOpcode()) {
1698*9880d681SAndroid Build Coastguard Worker default: return false; // Unhandled case.
1699*9880d681SAndroid Build Coastguard Worker case Instruction::BitCast:
1700*9880d681SAndroid Build Coastguard Worker return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1701*9880d681SAndroid Build Coastguard Worker isBigEndian);
1702*9880d681SAndroid Build Coastguard Worker case Instruction::ZExt:
1703*9880d681SAndroid Build Coastguard Worker if (!isMultipleOfTypeSize(
1704*9880d681SAndroid Build Coastguard Worker I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1705*9880d681SAndroid Build Coastguard Worker VecEltTy))
1706*9880d681SAndroid Build Coastguard Worker return false;
1707*9880d681SAndroid Build Coastguard Worker return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1708*9880d681SAndroid Build Coastguard Worker isBigEndian);
1709*9880d681SAndroid Build Coastguard Worker case Instruction::Or:
1710*9880d681SAndroid Build Coastguard Worker return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1711*9880d681SAndroid Build Coastguard Worker isBigEndian) &&
1712*9880d681SAndroid Build Coastguard Worker collectInsertionElements(I->getOperand(1), Shift, Elements, VecEltTy,
1713*9880d681SAndroid Build Coastguard Worker isBigEndian);
1714*9880d681SAndroid Build Coastguard Worker case Instruction::Shl: {
1715*9880d681SAndroid Build Coastguard Worker // Must be shifting by a constant that is a multiple of the element size.
1716*9880d681SAndroid Build Coastguard Worker ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
1717*9880d681SAndroid Build Coastguard Worker if (!CI) return false;
1718*9880d681SAndroid Build Coastguard Worker Shift += CI->getZExtValue();
1719*9880d681SAndroid Build Coastguard Worker if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
1720*9880d681SAndroid Build Coastguard Worker return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1721*9880d681SAndroid Build Coastguard Worker isBigEndian);
1722*9880d681SAndroid Build Coastguard Worker }
1723*9880d681SAndroid Build Coastguard Worker
1724*9880d681SAndroid Build Coastguard Worker }
1725*9880d681SAndroid Build Coastguard Worker }
1726*9880d681SAndroid Build Coastguard Worker
1727*9880d681SAndroid Build Coastguard Worker
1728*9880d681SAndroid Build Coastguard Worker /// If the input is an 'or' instruction, we may be doing shifts and ors to
1729*9880d681SAndroid Build Coastguard Worker /// assemble the elements of the vector manually.
1730*9880d681SAndroid Build Coastguard Worker /// Try to rip the code out and replace it with insertelements. This is to
1731*9880d681SAndroid Build Coastguard Worker /// optimize code like this:
1732*9880d681SAndroid Build Coastguard Worker ///
1733*9880d681SAndroid Build Coastguard Worker /// %tmp37 = bitcast float %inc to i32
1734*9880d681SAndroid Build Coastguard Worker /// %tmp38 = zext i32 %tmp37 to i64
1735*9880d681SAndroid Build Coastguard Worker /// %tmp31 = bitcast float %inc5 to i32
1736*9880d681SAndroid Build Coastguard Worker /// %tmp32 = zext i32 %tmp31 to i64
1737*9880d681SAndroid Build Coastguard Worker /// %tmp33 = shl i64 %tmp32, 32
1738*9880d681SAndroid Build Coastguard Worker /// %ins35 = or i64 %tmp33, %tmp38
1739*9880d681SAndroid Build Coastguard Worker /// %tmp43 = bitcast i64 %ins35 to <2 x float>
1740*9880d681SAndroid Build Coastguard Worker ///
1741*9880d681SAndroid Build Coastguard Worker /// Into two insertelements that do "buildvector{%inc, %inc5}".
optimizeIntegerToVectorInsertions(BitCastInst & CI,InstCombiner & IC)1742*9880d681SAndroid Build Coastguard Worker static Value *optimizeIntegerToVectorInsertions(BitCastInst &CI,
1743*9880d681SAndroid Build Coastguard Worker InstCombiner &IC) {
1744*9880d681SAndroid Build Coastguard Worker VectorType *DestVecTy = cast<VectorType>(CI.getType());
1745*9880d681SAndroid Build Coastguard Worker Value *IntInput = CI.getOperand(0);
1746*9880d681SAndroid Build Coastguard Worker
1747*9880d681SAndroid Build Coastguard Worker SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1748*9880d681SAndroid Build Coastguard Worker if (!collectInsertionElements(IntInput, 0, Elements,
1749*9880d681SAndroid Build Coastguard Worker DestVecTy->getElementType(),
1750*9880d681SAndroid Build Coastguard Worker IC.getDataLayout().isBigEndian()))
1751*9880d681SAndroid Build Coastguard Worker return nullptr;
1752*9880d681SAndroid Build Coastguard Worker
1753*9880d681SAndroid Build Coastguard Worker // If we succeeded, we know that all of the element are specified by Elements
1754*9880d681SAndroid Build Coastguard Worker // or are zero if Elements has a null entry. Recast this as a set of
1755*9880d681SAndroid Build Coastguard Worker // insertions.
1756*9880d681SAndroid Build Coastguard Worker Value *Result = Constant::getNullValue(CI.getType());
1757*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
1758*9880d681SAndroid Build Coastguard Worker if (!Elements[i]) continue; // Unset element.
1759*9880d681SAndroid Build Coastguard Worker
1760*9880d681SAndroid Build Coastguard Worker Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1761*9880d681SAndroid Build Coastguard Worker IC.Builder->getInt32(i));
1762*9880d681SAndroid Build Coastguard Worker }
1763*9880d681SAndroid Build Coastguard Worker
1764*9880d681SAndroid Build Coastguard Worker return Result;
1765*9880d681SAndroid Build Coastguard Worker }
1766*9880d681SAndroid Build Coastguard Worker
1767*9880d681SAndroid Build Coastguard Worker /// Canonicalize scalar bitcasts of extracted elements into a bitcast of the
1768*9880d681SAndroid Build Coastguard Worker /// vector followed by extract element. The backend tends to handle bitcasts of
1769*9880d681SAndroid Build Coastguard Worker /// vectors better than bitcasts of scalars because vector registers are
1770*9880d681SAndroid Build Coastguard Worker /// usually not type-specific like scalar integer or scalar floating-point.
canonicalizeBitCastExtElt(BitCastInst & BitCast,InstCombiner & IC,const DataLayout & DL)1771*9880d681SAndroid Build Coastguard Worker static Instruction *canonicalizeBitCastExtElt(BitCastInst &BitCast,
1772*9880d681SAndroid Build Coastguard Worker InstCombiner &IC,
1773*9880d681SAndroid Build Coastguard Worker const DataLayout &DL) {
1774*9880d681SAndroid Build Coastguard Worker // TODO: Create and use a pattern matcher for ExtractElementInst.
1775*9880d681SAndroid Build Coastguard Worker auto *ExtElt = dyn_cast<ExtractElementInst>(BitCast.getOperand(0));
1776*9880d681SAndroid Build Coastguard Worker if (!ExtElt || !ExtElt->hasOneUse())
1777*9880d681SAndroid Build Coastguard Worker return nullptr;
1778*9880d681SAndroid Build Coastguard Worker
1779*9880d681SAndroid Build Coastguard Worker // The bitcast must be to a vectorizable type, otherwise we can't make a new
1780*9880d681SAndroid Build Coastguard Worker // type to extract from.
1781*9880d681SAndroid Build Coastguard Worker Type *DestType = BitCast.getType();
1782*9880d681SAndroid Build Coastguard Worker if (!VectorType::isValidElementType(DestType))
1783*9880d681SAndroid Build Coastguard Worker return nullptr;
1784*9880d681SAndroid Build Coastguard Worker
1785*9880d681SAndroid Build Coastguard Worker unsigned NumElts = ExtElt->getVectorOperandType()->getNumElements();
1786*9880d681SAndroid Build Coastguard Worker auto *NewVecType = VectorType::get(DestType, NumElts);
1787*9880d681SAndroid Build Coastguard Worker auto *NewBC = IC.Builder->CreateBitCast(ExtElt->getVectorOperand(),
1788*9880d681SAndroid Build Coastguard Worker NewVecType, "bc");
1789*9880d681SAndroid Build Coastguard Worker return ExtractElementInst::Create(NewBC, ExtElt->getIndexOperand());
1790*9880d681SAndroid Build Coastguard Worker }
1791*9880d681SAndroid Build Coastguard Worker
visitBitCast(BitCastInst & CI)1792*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1793*9880d681SAndroid Build Coastguard Worker // If the operands are integer typed then apply the integer transforms,
1794*9880d681SAndroid Build Coastguard Worker // otherwise just apply the common ones.
1795*9880d681SAndroid Build Coastguard Worker Value *Src = CI.getOperand(0);
1796*9880d681SAndroid Build Coastguard Worker Type *SrcTy = Src->getType();
1797*9880d681SAndroid Build Coastguard Worker Type *DestTy = CI.getType();
1798*9880d681SAndroid Build Coastguard Worker
1799*9880d681SAndroid Build Coastguard Worker // Get rid of casts from one type to the same type. These are useless and can
1800*9880d681SAndroid Build Coastguard Worker // be replaced by the operand.
1801*9880d681SAndroid Build Coastguard Worker if (DestTy == Src->getType())
1802*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(CI, Src);
1803*9880d681SAndroid Build Coastguard Worker
1804*9880d681SAndroid Build Coastguard Worker if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1805*9880d681SAndroid Build Coastguard Worker PointerType *SrcPTy = cast<PointerType>(SrcTy);
1806*9880d681SAndroid Build Coastguard Worker Type *DstElTy = DstPTy->getElementType();
1807*9880d681SAndroid Build Coastguard Worker Type *SrcElTy = SrcPTy->getElementType();
1808*9880d681SAndroid Build Coastguard Worker
1809*9880d681SAndroid Build Coastguard Worker // If we are casting a alloca to a pointer to a type of the same
1810*9880d681SAndroid Build Coastguard Worker // size, rewrite the allocation instruction to allocate the "right" type.
1811*9880d681SAndroid Build Coastguard Worker // There is no need to modify malloc calls because it is their bitcast that
1812*9880d681SAndroid Build Coastguard Worker // needs to be cleaned up.
1813*9880d681SAndroid Build Coastguard Worker if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1814*9880d681SAndroid Build Coastguard Worker if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1815*9880d681SAndroid Build Coastguard Worker return V;
1816*9880d681SAndroid Build Coastguard Worker
1817*9880d681SAndroid Build Coastguard Worker // When the type pointed to is not sized the cast cannot be
1818*9880d681SAndroid Build Coastguard Worker // turned into a gep.
1819*9880d681SAndroid Build Coastguard Worker Type *PointeeType =
1820*9880d681SAndroid Build Coastguard Worker cast<PointerType>(Src->getType()->getScalarType())->getElementType();
1821*9880d681SAndroid Build Coastguard Worker if (!PointeeType->isSized())
1822*9880d681SAndroid Build Coastguard Worker return nullptr;
1823*9880d681SAndroid Build Coastguard Worker
1824*9880d681SAndroid Build Coastguard Worker // If the source and destination are pointers, and this cast is equivalent
1825*9880d681SAndroid Build Coastguard Worker // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1826*9880d681SAndroid Build Coastguard Worker // This can enhance SROA and other transforms that want type-safe pointers.
1827*9880d681SAndroid Build Coastguard Worker unsigned NumZeros = 0;
1828*9880d681SAndroid Build Coastguard Worker while (SrcElTy != DstElTy &&
1829*9880d681SAndroid Build Coastguard Worker isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
1830*9880d681SAndroid Build Coastguard Worker SrcElTy->getNumContainedTypes() /* not "{}" */) {
1831*9880d681SAndroid Build Coastguard Worker SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(0U);
1832*9880d681SAndroid Build Coastguard Worker ++NumZeros;
1833*9880d681SAndroid Build Coastguard Worker }
1834*9880d681SAndroid Build Coastguard Worker
1835*9880d681SAndroid Build Coastguard Worker // If we found a path from the src to dest, create the getelementptr now.
1836*9880d681SAndroid Build Coastguard Worker if (SrcElTy == DstElTy) {
1837*9880d681SAndroid Build Coastguard Worker SmallVector<Value *, 8> Idxs(NumZeros + 1, Builder->getInt32(0));
1838*9880d681SAndroid Build Coastguard Worker return GetElementPtrInst::CreateInBounds(Src, Idxs);
1839*9880d681SAndroid Build Coastguard Worker }
1840*9880d681SAndroid Build Coastguard Worker }
1841*9880d681SAndroid Build Coastguard Worker
1842*9880d681SAndroid Build Coastguard Worker if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
1843*9880d681SAndroid Build Coastguard Worker if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
1844*9880d681SAndroid Build Coastguard Worker Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1845*9880d681SAndroid Build Coastguard Worker return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
1846*9880d681SAndroid Build Coastguard Worker Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1847*9880d681SAndroid Build Coastguard Worker // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1848*9880d681SAndroid Build Coastguard Worker }
1849*9880d681SAndroid Build Coastguard Worker
1850*9880d681SAndroid Build Coastguard Worker if (isa<IntegerType>(SrcTy)) {
1851*9880d681SAndroid Build Coastguard Worker // If this is a cast from an integer to vector, check to see if the input
1852*9880d681SAndroid Build Coastguard Worker // is a trunc or zext of a bitcast from vector. If so, we can replace all
1853*9880d681SAndroid Build Coastguard Worker // the casts with a shuffle and (potentially) a bitcast.
1854*9880d681SAndroid Build Coastguard Worker if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
1855*9880d681SAndroid Build Coastguard Worker CastInst *SrcCast = cast<CastInst>(Src);
1856*9880d681SAndroid Build Coastguard Worker if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1857*9880d681SAndroid Build Coastguard Worker if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1858*9880d681SAndroid Build Coastguard Worker if (Instruction *I = optimizeVectorResize(BCIn->getOperand(0),
1859*9880d681SAndroid Build Coastguard Worker cast<VectorType>(DestTy), *this))
1860*9880d681SAndroid Build Coastguard Worker return I;
1861*9880d681SAndroid Build Coastguard Worker }
1862*9880d681SAndroid Build Coastguard Worker
1863*9880d681SAndroid Build Coastguard Worker // If the input is an 'or' instruction, we may be doing shifts and ors to
1864*9880d681SAndroid Build Coastguard Worker // assemble the elements of the vector manually. Try to rip the code out
1865*9880d681SAndroid Build Coastguard Worker // and replace it with insertelements.
1866*9880d681SAndroid Build Coastguard Worker if (Value *V = optimizeIntegerToVectorInsertions(CI, *this))
1867*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(CI, V);
1868*9880d681SAndroid Build Coastguard Worker }
1869*9880d681SAndroid Build Coastguard Worker }
1870*9880d681SAndroid Build Coastguard Worker
1871*9880d681SAndroid Build Coastguard Worker if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
1872*9880d681SAndroid Build Coastguard Worker if (SrcVTy->getNumElements() == 1) {
1873*9880d681SAndroid Build Coastguard Worker // If our destination is not a vector, then make this a straight
1874*9880d681SAndroid Build Coastguard Worker // scalar-scalar cast.
1875*9880d681SAndroid Build Coastguard Worker if (!DestTy->isVectorTy()) {
1876*9880d681SAndroid Build Coastguard Worker Value *Elem =
1877*9880d681SAndroid Build Coastguard Worker Builder->CreateExtractElement(Src,
1878*9880d681SAndroid Build Coastguard Worker Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1879*9880d681SAndroid Build Coastguard Worker return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1880*9880d681SAndroid Build Coastguard Worker }
1881*9880d681SAndroid Build Coastguard Worker
1882*9880d681SAndroid Build Coastguard Worker // Otherwise, see if our source is an insert. If so, then use the scalar
1883*9880d681SAndroid Build Coastguard Worker // component directly.
1884*9880d681SAndroid Build Coastguard Worker if (InsertElementInst *IEI =
1885*9880d681SAndroid Build Coastguard Worker dyn_cast<InsertElementInst>(CI.getOperand(0)))
1886*9880d681SAndroid Build Coastguard Worker return CastInst::Create(Instruction::BitCast, IEI->getOperand(1),
1887*9880d681SAndroid Build Coastguard Worker DestTy);
1888*9880d681SAndroid Build Coastguard Worker }
1889*9880d681SAndroid Build Coastguard Worker }
1890*9880d681SAndroid Build Coastguard Worker
1891*9880d681SAndroid Build Coastguard Worker if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
1892*9880d681SAndroid Build Coastguard Worker // Okay, we have (bitcast (shuffle ..)). Check to see if this is
1893*9880d681SAndroid Build Coastguard Worker // a bitcast to a vector with the same # elts.
1894*9880d681SAndroid Build Coastguard Worker if (SVI->hasOneUse() && DestTy->isVectorTy() &&
1895*9880d681SAndroid Build Coastguard Worker DestTy->getVectorNumElements() == SVI->getType()->getNumElements() &&
1896*9880d681SAndroid Build Coastguard Worker SVI->getType()->getNumElements() ==
1897*9880d681SAndroid Build Coastguard Worker SVI->getOperand(0)->getType()->getVectorNumElements()) {
1898*9880d681SAndroid Build Coastguard Worker BitCastInst *Tmp;
1899*9880d681SAndroid Build Coastguard Worker // If either of the operands is a cast from CI.getType(), then
1900*9880d681SAndroid Build Coastguard Worker // evaluating the shuffle in the casted destination's type will allow
1901*9880d681SAndroid Build Coastguard Worker // us to eliminate at least one cast.
1902*9880d681SAndroid Build Coastguard Worker if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1903*9880d681SAndroid Build Coastguard Worker Tmp->getOperand(0)->getType() == DestTy) ||
1904*9880d681SAndroid Build Coastguard Worker ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1905*9880d681SAndroid Build Coastguard Worker Tmp->getOperand(0)->getType() == DestTy)) {
1906*9880d681SAndroid Build Coastguard Worker Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1907*9880d681SAndroid Build Coastguard Worker Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1908*9880d681SAndroid Build Coastguard Worker // Return a new shuffle vector. Use the same element ID's, as we
1909*9880d681SAndroid Build Coastguard Worker // know the vector types match #elts.
1910*9880d681SAndroid Build Coastguard Worker return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
1911*9880d681SAndroid Build Coastguard Worker }
1912*9880d681SAndroid Build Coastguard Worker }
1913*9880d681SAndroid Build Coastguard Worker }
1914*9880d681SAndroid Build Coastguard Worker
1915*9880d681SAndroid Build Coastguard Worker if (Instruction *I = canonicalizeBitCastExtElt(CI, *this, DL))
1916*9880d681SAndroid Build Coastguard Worker return I;
1917*9880d681SAndroid Build Coastguard Worker
1918*9880d681SAndroid Build Coastguard Worker if (SrcTy->isPointerTy())
1919*9880d681SAndroid Build Coastguard Worker return commonPointerCastTransforms(CI);
1920*9880d681SAndroid Build Coastguard Worker return commonCastTransforms(CI);
1921*9880d681SAndroid Build Coastguard Worker }
1922*9880d681SAndroid Build Coastguard Worker
visitAddrSpaceCast(AddrSpaceCastInst & CI)1923*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
1924*9880d681SAndroid Build Coastguard Worker // If the destination pointer element type is not the same as the source's
1925*9880d681SAndroid Build Coastguard Worker // first do a bitcast to the destination type, and then the addrspacecast.
1926*9880d681SAndroid Build Coastguard Worker // This allows the cast to be exposed to other transforms.
1927*9880d681SAndroid Build Coastguard Worker Value *Src = CI.getOperand(0);
1928*9880d681SAndroid Build Coastguard Worker PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType());
1929*9880d681SAndroid Build Coastguard Worker PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType());
1930*9880d681SAndroid Build Coastguard Worker
1931*9880d681SAndroid Build Coastguard Worker Type *DestElemTy = DestTy->getElementType();
1932*9880d681SAndroid Build Coastguard Worker if (SrcTy->getElementType() != DestElemTy) {
1933*9880d681SAndroid Build Coastguard Worker Type *MidTy = PointerType::get(DestElemTy, SrcTy->getAddressSpace());
1934*9880d681SAndroid Build Coastguard Worker if (VectorType *VT = dyn_cast<VectorType>(CI.getType())) {
1935*9880d681SAndroid Build Coastguard Worker // Handle vectors of pointers.
1936*9880d681SAndroid Build Coastguard Worker MidTy = VectorType::get(MidTy, VT->getNumElements());
1937*9880d681SAndroid Build Coastguard Worker }
1938*9880d681SAndroid Build Coastguard Worker
1939*9880d681SAndroid Build Coastguard Worker Value *NewBitCast = Builder->CreateBitCast(Src, MidTy);
1940*9880d681SAndroid Build Coastguard Worker return new AddrSpaceCastInst(NewBitCast, CI.getType());
1941*9880d681SAndroid Build Coastguard Worker }
1942*9880d681SAndroid Build Coastguard Worker
1943*9880d681SAndroid Build Coastguard Worker return commonPointerCastTransforms(CI);
1944*9880d681SAndroid Build Coastguard Worker }
1945