blob: 1fe50d4e636cf5fac6c7d665736a9ce529198734 [file] [log] [blame]
Chris Lattner2b295a02010-01-04 07:53:58 +00001//===- InstCombineCasts.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for cast operations.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth5f1f26e2014-04-21 19:51:41 +000014#define DEBUG_TYPE "instcombine"
Chris Lattner2b295a02010-01-04 07:53:58 +000015#include "InstCombine.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000016#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/DataLayout.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner2b295a02010-01-04 07:53:58 +000020using namespace llvm;
21using namespace PatternMatch;
22
Chris Lattner59d95742010-01-04 07:59:07 +000023/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
24/// expression. If so, decompose it, returning some value X, such that Val is
25/// X*Scale+Offset.
26///
27static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Dan Gohman05a65552010-05-28 04:33:04 +000028 uint64_t &Offset) {
Chris Lattner59d95742010-01-04 07:59:07 +000029 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
30 Offset = CI->getZExtValue();
31 Scale = 0;
Dan Gohman05a65552010-05-28 04:33:04 +000032 return ConstantInt::get(Val->getType(), 0);
Chris Lattneraaccc8d2010-01-05 20:57:30 +000033 }
Craig Topper3529aa52013-01-24 05:22:40 +000034
Chris Lattneraaccc8d2010-01-05 20:57:30 +000035 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
Bob Wilson3c68b622011-07-08 22:09:33 +000036 // Cannot look past anything that might overflow.
37 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
Stepan Dyatkovskiycb2a1a32012-05-05 07:09:40 +000038 if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) {
Bob Wilson3c68b622011-07-08 22:09:33 +000039 Scale = 1;
40 Offset = 0;
41 return Val;
42 }
43
Chris Lattner59d95742010-01-04 07:59:07 +000044 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
45 if (I->getOpcode() == Instruction::Shl) {
46 // This is a value scaled by '1 << the shift amt'.
Dan Gohman05a65552010-05-28 04:33:04 +000047 Scale = UINT64_C(1) << RHS->getZExtValue();
Chris Lattner59d95742010-01-04 07:59:07 +000048 Offset = 0;
49 return I->getOperand(0);
Chris Lattneraaccc8d2010-01-05 20:57:30 +000050 }
Craig Topper3529aa52013-01-24 05:22:40 +000051
Chris Lattneraaccc8d2010-01-05 20:57:30 +000052 if (I->getOpcode() == Instruction::Mul) {
Chris Lattner59d95742010-01-04 07:59:07 +000053 // This value is scaled by 'RHS'.
54 Scale = RHS->getZExtValue();
55 Offset = 0;
56 return I->getOperand(0);
Chris Lattneraaccc8d2010-01-05 20:57:30 +000057 }
Craig Topper3529aa52013-01-24 05:22:40 +000058
Chris Lattneraaccc8d2010-01-05 20:57:30 +000059 if (I->getOpcode() == Instruction::Add) {
Craig Topper3529aa52013-01-24 05:22:40 +000060 // We have X+C. Check to see if we really have (X*C2)+C1,
Chris Lattner59d95742010-01-04 07:59:07 +000061 // where C1 is divisible by C2.
62 unsigned SubScale;
Craig Topper3529aa52013-01-24 05:22:40 +000063 Value *SubVal =
Chris Lattner59d95742010-01-04 07:59:07 +000064 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
65 Offset += RHS->getZExtValue();
66 Scale = SubScale;
67 return SubVal;
68 }
69 }
70 }
71
72 // Otherwise, we can't look past this.
73 Scale = 1;
74 Offset = 0;
75 return Val;
76}
77
78/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
79/// try to eliminate the cast by moving the type information into the alloc.
80Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
81 AllocaInst &AI) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +000082 // This requires DataLayout to get the alloca alignment and size information.
Rafael Espindola37dc9e12014-02-21 00:06:31 +000083 if (!DL) return 0;
Chris Lattner59d95742010-01-04 07:59:07 +000084
Chris Lattner229907c2011-07-18 04:54:35 +000085 PointerType *PTy = cast<PointerType>(CI.getType());
Craig Topper3529aa52013-01-24 05:22:40 +000086
Chris Lattner59d95742010-01-04 07:59:07 +000087 BuilderTy AllocaBuilder(*Builder);
88 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
89
90 // Get the type really allocated and the type casted to.
Chris Lattner229907c2011-07-18 04:54:35 +000091 Type *AllocElTy = AI.getAllocatedType();
92 Type *CastElTy = PTy->getElementType();
Chris Lattner59d95742010-01-04 07:59:07 +000093 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
94
Rafael Espindola37dc9e12014-02-21 00:06:31 +000095 unsigned AllocElTyAlign = DL->getABITypeAlignment(AllocElTy);
96 unsigned CastElTyAlign = DL->getABITypeAlignment(CastElTy);
Chris Lattner59d95742010-01-04 07:59:07 +000097 if (CastElTyAlign < AllocElTyAlign) return 0;
98
99 // If the allocation has multiple uses, only promote it if we are strictly
100 // increasing the alignment of the resultant allocation. If we keep it the
Devang Patelfbb482b2011-03-08 22:12:11 +0000101 // same, we open the door to infinite loops of various kinds.
102 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner59d95742010-01-04 07:59:07 +0000103
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000104 uint64_t AllocElTySize = DL->getTypeAllocSize(AllocElTy);
105 uint64_t CastElTySize = DL->getTypeAllocSize(CastElTy);
Chris Lattner59d95742010-01-04 07:59:07 +0000106 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
107
Jim Grosbach95d2eb92013-03-06 05:44:53 +0000108 // If the allocation has multiple uses, only promote it if we're not
109 // shrinking the amount of memory being allocated.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000110 uint64_t AllocElTyStoreSize = DL->getTypeStoreSize(AllocElTy);
111 uint64_t CastElTyStoreSize = DL->getTypeStoreSize(CastElTy);
Jim Grosbach95d2eb92013-03-06 05:44:53 +0000112 if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return 0;
113
Chris Lattner59d95742010-01-04 07:59:07 +0000114 // See if we can satisfy the modulus by pulling a scale out of the array
115 // size argument.
116 unsigned ArraySizeScale;
Dan Gohman05a65552010-05-28 04:33:04 +0000117 uint64_t ArrayOffset;
Chris Lattner59d95742010-01-04 07:59:07 +0000118 Value *NumElements = // See if the array size is a decomposable linear expr.
119 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
Craig Topper3529aa52013-01-24 05:22:40 +0000120
Chris Lattner59d95742010-01-04 07:59:07 +0000121 // If we can now satisfy the modulus, by using a non-1 scale, we really can
122 // do the xform.
123 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
124 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
125
126 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
127 Value *Amt = 0;
128 if (Scale == 1) {
129 Amt = NumElements;
130 } else {
Dan Gohman05a65552010-05-28 04:33:04 +0000131 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
Chris Lattner59d95742010-01-04 07:59:07 +0000132 // Insert before the alloca, not before the cast.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000133 Amt = AllocaBuilder.CreateMul(Amt, NumElements);
Chris Lattner59d95742010-01-04 07:59:07 +0000134 }
Craig Topper3529aa52013-01-24 05:22:40 +0000135
Dan Gohman05a65552010-05-28 04:33:04 +0000136 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
137 Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
Chris Lattner59d95742010-01-04 07:59:07 +0000138 Offset, true);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000139 Amt = AllocaBuilder.CreateAdd(Amt, Off);
Chris Lattner59d95742010-01-04 07:59:07 +0000140 }
Craig Topper3529aa52013-01-24 05:22:40 +0000141
Chris Lattner59d95742010-01-04 07:59:07 +0000142 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
143 New->setAlignment(AI.getAlignment());
144 New->takeName(&AI);
Craig Topper3529aa52013-01-24 05:22:40 +0000145
Chris Lattner59d95742010-01-04 07:59:07 +0000146 // If the allocation has multiple real uses, insert a cast and change all
147 // things that used it to use the new cast. This will also hack on CI, but it
148 // will die soon.
Devang Patelfbb482b2011-03-08 22:12:11 +0000149 if (!AI.hasOneUse()) {
Chris Lattner59d95742010-01-04 07:59:07 +0000150 // New is the allocation instruction, pointer typed. AI is the original
151 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
152 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Eli Friedmanb9ed18f2011-05-18 00:32:01 +0000153 ReplaceInstUsesWith(AI, NewCast);
Chris Lattner59d95742010-01-04 07:59:07 +0000154 }
155 return ReplaceInstUsesWith(CI, New);
156}
157
Craig Topper3529aa52013-01-24 05:22:40 +0000158/// EvaluateInDifferentType - Given an expression that
Chris Lattner10840e92010-01-08 19:19:23 +0000159/// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
Chris Lattner98748c02010-01-06 01:56:21 +0000160/// insert the code to evaluate the expression.
Craig Topper3529aa52013-01-24 05:22:40 +0000161Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
Chris Lattner92be2ad2010-01-04 07:54:59 +0000162 bool isSigned) {
Chris Lattner9242ae02010-01-08 19:28:47 +0000163 if (Constant *C = dyn_cast<Constant>(V)) {
164 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000165 // If we got a constantexpr back, try to simplify it with DL info.
Chris Lattner9242ae02010-01-08 19:28:47 +0000166 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000167 C = ConstantFoldConstantExpression(CE, DL, TLI);
Chris Lattner9242ae02010-01-08 19:28:47 +0000168 return C;
169 }
Chris Lattner92be2ad2010-01-04 07:54:59 +0000170
171 // Otherwise, it must be an instruction.
172 Instruction *I = cast<Instruction>(V);
173 Instruction *Res = 0;
174 unsigned Opc = I->getOpcode();
175 switch (Opc) {
176 case Instruction::Add:
177 case Instruction::Sub:
178 case Instruction::Mul:
179 case Instruction::And:
180 case Instruction::Or:
181 case Instruction::Xor:
182 case Instruction::AShr:
183 case Instruction::LShr:
184 case Instruction::Shl:
185 case Instruction::UDiv:
186 case Instruction::URem: {
187 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
188 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
189 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
190 break;
Craig Topper3529aa52013-01-24 05:22:40 +0000191 }
Chris Lattner92be2ad2010-01-04 07:54:59 +0000192 case Instruction::Trunc:
193 case Instruction::ZExt:
194 case Instruction::SExt:
195 // If the source type of the cast is the type we're trying for then we can
196 // just return the source. There's no need to insert it because it is not
197 // new.
198 if (I->getOperand(0)->getType() == Ty)
199 return I->getOperand(0);
Craig Topper3529aa52013-01-24 05:22:40 +0000200
Chris Lattner92be2ad2010-01-04 07:54:59 +0000201 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner39d2daa2010-01-10 20:25:54 +0000202 // This also handles the case of zext(trunc(x)) -> zext(x).
203 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
204 Opc == Instruction::SExt);
Chris Lattner92be2ad2010-01-04 07:54:59 +0000205 break;
206 case Instruction::Select: {
207 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
208 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
209 Res = SelectInst::Create(I->getOperand(0), True, False);
210 break;
211 }
212 case Instruction::PHI: {
213 PHINode *OPN = cast<PHINode>(I);
Jay Foad52131342011-03-30 11:28:46 +0000214 PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
Chris Lattner92be2ad2010-01-04 07:54:59 +0000215 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
216 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
217 NPN->addIncoming(V, OPN->getIncomingBlock(i));
218 }
219 Res = NPN;
220 break;
221 }
Craig Topper3529aa52013-01-24 05:22:40 +0000222 default:
Chris Lattner92be2ad2010-01-04 07:54:59 +0000223 // TODO: Can handle more cases here.
224 llvm_unreachable("Unreachable!");
Chris Lattner92be2ad2010-01-04 07:54:59 +0000225 }
Craig Topper3529aa52013-01-24 05:22:40 +0000226
Chris Lattner92be2ad2010-01-04 07:54:59 +0000227 Res->takeName(I);
Eli Friedman35211c62011-05-27 00:19:40 +0000228 return InsertNewInstWith(Res, *I);
Chris Lattner92be2ad2010-01-04 07:54:59 +0000229}
Chris Lattner2b295a02010-01-04 07:53:58 +0000230
231
232/// This function is a wrapper around CastInst::isEliminableCastPair. It
233/// simply extracts arguments and returns what that function returns.
Craig Topper3529aa52013-01-24 05:22:40 +0000234static Instruction::CastOps
Chris Lattner2b295a02010-01-04 07:53:58 +0000235isEliminableCastPair(
236 const CastInst *CI, ///< The first cast instruction
237 unsigned opcode, ///< The opcode of the second cast instruction
Chris Lattner229907c2011-07-18 04:54:35 +0000238 Type *DstTy, ///< The target type for the second cast instruction
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000239 const DataLayout *DL ///< The target data for pointer size
Chris Lattner2b295a02010-01-04 07:53:58 +0000240) {
241
Chris Lattner229907c2011-07-18 04:54:35 +0000242 Type *SrcTy = CI->getOperand(0)->getType(); // A from above
243 Type *MidTy = CI->getType(); // B from above
Chris Lattner2b295a02010-01-04 07:53:58 +0000244
245 // Get the opcodes of the two Cast instructions
246 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
247 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000248 Type *SrcIntPtrTy = DL && SrcTy->isPtrOrPtrVectorTy() ?
249 DL->getIntPtrType(SrcTy) : 0;
250 Type *MidIntPtrTy = DL && MidTy->isPtrOrPtrVectorTy() ?
251 DL->getIntPtrType(MidTy) : 0;
252 Type *DstIntPtrTy = DL && DstTy->isPtrOrPtrVectorTy() ?
253 DL->getIntPtrType(DstTy) : 0;
Chris Lattner2b295a02010-01-04 07:53:58 +0000254 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Duncan Sandse2395dc2012-10-30 16:03:32 +0000255 DstTy, SrcIntPtrTy, MidIntPtrTy,
256 DstIntPtrTy);
Micah Villmow12d91272012-10-24 15:52:52 +0000257
Chris Lattner2b295a02010-01-04 07:53:58 +0000258 // We don't want to form an inttoptr or ptrtoint that converts to an integer
259 // type that differs from the pointer size.
Duncan Sandse2395dc2012-10-30 16:03:32 +0000260 if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
261 (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
Chris Lattner2b295a02010-01-04 07:53:58 +0000262 Res = 0;
Craig Topper3529aa52013-01-24 05:22:40 +0000263
Chris Lattner2b295a02010-01-04 07:53:58 +0000264 return Instruction::CastOps(Res);
265}
266
Chris Lattner4e8137d2010-02-11 06:26:33 +0000267/// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
268/// results in any code being generated and is interesting to optimize out. If
269/// the cast can be eliminated by some other simple transformation, we prefer
270/// to do the simplification first.
271bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
Chris Lattner229907c2011-07-18 04:54:35 +0000272 Type *Ty) {
Chris Lattner4e8137d2010-02-11 06:26:33 +0000273 // Noop casts and casts of constants should be eliminated trivially.
Chris Lattner2b295a02010-01-04 07:53:58 +0000274 if (V->getType() == Ty || isa<Constant>(V)) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000275
Chris Lattner4e8137d2010-02-11 06:26:33 +0000276 // If this is another cast that can be eliminated, we prefer to have it
277 // eliminated.
Chris Lattner2b295a02010-01-04 07:53:58 +0000278 if (const CastInst *CI = dyn_cast<CastInst>(V))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000279 if (isEliminableCastPair(CI, opc, Ty, DL))
Chris Lattner2b295a02010-01-04 07:53:58 +0000280 return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000281
Chris Lattner4e8137d2010-02-11 06:26:33 +0000282 // If this is a vector sext from a compare, then we don't want to break the
283 // idiom where each element of the extended vector is either zero or all ones.
Duncan Sands19d0b472010-02-16 11:11:14 +0000284 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
Chris Lattner4e8137d2010-02-11 06:26:33 +0000285 return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000286
Chris Lattner2b295a02010-01-04 07:53:58 +0000287 return true;
288}
289
290
291/// @brief Implement the transforms common to all CastInst visitors.
292Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
293 Value *Src = CI.getOperand(0);
294
295 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
296 // eliminate it now.
297 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Craig Topper3529aa52013-01-24 05:22:40 +0000298 if (Instruction::CastOps opc =
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000299 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), DL)) {
Chris Lattner2b295a02010-01-04 07:53:58 +0000300 // The first cast (CSrc) is eliminable so we need to fix up or replace
301 // the second cast (CI). CSrc will then have a good chance of being dead.
302 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
303 }
304 }
305
306 // If we are casting a select then fold the cast into the select
307 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
308 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
309 return NV;
310
311 // If we are casting a PHI then fold the cast into the PHI
312 if (isa<PHINode>(Src)) {
313 // We don't do this if this would create a PHI node with an illegal type if
314 // it is currently legal.
Duncan Sands19d0b472010-02-16 11:11:14 +0000315 if (!Src->getType()->isIntegerTy() ||
316 !CI.getType()->isIntegerTy() ||
Chris Lattner2b295a02010-01-04 07:53:58 +0000317 ShouldChangeType(CI.getType(), Src->getType()))
318 if (Instruction *NV = FoldOpIntoPhi(CI))
319 return NV;
320 }
Craig Topper3529aa52013-01-24 05:22:40 +0000321
Chris Lattner2b295a02010-01-04 07:53:58 +0000322 return 0;
323}
324
Chris Lattnerc3aca382010-01-10 00:58:42 +0000325/// CanEvaluateTruncated - Return true if we can evaluate the specified
326/// expression tree as type Ty instead of its larger type, and arrive with the
327/// same value. This is used by code that tries to eliminate truncates.
328///
329/// Ty will always be a type smaller than V. We should return true if trunc(V)
330/// can be computed by computing V in the smaller type. If V is an instruction,
331/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
332/// makes sense if x and y can be efficiently truncated.
333///
Chris Lattner172630a2010-01-11 02:43:35 +0000334/// This function works on both vectors and scalars.
335///
Chris Lattner229907c2011-07-18 04:54:35 +0000336static bool CanEvaluateTruncated(Value *V, Type *Ty) {
Chris Lattnerc3aca382010-01-10 00:58:42 +0000337 // We can always evaluate constants in another type.
338 if (isa<Constant>(V))
339 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000340
Chris Lattnerc3aca382010-01-10 00:58:42 +0000341 Instruction *I = dyn_cast<Instruction>(V);
342 if (!I) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000343
Chris Lattner229907c2011-07-18 04:54:35 +0000344 Type *OrigTy = V->getType();
Craig Topper3529aa52013-01-24 05:22:40 +0000345
Chris Lattnera6b13562010-01-11 22:45:25 +0000346 // If this is an extension from the dest type, we can eliminate it, even if it
347 // has multiple uses.
Craig Topper3529aa52013-01-24 05:22:40 +0000348 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
Chris Lattnerc3aca382010-01-10 00:58:42 +0000349 I->getOperand(0)->getType() == Ty)
350 return true;
351
352 // We can't extend or shrink something that has multiple uses: doing so would
353 // require duplicating the instruction in general, which isn't profitable.
354 if (!I->hasOneUse()) return false;
355
356 unsigned Opc = I->getOpcode();
357 switch (Opc) {
358 case Instruction::Add:
359 case Instruction::Sub:
360 case Instruction::Mul:
361 case Instruction::And:
362 case Instruction::Or:
363 case Instruction::Xor:
364 // These operators can all arbitrarily be extended or truncated.
365 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
366 CanEvaluateTruncated(I->getOperand(1), Ty);
367
368 case Instruction::UDiv:
369 case Instruction::URem: {
370 // UDiv and URem can be truncated if all the truncated bits are zero.
371 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
372 uint32_t BitWidth = Ty->getScalarSizeInBits();
373 if (BitWidth < OrigBitWidth) {
374 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
375 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
376 MaskedValueIsZero(I->getOperand(1), Mask)) {
377 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
378 CanEvaluateTruncated(I->getOperand(1), Ty);
379 }
380 }
381 break;
382 }
383 case Instruction::Shl:
384 // If we are truncating the result of this SHL, and if it's a shift of a
385 // constant amount, we can always perform a SHL in a smaller type.
386 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
387 uint32_t BitWidth = Ty->getScalarSizeInBits();
388 if (CI->getLimitedValue(BitWidth) < BitWidth)
389 return CanEvaluateTruncated(I->getOperand(0), Ty);
390 }
391 break;
392 case Instruction::LShr:
393 // If this is a truncate of a logical shr, we can truncate it to a smaller
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000394 // lshr iff we know that the bits we would otherwise be shifting in are
Chris Lattnerc3aca382010-01-10 00:58:42 +0000395 // already zeros.
396 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
397 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
398 uint32_t BitWidth = Ty->getScalarSizeInBits();
399 if (MaskedValueIsZero(I->getOperand(0),
400 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
401 CI->getLimitedValue(BitWidth) < BitWidth) {
402 return CanEvaluateTruncated(I->getOperand(0), Ty);
403 }
404 }
405 break;
406 case Instruction::Trunc:
407 // trunc(trunc(x)) -> trunc(x)
408 return true;
Chris Lattner73984342010-08-27 20:32:06 +0000409 case Instruction::ZExt:
410 case Instruction::SExt:
411 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
412 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
413 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000414 case Instruction::Select: {
415 SelectInst *SI = cast<SelectInst>(I);
416 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
417 CanEvaluateTruncated(SI->getFalseValue(), Ty);
418 }
419 case Instruction::PHI: {
420 // We can change a phi if we can change all operands. Note that we never
421 // get into trouble with cyclic PHIs here because we only consider
422 // instructions with a single use.
423 PHINode *PN = cast<PHINode>(I);
424 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
425 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
426 return false;
427 return true;
428 }
429 default:
430 // TODO: Can handle more cases here.
431 break;
432 }
Craig Topper3529aa52013-01-24 05:22:40 +0000433
Chris Lattnerc3aca382010-01-10 00:58:42 +0000434 return false;
435}
436
437Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner883550a2010-01-10 01:00:46 +0000438 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattnerc3aca382010-01-10 00:58:42 +0000439 return Result;
Craig Topper3529aa52013-01-24 05:22:40 +0000440
441 // See if we can simplify any instructions used by the input whose sole
Chris Lattner883550a2010-01-10 01:00:46 +0000442 // purpose is to compute bits we don't care about.
443 if (SimplifyDemandedInstructionBits(CI))
444 return &CI;
Craig Topper3529aa52013-01-24 05:22:40 +0000445
Chris Lattnerc3aca382010-01-10 00:58:42 +0000446 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000447 Type *DestTy = CI.getType(), *SrcTy = Src->getType();
Craig Topper3529aa52013-01-24 05:22:40 +0000448
Chris Lattnerc3aca382010-01-10 00:58:42 +0000449 // Attempt to truncate the entire input expression tree to the destination
450 // type. Only do this if the dest type is a simple type, don't convert the
Chris Lattner2b295a02010-01-04 07:53:58 +0000451 // expression tree to something weird like i93 unless the source is also
452 // strange.
Duncan Sands19d0b472010-02-16 11:11:14 +0000453 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattnerc3aca382010-01-10 00:58:42 +0000454 CanEvaluateTruncated(Src, DestTy)) {
Craig Topper3529aa52013-01-24 05:22:40 +0000455
Chris Lattner2b295a02010-01-04 07:53:58 +0000456 // If this cast is a truncate, evaluting in a different type always
Chris Lattner8600dd32010-01-05 23:00:30 +0000457 // eliminates the cast, so it is always a win.
Chris Lattner3057c372010-01-07 23:41:00 +0000458 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
Dan Gohmana4abd032010-05-25 21:50:35 +0000459 " to avoid cast: " << CI << '\n');
Chris Lattner3057c372010-01-07 23:41:00 +0000460 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
461 assert(Res->getType() == DestTy);
462 return ReplaceInstUsesWith(CI, Res);
463 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000464
Chris Lattnera93c63c2010-01-05 22:21:18 +0000465 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
466 if (DestTy->getScalarSizeInBits() == 1) {
Chris Lattner2b295a02010-01-04 07:53:58 +0000467 Constant *One = ConstantInt::get(Src->getType(), 1);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000468 Src = Builder->CreateAnd(Src, One);
Chris Lattner2b295a02010-01-04 07:53:58 +0000469 Value *Zero = Constant::getNullValue(Src->getType());
470 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
471 }
Craig Topper3529aa52013-01-24 05:22:40 +0000472
Chris Lattner90cd7462010-08-27 18:31:05 +0000473 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
474 Value *A = 0; ConstantInt *Cst = 0;
Chris Lattner9c10d582011-01-15 06:32:33 +0000475 if (Src->hasOneUse() &&
476 match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
Chris Lattner90cd7462010-08-27 18:31:05 +0000477 // We have three types to worry about here, the type of A, the source of
478 // the truncate (MidSize), and the destination of the truncate. We know that
479 // ASize < MidSize and MidSize > ResultSize, but don't know the relation
480 // between ASize and ResultSize.
481 unsigned ASize = A->getType()->getPrimitiveSizeInBits();
Craig Topper3529aa52013-01-24 05:22:40 +0000482
Chris Lattner90cd7462010-08-27 18:31:05 +0000483 // If the shift amount is larger than the size of A, then the result is
484 // known to be zero because all the input bits got shifted out.
485 if (Cst->getZExtValue() >= ASize)
486 return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
487
488 // Since we're doing an lshr and a zero extend, and know that the shift
489 // amount is smaller than ASize, it is always safe to do the shift in A's
490 // type, then zero extend or truncate to the result.
491 Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
492 Shift->takeName(Src);
493 return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
494 }
Craig Topper3529aa52013-01-24 05:22:40 +0000495
Chris Lattner9c10d582011-01-15 06:32:33 +0000496 // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
497 // type isn't non-native.
498 if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
499 ShouldChangeType(Src->getType(), CI.getType()) &&
500 match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
501 Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
502 return BinaryOperator::CreateAnd(NewTrunc,
503 ConstantExpr::getTrunc(Cst, CI.getType()));
504 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000505
Chris Lattner2b295a02010-01-04 07:53:58 +0000506 return 0;
507}
508
509/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
510/// in order to eliminate the icmp.
511Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
512 bool DoXform) {
513 // If we are just checking for a icmp eq of a single bit and zext'ing it
514 // to an integer, then shift the bit to the appropriate place and then
515 // cast to integer to avoid the comparison.
516 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
517 const APInt &Op1CV = Op1C->getValue();
Craig Topper3529aa52013-01-24 05:22:40 +0000518
Chris Lattner2b295a02010-01-04 07:53:58 +0000519 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
520 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
521 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
522 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
523 if (!DoXform) return ICI;
524
525 Value *In = ICI->getOperand(0);
526 Value *Sh = ConstantInt::get(In->getType(),
527 In->getType()->getScalarSizeInBits()-1);
528 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
529 if (In->getType() != CI.getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000530 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner2b295a02010-01-04 07:53:58 +0000531
532 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
533 Constant *One = ConstantInt::get(In->getType(), 1);
534 In = Builder->CreateXor(In, One, In->getName()+".not");
535 }
536
537 return ReplaceInstUsesWith(CI, In);
538 }
Chad Rosier385d9f62011-11-30 01:59:59 +0000539
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000540 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
541 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
542 // zext (X == 1) to i32 --> X iff X has only the low bit set.
543 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
544 // zext (X != 0) to i32 --> X iff X has only the low bit set.
545 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
546 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
547 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Craig Topper3529aa52013-01-24 05:22:40 +0000548 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
Chris Lattner2b295a02010-01-04 07:53:58 +0000549 // This only works for EQ and NE
550 ICI->isEquality()) {
551 // If Op1C some other power of two, convert:
552 uint32_t BitWidth = Op1C->getType()->getBitWidth();
553 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000554 ComputeMaskedBits(ICI->getOperand(0), KnownZero, KnownOne);
Craig Topper3529aa52013-01-24 05:22:40 +0000555
Chris Lattner2b295a02010-01-04 07:53:58 +0000556 APInt KnownZeroMask(~KnownZero);
557 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
558 if (!DoXform) return ICI;
559
560 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
561 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
562 // (X&4) == 2 --> false
563 // (X&4) != 2 --> true
564 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
565 isNE);
566 Res = ConstantExpr::getZExt(Res, CI.getType());
567 return ReplaceInstUsesWith(CI, Res);
568 }
Craig Topper3529aa52013-01-24 05:22:40 +0000569
Chris Lattner2b295a02010-01-04 07:53:58 +0000570 uint32_t ShiftAmt = KnownZeroMask.logBase2();
571 Value *In = ICI->getOperand(0);
572 if (ShiftAmt) {
573 // Perform a logical shr by shiftamt.
574 // Insert the shift to put the result in the low bit.
575 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
576 In->getName()+".lobit");
577 }
Craig Topper3529aa52013-01-24 05:22:40 +0000578
Chris Lattner2b295a02010-01-04 07:53:58 +0000579 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
580 Constant *One = ConstantInt::get(In->getType(), 1);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000581 In = Builder->CreateXor(In, One);
Chris Lattner2b295a02010-01-04 07:53:58 +0000582 }
Craig Topper3529aa52013-01-24 05:22:40 +0000583
Chris Lattner2b295a02010-01-04 07:53:58 +0000584 if (CI.getType() == In->getType())
585 return ReplaceInstUsesWith(CI, In);
Chris Lattner18d7fc82010-08-27 22:24:38 +0000586 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner2b295a02010-01-04 07:53:58 +0000587 }
588 }
589 }
590
591 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
592 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
593 // may lead to additional simplifications.
594 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000595 if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
Chris Lattner2b295a02010-01-04 07:53:58 +0000596 uint32_t BitWidth = ITy->getBitWidth();
597 Value *LHS = ICI->getOperand(0);
598 Value *RHS = ICI->getOperand(1);
599
600 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
601 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000602 ComputeMaskedBits(LHS, KnownZeroLHS, KnownOneLHS);
603 ComputeMaskedBits(RHS, KnownZeroRHS, KnownOneRHS);
Chris Lattner2b295a02010-01-04 07:53:58 +0000604
605 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
606 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
607 APInt UnknownBit = ~KnownBits;
608 if (UnknownBit.countPopulation() == 1) {
609 if (!DoXform) return ICI;
610
611 Value *Result = Builder->CreateXor(LHS, RHS);
612
613 // Mask off any bits that are set and won't be shifted away.
614 if (KnownOneLHS.uge(UnknownBit))
615 Result = Builder->CreateAnd(Result,
616 ConstantInt::get(ITy, UnknownBit));
617
618 // Shift the bit we're testing down to the lsb.
619 Result = Builder->CreateLShr(
620 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
621
622 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
623 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
624 Result->takeName(ICI);
625 return ReplaceInstUsesWith(CI, Result);
626 }
627 }
628 }
629 }
630
631 return 0;
632}
633
Chris Lattnerc3aca382010-01-10 00:58:42 +0000634/// CanEvaluateZExtd - Determine if the specified value can be computed in the
Chris Lattner172630a2010-01-11 02:43:35 +0000635/// specified wider type and produce the same low bits. If not, return false.
636///
Chris Lattner12bd8992010-01-11 03:32:00 +0000637/// If this function returns true, it can also return a non-zero number of bits
638/// (in BitsToClear) which indicates that the value it computes is correct for
639/// the zero extend, but that the additional BitsToClear bits need to be zero'd
640/// out. For example, to promote something like:
641///
642/// %B = trunc i64 %A to i32
643/// %C = lshr i32 %B, 8
644/// %E = zext i32 %C to i64
645///
646/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
647/// set to 8 to indicate that the promoted value needs to have bits 24-31
648/// cleared in addition to bits 32-63. Since an 'and' will be generated to
649/// clear the top bits anyway, doing this has no extra cost.
650///
Chris Lattner172630a2010-01-11 02:43:35 +0000651/// This function works on both vectors and scalars.
Chris Lattner229907c2011-07-18 04:54:35 +0000652static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear) {
Chris Lattner12bd8992010-01-11 03:32:00 +0000653 BitsToClear = 0;
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000654 if (isa<Constant>(V))
655 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000656
Chris Lattnerc3aca382010-01-10 00:58:42 +0000657 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000658 if (!I) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000659
Chris Lattnerc3aca382010-01-10 00:58:42 +0000660 // If the input is a truncate from the destination type, we can trivially
Jakob Stoklund Olesenc5c4e962012-06-22 16:36:43 +0000661 // eliminate it.
662 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000663 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000664
Chris Lattnerc3aca382010-01-10 00:58:42 +0000665 // We can't extend or shrink something that has multiple uses: doing so would
666 // require duplicating the instruction in general, which isn't profitable.
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000667 if (!I->hasOneUse()) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000668
Chris Lattner12bd8992010-01-11 03:32:00 +0000669 unsigned Opc = I->getOpcode(), Tmp;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000670 switch (Opc) {
Chris Lattner39d2daa2010-01-10 20:25:54 +0000671 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
672 case Instruction::SExt: // zext(sext(x)) -> sext(x).
673 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
674 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000675 case Instruction::And:
Chris Lattnerc3aca382010-01-10 00:58:42 +0000676 case Instruction::Or:
677 case Instruction::Xor:
Chris Lattnerc3aca382010-01-10 00:58:42 +0000678 case Instruction::Add:
679 case Instruction::Sub:
680 case Instruction::Mul:
Chris Lattner12bd8992010-01-11 03:32:00 +0000681 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
682 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
683 return false;
684 // These can all be promoted if neither operand has 'bits to clear'.
685 if (BitsToClear == 0 && Tmp == 0)
686 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000687
Chris Lattner0a854202010-01-11 04:05:13 +0000688 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
689 // other side, BitsToClear is ok.
690 if (Tmp == 0 &&
691 (Opc == Instruction::And || Opc == Instruction::Or ||
692 Opc == Instruction::Xor)) {
693 // We use MaskedValueIsZero here for generality, but the case we care
694 // about the most is constant RHS.
695 unsigned VSize = V->getType()->getScalarSizeInBits();
696 if (MaskedValueIsZero(I->getOperand(1),
697 APInt::getHighBitsSet(VSize, BitsToClear)))
698 return true;
699 }
Craig Topper3529aa52013-01-24 05:22:40 +0000700
Chris Lattner0a854202010-01-11 04:05:13 +0000701 // Otherwise, we don't know how to analyze this BitsToClear case yet.
Chris Lattner12bd8992010-01-11 03:32:00 +0000702 return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000703
Benjamin Kramer14e915f2013-05-10 16:26:37 +0000704 case Instruction::Shl:
705 // We can promote shl(x, cst) if we can promote x. Since shl overwrites the
706 // upper bits we can reduce BitsToClear by the shift amount.
707 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
708 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
709 return false;
710 uint64_t ShiftAmt = Amt->getZExtValue();
711 BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
712 return true;
713 }
714 return false;
Chris Lattner12bd8992010-01-11 03:32:00 +0000715 case Instruction::LShr:
716 // We can promote lshr(x, cst) if we can promote x. This requires the
717 // ultimate 'and' to clear out the high zero bits we're clearing out though.
718 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
719 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
720 return false;
721 BitsToClear += Amt->getZExtValue();
722 if (BitsToClear > V->getType()->getScalarSizeInBits())
723 BitsToClear = V->getType()->getScalarSizeInBits();
724 return true;
725 }
726 // Cannot promote variable LSHR.
727 return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000728 case Instruction::Select:
Chris Lattner12bd8992010-01-11 03:32:00 +0000729 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
730 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
Chris Lattner0a854202010-01-11 04:05:13 +0000731 // TODO: If important, we could handle the case when the BitsToClear are
732 // known zero in the disagreeing side.
Chris Lattner12bd8992010-01-11 03:32:00 +0000733 Tmp != BitsToClear)
734 return false;
735 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000736
Chris Lattnerc3aca382010-01-10 00:58:42 +0000737 case Instruction::PHI: {
738 // We can change a phi if we can change all operands. Note that we never
739 // get into trouble with cyclic PHIs here because we only consider
740 // instructions with a single use.
741 PHINode *PN = cast<PHINode>(I);
Chris Lattner12bd8992010-01-11 03:32:00 +0000742 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
743 return false;
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000744 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner12bd8992010-01-11 03:32:00 +0000745 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
Chris Lattner0a854202010-01-11 04:05:13 +0000746 // TODO: If important, we could handle the case when the BitsToClear
747 // are known zero in the disagreeing input.
Chris Lattner12bd8992010-01-11 03:32:00 +0000748 Tmp != BitsToClear)
749 return false;
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000750 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000751 }
752 default:
753 // TODO: Can handle more cases here.
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000754 return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000755 }
756}
757
Chris Lattner2b295a02010-01-04 07:53:58 +0000758Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Nick Lewycky80ea0032013-01-14 20:56:10 +0000759 // If this zero extend is only used by a truncate, let the truncate be
Chris Lattner49d2c972010-01-10 02:39:31 +0000760 // eliminated before we try to optimize this zext.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000761 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
Chris Lattner49d2c972010-01-10 02:39:31 +0000762 return 0;
Craig Topper3529aa52013-01-24 05:22:40 +0000763
Chris Lattner2b295a02010-01-04 07:53:58 +0000764 // If one of the common conversion will work, do it.
Chris Lattner883550a2010-01-10 01:00:46 +0000765 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner2b295a02010-01-04 07:53:58 +0000766 return Result;
767
Craig Topper3529aa52013-01-24 05:22:40 +0000768 // See if we can simplify any instructions used by the input whose sole
Chris Lattner883550a2010-01-10 01:00:46 +0000769 // purpose is to compute bits we don't care about.
770 if (SimplifyDemandedInstructionBits(CI))
771 return &CI;
Craig Topper3529aa52013-01-24 05:22:40 +0000772
Chris Lattner883550a2010-01-10 01:00:46 +0000773 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000774 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Craig Topper3529aa52013-01-24 05:22:40 +0000775
Chris Lattnerc3aca382010-01-10 00:58:42 +0000776 // Attempt to extend the entire input expression tree to the destination
777 // type. Only do this if the dest type is a simple type, don't convert the
778 // expression tree to something weird like i93 unless the source is also
779 // strange.
Chris Lattner12bd8992010-01-11 03:32:00 +0000780 unsigned BitsToClear;
Duncan Sands19d0b472010-02-16 11:11:14 +0000781 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Craig Topper3529aa52013-01-24 05:22:40 +0000782 CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
Chris Lattner12bd8992010-01-11 03:32:00 +0000783 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
784 "Unreasonable BitsToClear");
Craig Topper3529aa52013-01-24 05:22:40 +0000785
Chris Lattner49d2c972010-01-10 02:39:31 +0000786 // Okay, we can transform this! Insert the new expression now.
787 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
788 " to avoid zero extend: " << CI);
789 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
790 assert(Res->getType() == DestTy);
Craig Topper3529aa52013-01-24 05:22:40 +0000791
Chris Lattner12bd8992010-01-11 03:32:00 +0000792 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
793 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Craig Topper3529aa52013-01-24 05:22:40 +0000794
Chris Lattner49d2c972010-01-10 02:39:31 +0000795 // If the high bits are already filled with zeros, just replace this
796 // cast with the result.
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000797 if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
Chris Lattner12bd8992010-01-11 03:32:00 +0000798 DestBitSize-SrcBitsKept)))
Chris Lattner49d2c972010-01-10 02:39:31 +0000799 return ReplaceInstUsesWith(CI, Res);
Craig Topper3529aa52013-01-24 05:22:40 +0000800
Chris Lattner49d2c972010-01-10 02:39:31 +0000801 // We need to emit an AND to clear the high bits.
Chris Lattner39d2daa2010-01-10 20:25:54 +0000802 Constant *C = ConstantInt::get(Res->getType(),
Chris Lattner12bd8992010-01-11 03:32:00 +0000803 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
Chris Lattner49d2c972010-01-10 02:39:31 +0000804 return BinaryOperator::CreateAnd(Res, C);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000805 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000806
807 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
808 // types and if the sizes are just right we can convert this into a logical
809 // 'and' which will be much cheaper than the pair of casts.
810 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
Chris Lattnerd8509422010-01-10 07:08:30 +0000811 // TODO: Subsume this into EvaluateInDifferentType.
Craig Topper3529aa52013-01-24 05:22:40 +0000812
Chris Lattner2b295a02010-01-04 07:53:58 +0000813 // Get the sizes of the types involved. We know that the intermediate type
814 // will be smaller than A or C, but don't know the relation between A and C.
815 Value *A = CSrc->getOperand(0);
816 unsigned SrcSize = A->getType()->getScalarSizeInBits();
817 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
818 unsigned DstSize = CI.getType()->getScalarSizeInBits();
819 // If we're actually extending zero bits, then if
820 // SrcSize < DstSize: zext(a & mask)
821 // SrcSize == DstSize: a & mask
822 // SrcSize > DstSize: trunc(a) & mask
823 if (SrcSize < DstSize) {
824 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
825 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
826 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
827 return new ZExtInst(And, CI.getType());
828 }
Craig Topper3529aa52013-01-24 05:22:40 +0000829
Chris Lattner2b295a02010-01-04 07:53:58 +0000830 if (SrcSize == DstSize) {
831 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
832 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
833 AndValue));
834 }
835 if (SrcSize > DstSize) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000836 Value *Trunc = Builder->CreateTrunc(A, CI.getType());
Chris Lattner2b295a02010-01-04 07:53:58 +0000837 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Craig Topper3529aa52013-01-24 05:22:40 +0000838 return BinaryOperator::CreateAnd(Trunc,
Chris Lattner2b295a02010-01-04 07:53:58 +0000839 ConstantInt::get(Trunc->getType(),
Chris Lattnerd8509422010-01-10 07:08:30 +0000840 AndValue));
Chris Lattner2b295a02010-01-04 07:53:58 +0000841 }
842 }
843
844 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
845 return transformZExtICmp(ICI, CI);
846
847 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
848 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
849 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
850 // of the (zext icmp) will be transformed.
851 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
852 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
853 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
854 (transformZExtICmp(LHS, CI, false) ||
855 transformZExtICmp(RHS, CI, false))) {
856 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
857 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
858 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
859 }
860 }
861
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000862 // zext(trunc(X) & C) -> (X & zext(C)).
863 Constant *C;
864 Value *X;
865 if (SrcI &&
866 match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) &&
867 X->getType() == CI.getType())
868 return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType()));
Chris Lattner2b295a02010-01-04 07:53:58 +0000869
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000870 // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)).
871 Value *And;
872 if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) &&
873 match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) &&
874 X->getType() == CI.getType()) {
875 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
876 return BinaryOperator::CreateXor(Builder->CreateAnd(X, ZC), ZC);
877 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000878
Chris Lattnerfd7e42b2010-01-05 21:04:47 +0000879 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000880 if (SrcI && SrcI->hasOneUse() &&
881 SrcI->getType()->getScalarType()->isIntegerTy(1) &&
882 match(SrcI, m_Not(m_Value(X))) && (!X->hasOneUse() || !isa<CmpInst>(X))) {
Chris Lattnerfd7e42b2010-01-05 21:04:47 +0000883 Value *New = Builder->CreateZExt(X, CI.getType());
884 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
885 }
Craig Topper3529aa52013-01-24 05:22:40 +0000886
Chris Lattner2b295a02010-01-04 07:53:58 +0000887 return 0;
888}
889
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000890/// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations
891/// in order to eliminate the icmp.
892Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
893 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
894 ICmpInst::Predicate Pred = ICI->getPredicate();
895
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000896 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Benjamin Kramer8b94c292011-04-01 22:29:18 +0000897 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative
898 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000899 if ((Pred == ICmpInst::ICMP_SLT && Op1C->isNullValue()) ||
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000900 (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
901
902 Value *Sh = ConstantInt::get(Op0->getType(),
903 Op0->getType()->getScalarSizeInBits()-1);
904 Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
905 if (In->getType() != CI.getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000906 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000907
908 if (Pred == ICmpInst::ICMP_SGT)
909 In = Builder->CreateNot(In, In->getName()+".not");
910 return ReplaceInstUsesWith(CI, In);
911 }
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000912 }
Benjamin Kramerd1217652011-04-01 20:09:10 +0000913
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000914 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Benjamin Kramerd1217652011-04-01 20:09:10 +0000915 // If we know that only one bit of the LHS of the icmp can be set and we
916 // have an equality comparison with zero or a power of 2, we can transform
917 // the icmp and sext into bitwise/integer operations.
Benjamin Kramer5cad4532011-04-01 22:22:11 +0000918 if (ICI->hasOneUse() &&
919 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
Benjamin Kramerd1217652011-04-01 20:09:10 +0000920 unsigned BitWidth = Op1C->getType()->getBitWidth();
921 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000922 ComputeMaskedBits(Op0, KnownZero, KnownOne);
Benjamin Kramerd1217652011-04-01 20:09:10 +0000923
Benjamin Kramerac2d5652011-04-01 20:15:16 +0000924 APInt KnownZeroMask(~KnownZero);
925 if (KnownZeroMask.isPowerOf2()) {
Benjamin Kramerd1217652011-04-01 20:09:10 +0000926 Value *In = ICI->getOperand(0);
927
Benjamin Kramer50a281a2011-04-02 18:50:58 +0000928 // If the icmp tests for a known zero bit we can constant fold it.
929 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
930 Value *V = Pred == ICmpInst::ICMP_NE ?
931 ConstantInt::getAllOnesValue(CI.getType()) :
932 ConstantInt::getNullValue(CI.getType());
933 return ReplaceInstUsesWith(CI, V);
934 }
Benjamin Kramer5cad4532011-04-01 22:22:11 +0000935
Benjamin Kramerd1217652011-04-01 20:09:10 +0000936 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
937 // sext ((x & 2^n) == 0) -> (x >> n) - 1
938 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
939 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
940 // Perform a right shift to place the desired bit in the LSB.
941 if (ShiftAmt)
942 In = Builder->CreateLShr(In,
943 ConstantInt::get(In->getType(), ShiftAmt));
944
945 // At this point "In" is either 1 or 0. Subtract 1 to turn
946 // {1, 0} -> {0, -1}.
947 In = Builder->CreateAdd(In,
948 ConstantInt::getAllOnesValue(In->getType()),
949 "sext");
950 } else {
951 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramer5cad4532011-04-01 22:22:11 +0000952 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramerd1217652011-04-01 20:09:10 +0000953 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
954 // Perform a left shift to place the desired bit in the MSB.
955 if (ShiftAmt)
956 In = Builder->CreateShl(In,
957 ConstantInt::get(In->getType(), ShiftAmt));
958
959 // Distribute the bit over the whole bit width.
960 In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
961 BitWidth - 1), "sext");
962 }
963
964 if (CI.getType() == In->getType())
965 return ReplaceInstUsesWith(CI, In);
966 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
967 }
968 }
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000969 }
970
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000971 return 0;
972}
973
Chris Lattnerc3aca382010-01-10 00:58:42 +0000974/// CanEvaluateSExtd - Return true if we can take the specified value
975/// and return it as type Ty without inserting any new casts and without
976/// changing the value of the common low bits. This is used by code that tries
977/// to promote integer operations to a wider types will allow us to eliminate
978/// the extension.
979///
Chris Lattner1a05fdd2010-01-10 07:57:20 +0000980/// This function works on both vectors and scalars.
Chris Lattnerc3aca382010-01-10 00:58:42 +0000981///
Chris Lattner229907c2011-07-18 04:54:35 +0000982static bool CanEvaluateSExtd(Value *V, Type *Ty) {
Chris Lattnerc3aca382010-01-10 00:58:42 +0000983 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
984 "Can't sign extend type to a smaller type");
Chris Lattner1a05fdd2010-01-10 07:57:20 +0000985 // If this is a constant, it can be trivially promoted.
986 if (isa<Constant>(V))
987 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000988
Chris Lattnerc3aca382010-01-10 00:58:42 +0000989 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner1a05fdd2010-01-10 07:57:20 +0000990 if (!I) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000991
Jakob Stoklund Olesenc5c4e962012-06-22 16:36:43 +0000992 // If this is a truncate from the dest type, we can trivially eliminate it.
993 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattner1a05fdd2010-01-10 07:57:20 +0000994 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000995
Chris Lattnerc3aca382010-01-10 00:58:42 +0000996 // We can't extend or shrink something that has multiple uses: doing so would
997 // require duplicating the instruction in general, which isn't profitable.
Chris Lattner1a05fdd2010-01-10 07:57:20 +0000998 if (!I->hasOneUse()) return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000999
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001000 switch (I->getOpcode()) {
Chris Lattner7dd540e2010-01-10 20:30:41 +00001001 case Instruction::SExt: // sext(sext(x)) -> sext(x)
1002 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
1003 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1004 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +00001005 case Instruction::And:
1006 case Instruction::Or:
1007 case Instruction::Xor:
Chris Lattnerc3aca382010-01-10 00:58:42 +00001008 case Instruction::Add:
1009 case Instruction::Sub:
Chris Lattnerc3aca382010-01-10 00:58:42 +00001010 case Instruction::Mul:
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001011 // These operators can all arbitrarily be extended if their inputs can.
Chris Lattner172630a2010-01-11 02:43:35 +00001012 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
1013 CanEvaluateSExtd(I->getOperand(1), Ty);
Craig Topper3529aa52013-01-24 05:22:40 +00001014
Chris Lattnerc3aca382010-01-10 00:58:42 +00001015 //case Instruction::Shl: TODO
1016 //case Instruction::LShr: TODO
Craig Topper3529aa52013-01-24 05:22:40 +00001017
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001018 case Instruction::Select:
Chris Lattner172630a2010-01-11 02:43:35 +00001019 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
1020 CanEvaluateSExtd(I->getOperand(2), Ty);
Craig Topper3529aa52013-01-24 05:22:40 +00001021
Chris Lattnerc3aca382010-01-10 00:58:42 +00001022 case Instruction::PHI: {
1023 // We can change a phi if we can change all operands. Note that we never
1024 // get into trouble with cyclic PHIs here because we only consider
1025 // instructions with a single use.
1026 PHINode *PN = cast<PHINode>(I);
Chris Lattner39d2daa2010-01-10 20:25:54 +00001027 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner172630a2010-01-11 02:43:35 +00001028 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001029 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +00001030 }
1031 default:
1032 // TODO: Can handle more cases here.
1033 break;
1034 }
Craig Topper3529aa52013-01-24 05:22:40 +00001035
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001036 return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +00001037}
1038
Chris Lattner2b295a02010-01-04 07:53:58 +00001039Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Arnaud A. de Grandmaison2e4df4f2013-02-13 00:19:19 +00001040 // If this sign extend is only used by a truncate, let the truncate be
1041 // eliminated before we try to optimize this sext.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001042 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
Chris Lattner49d2c972010-01-10 02:39:31 +00001043 return 0;
Craig Topper3529aa52013-01-24 05:22:40 +00001044
Chris Lattner883550a2010-01-10 01:00:46 +00001045 if (Instruction *I = commonCastTransforms(CI))
Chris Lattner2b295a02010-01-04 07:53:58 +00001046 return I;
Craig Topper3529aa52013-01-24 05:22:40 +00001047
1048 // See if we can simplify any instructions used by the input whose sole
Chris Lattner883550a2010-01-10 01:00:46 +00001049 // purpose is to compute bits we don't care about.
1050 if (SimplifyDemandedInstructionBits(CI))
1051 return &CI;
Craig Topper3529aa52013-01-24 05:22:40 +00001052
Chris Lattner2b295a02010-01-04 07:53:58 +00001053 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001054 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Chris Lattnerc3aca382010-01-10 00:58:42 +00001055
Chris Lattnerc3aca382010-01-10 00:58:42 +00001056 // Attempt to extend the entire input expression tree to the destination
1057 // type. Only do this if the dest type is a simple type, don't convert the
1058 // expression tree to something weird like i93 unless the source is also
1059 // strange.
Duncan Sands19d0b472010-02-16 11:11:14 +00001060 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner172630a2010-01-11 02:43:35 +00001061 CanEvaluateSExtd(Src, DestTy)) {
Chris Lattner2fff10c2010-01-10 07:40:50 +00001062 // Okay, we can transform this! Insert the new expression now.
1063 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1064 " to avoid sign extend: " << CI);
1065 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1066 assert(Res->getType() == DestTy);
1067
Chris Lattnerc3aca382010-01-10 00:58:42 +00001068 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1069 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Chris Lattner2fff10c2010-01-10 07:40:50 +00001070
1071 // If the high bits are already filled with sign bit, just replace this
1072 // cast with the result.
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001073 if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
Chris Lattner2fff10c2010-01-10 07:40:50 +00001074 return ReplaceInstUsesWith(CI, Res);
Craig Topper3529aa52013-01-24 05:22:40 +00001075
Chris Lattner2fff10c2010-01-10 07:40:50 +00001076 // We need to emit a shl + ashr to do the sign extend.
1077 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1078 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
1079 ShAmt);
Chris Lattnerc3aca382010-01-10 00:58:42 +00001080 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001081
Chris Lattner43f2fa62010-01-18 22:19:16 +00001082 // If this input is a trunc from our destination, then turn sext(trunc(x))
1083 // into shifts.
1084 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1085 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1086 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1087 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Craig Topper3529aa52013-01-24 05:22:40 +00001088
Chris Lattner43f2fa62010-01-18 22:19:16 +00001089 // We need to emit a shl + ashr to do the sign extend.
1090 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1091 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1092 return BinaryOperator::CreateAShr(Res, ShAmt);
1093 }
Nate Begeman7aa18bf2010-12-17 23:12:19 +00001094
Benjamin Kramer398b8c52011-04-01 20:09:03 +00001095 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1096 return transformSExtICmp(ICI, CI);
Bill Wendling5e360552010-12-17 23:27:41 +00001097
Chris Lattner2b295a02010-01-04 07:53:58 +00001098 // If the input is a shl/ashr pair of a same constant, then this is a sign
1099 // extension from a smaller value. If we could trust arbitrary bitwidth
1100 // integers, we could turn this into a truncate to the smaller bit and then
1101 // use a sext for the whole extension. Since we don't, look deeper and check
1102 // for a truncate. If the source and dest are the same type, eliminate the
1103 // trunc and extend and just do shifts. For example, turn:
1104 // %a = trunc i32 %i to i8
1105 // %b = shl i8 %a, 6
1106 // %c = ashr i8 %b, 6
1107 // %d = sext i8 %c to i32
1108 // into:
1109 // %a = shl i32 %i, 30
1110 // %d = ashr i32 %a, 30
1111 Value *A = 0;
Chris Lattnerc95a7a22010-01-10 01:04:31 +00001112 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
Chris Lattner2b295a02010-01-04 07:53:58 +00001113 ConstantInt *BA = 0, *CA = 0;
Chris Lattnerc95a7a22010-01-10 01:04:31 +00001114 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
Chris Lattner2b295a02010-01-04 07:53:58 +00001115 m_ConstantInt(CA))) &&
Chris Lattnerc95a7a22010-01-10 01:04:31 +00001116 BA == CA && A->getType() == CI.getType()) {
1117 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1118 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1119 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1120 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1121 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1122 return BinaryOperator::CreateAShr(A, ShAmtV);
Chris Lattner2b295a02010-01-04 07:53:58 +00001123 }
Craig Topper3529aa52013-01-24 05:22:40 +00001124
Chris Lattner2b295a02010-01-04 07:53:58 +00001125 return 0;
1126}
1127
1128
1129/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1130/// in the specified FP type without changing its value.
1131static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1132 bool losesInfo;
1133 APFloat F = CFP->getValueAPF();
1134 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1135 if (!losesInfo)
1136 return ConstantFP::get(CFP->getContext(), F);
1137 return 0;
1138}
1139
1140/// LookThroughFPExtensions - If this is an fp extension instruction, look
1141/// through it until we get the source value.
1142static Value *LookThroughFPExtensions(Value *V) {
1143 if (Instruction *I = dyn_cast<Instruction>(V))
1144 if (I->getOpcode() == Instruction::FPExt)
1145 return LookThroughFPExtensions(I->getOperand(0));
Craig Topper3529aa52013-01-24 05:22:40 +00001146
Chris Lattner2b295a02010-01-04 07:53:58 +00001147 // If this value is a constant, return the constant in the smallest FP type
1148 // that can accurately represent it. This allows us to turn
1149 // (float)((double)X+2.0) into x+2.0f.
1150 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1151 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1152 return V; // No constant folding of this.
Dan Gohman518cda42011-12-17 00:04:22 +00001153 // See if the value can be truncated to half and then reextended.
1154 if (Value *V = FitsInFPType(CFP, APFloat::IEEEhalf))
1155 return V;
Chris Lattner2b295a02010-01-04 07:53:58 +00001156 // See if the value can be truncated to float and then reextended.
1157 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1158 return V;
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001159 if (CFP->getType()->isDoubleTy())
Chris Lattner2b295a02010-01-04 07:53:58 +00001160 return V; // Won't shrink.
1161 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1162 return V;
1163 // Don't try to shrink to various long double types.
1164 }
Craig Topper3529aa52013-01-24 05:22:40 +00001165
Chris Lattner2b295a02010-01-04 07:53:58 +00001166 return V;
1167}
1168
1169Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1170 if (Instruction *I = commonCastTransforms(CI))
1171 return I;
Stephen Canonc4549642013-11-28 21:38:05 +00001172 // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
1173 // simpilify this expression to avoid one or more of the trunc/extend
1174 // operations if we can do so without changing the numerical results.
1175 //
1176 // The exact manner in which the widths of the operands interact to limit
1177 // what we can and cannot do safely varies from operation to operation, and
1178 // is explained below in the various case statements.
Chris Lattner2b295a02010-01-04 07:53:58 +00001179 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1180 if (OpI && OpI->hasOneUse()) {
Stephen Canonc4549642013-11-28 21:38:05 +00001181 Value *LHSOrig = LookThroughFPExtensions(OpI->getOperand(0));
1182 Value *RHSOrig = LookThroughFPExtensions(OpI->getOperand(1));
1183 unsigned OpWidth = OpI->getType()->getFPMantissaWidth();
1184 unsigned LHSWidth = LHSOrig->getType()->getFPMantissaWidth();
1185 unsigned RHSWidth = RHSOrig->getType()->getFPMantissaWidth();
1186 unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
1187 unsigned DstWidth = CI.getType()->getFPMantissaWidth();
Chris Lattner2b295a02010-01-04 07:53:58 +00001188 switch (OpI->getOpcode()) {
Stephen Canonc4549642013-11-28 21:38:05 +00001189 default: break;
1190 case Instruction::FAdd:
1191 case Instruction::FSub:
1192 // For addition and subtraction, the infinitely precise result can
1193 // essentially be arbitrarily wide; proving that double rounding
1194 // will not occur because the result of OpI is exact (as we will for
1195 // FMul, for example) is hopeless. However, we *can* nonetheless
1196 // frequently know that double rounding cannot occur (or that it is
Alp Tokercb402912014-01-24 17:20:08 +00001197 // innocuous) by taking advantage of the specific structure of
Stephen Canonc4549642013-11-28 21:38:05 +00001198 // infinitely-precise results that admit double rounding.
1199 //
Alp Tokercb402912014-01-24 17:20:08 +00001200 // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
Stephen Canonc4549642013-11-28 21:38:05 +00001201 // to represent both sources, we can guarantee that the double
1202 // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
1203 // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
1204 // for proof of this fact).
1205 //
1206 // Note: Figueroa does not consider the case where DstFormat !=
1207 // SrcFormat. It's possible (likely even!) that this analysis
1208 // could be tightened for those cases, but they are rare (the main
1209 // case of interest here is (float)((double)float + float)).
1210 if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
1211 if (LHSOrig->getType() != CI.getType())
1212 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1213 if (RHSOrig->getType() != CI.getType())
1214 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001215 Instruction *RI =
1216 BinaryOperator::Create(OpI->getOpcode(), LHSOrig, RHSOrig);
1217 RI->copyFastMathFlags(OpI);
1218 return RI;
Chris Lattner2b295a02010-01-04 07:53:58 +00001219 }
Stephen Canonc4549642013-11-28 21:38:05 +00001220 break;
1221 case Instruction::FMul:
1222 // For multiplication, the infinitely precise result has at most
1223 // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
1224 // that such a value can be exactly represented, then no double
1225 // rounding can possibly occur; we can safely perform the operation
1226 // in the destination format if it can represent both sources.
1227 if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
1228 if (LHSOrig->getType() != CI.getType())
1229 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1230 if (RHSOrig->getType() != CI.getType())
1231 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001232 Instruction *RI =
1233 BinaryOperator::CreateFMul(LHSOrig, RHSOrig);
1234 RI->copyFastMathFlags(OpI);
1235 return RI;
Stephen Canonc4549642013-11-28 21:38:05 +00001236 }
1237 break;
1238 case Instruction::FDiv:
1239 // For division, we use again use the bound from Figueroa's
1240 // dissertation. I am entirely certain that this bound can be
1241 // tightened in the unbalanced operand case by an analysis based on
1242 // the diophantine rational approximation bound, but the well-known
1243 // condition used here is a good conservative first pass.
1244 // TODO: Tighten bound via rigorous analysis of the unbalanced case.
1245 if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
1246 if (LHSOrig->getType() != CI.getType())
1247 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1248 if (RHSOrig->getType() != CI.getType())
1249 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001250 Instruction *RI =
1251 BinaryOperator::CreateFDiv(LHSOrig, RHSOrig);
1252 RI->copyFastMathFlags(OpI);
1253 return RI;
Stephen Canonc4549642013-11-28 21:38:05 +00001254 }
1255 break;
1256 case Instruction::FRem:
1257 // Remainder is straightforward. Remainder is always exact, so the
1258 // type of OpI doesn't enter into things at all. We simply evaluate
1259 // in whichever source type is larger, then convert to the
1260 // destination type.
1261 if (LHSWidth < SrcWidth)
1262 LHSOrig = Builder->CreateFPExt(LHSOrig, RHSOrig->getType());
1263 else if (RHSWidth <= SrcWidth)
1264 RHSOrig = Builder->CreateFPExt(RHSOrig, LHSOrig->getType());
1265 Value *ExactResult = Builder->CreateFRem(LHSOrig, RHSOrig);
Owen Anderson48b842e2014-01-18 00:48:14 +00001266 if (Instruction *RI = dyn_cast<Instruction>(ExactResult))
1267 RI->copyFastMathFlags(OpI);
Stephen Canonc4549642013-11-28 21:38:05 +00001268 return CastInst::CreateFPCast(ExactResult, CI.getType());
Chris Lattner2b295a02010-01-04 07:53:58 +00001269 }
Owen Andersondbf0ca52013-01-10 22:06:52 +00001270
1271 // (fptrunc (fneg x)) -> (fneg (fptrunc x))
1272 if (BinaryOperator::isFNeg(OpI)) {
1273 Value *InnerTrunc = Builder->CreateFPTrunc(OpI->getOperand(1),
1274 CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001275 Instruction *RI = BinaryOperator::CreateFNeg(InnerTrunc);
1276 RI->copyFastMathFlags(OpI);
1277 return RI;
Owen Andersondbf0ca52013-01-10 22:06:52 +00001278 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001279 }
Owen Andersondbf0ca52013-01-10 22:06:52 +00001280
Owen Anderson5797bfd2013-10-03 21:08:05 +00001281 // (fptrunc (select cond, R1, Cst)) -->
1282 // (select cond, (fptrunc R1), (fptrunc Cst))
1283 SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0));
1284 if (SI &&
1285 (isa<ConstantFP>(SI->getOperand(1)) ||
1286 isa<ConstantFP>(SI->getOperand(2)))) {
1287 Value *LHSTrunc = Builder->CreateFPTrunc(SI->getOperand(1),
1288 CI.getType());
1289 Value *RHSTrunc = Builder->CreateFPTrunc(SI->getOperand(2),
1290 CI.getType());
1291 return SelectInst::Create(SI->getOperand(0), LHSTrunc, RHSTrunc);
1292 }
1293
Owen Andersondbf0ca52013-01-10 22:06:52 +00001294 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI.getOperand(0));
1295 if (II) {
1296 switch (II->getIntrinsicID()) {
1297 default: break;
1298 case Intrinsic::fabs: {
1299 // (fptrunc (fabs x)) -> (fabs (fptrunc x))
1300 Value *InnerTrunc = Builder->CreateFPTrunc(II->getArgOperand(0),
1301 CI.getType());
1302 Type *IntrinsicType[] = { CI.getType() };
1303 Function *Overload =
1304 Intrinsic::getDeclaration(CI.getParent()->getParent()->getParent(),
1305 II->getIntrinsicID(), IntrinsicType);
1306
1307 Value *Args[] = { InnerTrunc };
1308 return CallInst::Create(Overload, Args, II->getName());
1309 }
1310 }
1311 }
1312
Owen Anderson32a58342010-07-19 08:09:34 +00001313 // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
Hal Finkel12100bf2013-11-16 21:29:08 +00001314 // Note that we restrict this transformation based on
1315 // TLI->has(LibFunc::sqrtf), even for the sqrt intrinsic, because
1316 // TLI->has(LibFunc::sqrtf) is sufficient to guarantee that the
1317 // single-precision intrinsic can be expanded in the backend.
Owen Anderson32a58342010-07-19 08:09:34 +00001318 CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
Chad Rosiere6de63d2011-12-01 21:29:16 +00001319 if (Call && Call->getCalledFunction() && TLI->has(LibFunc::sqrtf) &&
Hal Finkel12100bf2013-11-16 21:29:08 +00001320 (Call->getCalledFunction()->getName() == TLI->getName(LibFunc::sqrt) ||
1321 Call->getCalledFunction()->getIntrinsicID() == Intrinsic::sqrt) &&
Evan Chengb94674b2011-07-13 19:08:16 +00001322 Call->getNumArgOperands() == 1 &&
1323 Call->hasOneUse()) {
Owen Anderson32a58342010-07-19 08:09:34 +00001324 CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
1325 if (Arg && Arg->getOpcode() == Instruction::FPExt &&
Owen Anderson84774ed2010-07-19 19:23:32 +00001326 CI.getType()->isFloatTy() &&
1327 Call->getType()->isDoubleTy() &&
1328 Arg->getType()->isDoubleTy() &&
1329 Arg->getOperand(0)->getType()->isFloatTy()) {
1330 Function *Callee = Call->getCalledFunction();
1331 Module *M = CI.getParent()->getParent()->getParent();
Hal Finkel12100bf2013-11-16 21:29:08 +00001332 Constant *SqrtfFunc = (Callee->getIntrinsicID() == Intrinsic::sqrt) ?
1333 Intrinsic::getDeclaration(M, Intrinsic::sqrt, Builder->getFloatTy()) :
1334 M->getOrInsertFunction("sqrtf", Callee->getAttributes(),
1335 Builder->getFloatTy(), Builder->getFloatTy(),
1336 NULL);
Owen Anderson32a58342010-07-19 08:09:34 +00001337 CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
1338 "sqrtfcall");
Owen Anderson84774ed2010-07-19 19:23:32 +00001339 ret->setAttributes(Callee->getAttributes());
Craig Topper3529aa52013-01-24 05:22:40 +00001340
1341
Chris Lattner6e27b3e2010-09-07 20:01:38 +00001342 // Remove the old Call. With -fmath-errno, it won't get marked readnone.
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00001343 ReplaceInstUsesWith(*Call, UndefValue::get(Call->getType()));
Chris Lattner6e27b3e2010-09-07 20:01:38 +00001344 EraseInstFromFunction(*Call);
Owen Anderson32a58342010-07-19 08:09:34 +00001345 return ret;
1346 }
1347 }
Craig Topper3529aa52013-01-24 05:22:40 +00001348
Chris Lattner2b295a02010-01-04 07:53:58 +00001349 return 0;
1350}
1351
1352Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1353 return commonCastTransforms(CI);
1354}
1355
1356Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1357 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1358 if (OpI == 0)
1359 return commonCastTransforms(FI);
1360
1361 // fptoui(uitofp(X)) --> X
1362 // fptoui(sitofp(X)) --> X
1363 // This is safe if the intermediate type has enough bits in its mantissa to
1364 // accurately represent all values of X. For example, do not do this with
1365 // i64->float->i64. This is also safe for sitofp case, because any negative
Craig Topper3529aa52013-01-24 05:22:40 +00001366 // 'X' value would cause an undefined result for the fptoui.
Chris Lattner2b295a02010-01-04 07:53:58 +00001367 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1368 OpI->getOperand(0)->getType() == FI.getType() &&
1369 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1370 OpI->getType()->getFPMantissaWidth())
1371 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1372
1373 return commonCastTransforms(FI);
1374}
1375
1376Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1377 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1378 if (OpI == 0)
1379 return commonCastTransforms(FI);
Craig Topper3529aa52013-01-24 05:22:40 +00001380
Chris Lattner2b295a02010-01-04 07:53:58 +00001381 // fptosi(sitofp(X)) --> X
1382 // fptosi(uitofp(X)) --> X
1383 // This is safe if the intermediate type has enough bits in its mantissa to
1384 // accurately represent all values of X. For example, do not do this with
1385 // i64->float->i64. This is also safe for sitofp case, because any negative
Craig Topper3529aa52013-01-24 05:22:40 +00001386 // 'X' value would cause an undefined result for the fptoui.
Chris Lattner2b295a02010-01-04 07:53:58 +00001387 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1388 OpI->getOperand(0)->getType() == FI.getType() &&
1389 (int)FI.getType()->getScalarSizeInBits() <=
1390 OpI->getType()->getFPMantissaWidth())
1391 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Craig Topper3529aa52013-01-24 05:22:40 +00001392
Chris Lattner2b295a02010-01-04 07:53:58 +00001393 return commonCastTransforms(FI);
1394}
1395
1396Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1397 return commonCastTransforms(CI);
1398}
1399
1400Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1401 return commonCastTransforms(CI);
1402}
1403
Chris Lattner2b295a02010-01-04 07:53:58 +00001404Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Dan Gohman949458d2010-02-02 01:44:02 +00001405 // If the source integer type is not the intptr_t type for this target, do a
1406 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1407 // cast to be exposed to other transforms.
Benjamin Kramer944e0ab2013-02-05 20:22:40 +00001408
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001409 if (DL) {
Matt Arsenault745101d2013-08-21 19:53:10 +00001410 unsigned AS = CI.getAddressSpace();
1411 if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001412 DL->getPointerSizeInBits(AS)) {
1413 Type *Ty = DL->getIntPtrType(CI.getContext(), AS);
Matt Arsenault745101d2013-08-21 19:53:10 +00001414 if (CI.getType()->isVectorTy()) // Handle vectors of pointers.
1415 Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements());
1416
1417 Value *P = Builder->CreateZExtOrTrunc(CI.getOperand(0), Ty);
1418 return new IntToPtrInst(P, CI.getType());
1419 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001420 }
Craig Topper3529aa52013-01-24 05:22:40 +00001421
Chris Lattner2b295a02010-01-04 07:53:58 +00001422 if (Instruction *I = commonCastTransforms(CI))
1423 return I;
1424
1425 return 0;
1426}
1427
Chris Lattnera93c63c2010-01-05 22:21:18 +00001428/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1429Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1430 Value *Src = CI.getOperand(0);
Craig Topper3529aa52013-01-24 05:22:40 +00001431
Chris Lattnera93c63c2010-01-05 22:21:18 +00001432 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1433 // If casting the result of a getelementptr instruction with no offset, turn
1434 // this into a cast of the original pointer!
1435 if (GEP->hasAllZeroIndices()) {
1436 // Changing the cast operand is usually not a good idea but it is safe
Craig Topper3529aa52013-01-24 05:22:40 +00001437 // here because the pointer operand is being replaced with another
Chris Lattnera93c63c2010-01-05 22:21:18 +00001438 // pointer operand so the opcode doesn't need to change.
1439 Worklist.Add(GEP);
1440 CI.setOperand(0, GEP->getOperand(0));
1441 return &CI;
1442 }
Craig Topper3529aa52013-01-24 05:22:40 +00001443
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001444 if (!DL)
Matt Arsenault94a028a2013-08-19 22:17:18 +00001445 return commonCastTransforms(CI);
1446
Chris Lattnera93c63c2010-01-05 22:21:18 +00001447 // If the GEP has a single use, and the base pointer is a bitcast, and the
1448 // GEP computes a constant offset, see if we can convert these three
1449 // instructions into fewer. This typically happens with unions and other
1450 // non-type-safe code.
Matt Arsenault745101d2013-08-21 19:53:10 +00001451 unsigned AS = GEP->getPointerAddressSpace();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001452 unsigned OffsetBits = DL->getPointerSizeInBits(AS);
Matt Arsenault94a028a2013-08-19 22:17:18 +00001453 APInt Offset(OffsetBits, 0);
1454 BitCastInst *BCI = dyn_cast<BitCastInst>(GEP->getOperand(0));
1455 if (GEP->hasOneUse() &&
1456 BCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001457 GEP->accumulateConstantOffset(*DL, Offset)) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001458 // Get the base pointer input of the bitcast, and the type it points to.
Matt Arsenault94a028a2013-08-19 22:17:18 +00001459 Value *OrigBase = BCI->getOperand(0);
Chris Lattnera93c63c2010-01-05 22:21:18 +00001460 SmallVector<Value*, 8> NewIndices;
Matt Arsenaultd79f7d92013-08-19 22:17:40 +00001461 if (FindElementAtOffset(OrigBase->getType(),
1462 Offset.getSExtValue(),
1463 NewIndices)) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001464 // If we were able to index down into an element, create the GEP
1465 // and bitcast the result. This eliminates one bitcast, potentially
1466 // two.
1467 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
Matt Arsenault94a028a2013-08-19 22:17:18 +00001468 Builder->CreateInBoundsGEP(OrigBase, NewIndices) :
1469 Builder->CreateGEP(OrigBase, NewIndices);
Chris Lattnera93c63c2010-01-05 22:21:18 +00001470 NGEP->takeName(GEP);
Craig Topper3529aa52013-01-24 05:22:40 +00001471
Chris Lattnera93c63c2010-01-05 22:21:18 +00001472 if (isa<BitCastInst>(CI))
1473 return new BitCastInst(NGEP, CI.getType());
1474 assert(isa<PtrToIntInst>(CI));
1475 return new PtrToIntInst(NGEP, CI.getType());
Craig Topper3529aa52013-01-24 05:22:40 +00001476 }
Chris Lattnera93c63c2010-01-05 22:21:18 +00001477 }
1478 }
Craig Topper3529aa52013-01-24 05:22:40 +00001479
Chris Lattnera93c63c2010-01-05 22:21:18 +00001480 return commonCastTransforms(CI);
1481}
1482
1483Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
Dan Gohman949458d2010-02-02 01:44:02 +00001484 // If the destination integer type is not the intptr_t type for this target,
1485 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1486 // to be exposed to other transforms.
Benjamin Kramere4778752013-02-05 19:21:56 +00001487
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001488 if (!DL)
Matt Arsenault745101d2013-08-21 19:53:10 +00001489 return commonPointerCastTransforms(CI);
Craig Topper3529aa52013-01-24 05:22:40 +00001490
Matt Arsenault745101d2013-08-21 19:53:10 +00001491 Type *Ty = CI.getType();
1492 unsigned AS = CI.getPointerAddressSpace();
1493
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001494 if (Ty->getScalarSizeInBits() == DL->getPointerSizeInBits(AS))
Matt Arsenault745101d2013-08-21 19:53:10 +00001495 return commonPointerCastTransforms(CI);
1496
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001497 Type *PtrTy = DL->getIntPtrType(CI.getContext(), AS);
Matt Arsenault745101d2013-08-21 19:53:10 +00001498 if (Ty->isVectorTy()) // Handle vectors of pointers.
1499 PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements());
1500
1501 Value *P = Builder->CreatePtrToInt(CI.getOperand(0), PtrTy);
1502 return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
Chris Lattnera93c63c2010-01-05 22:21:18 +00001503}
1504
Chris Lattner02b0df52010-05-08 21:50:26 +00001505/// OptimizeVectorResize - This input value (which is known to have vector type)
1506/// is being zero extended or truncated to the specified vector type. Try to
1507/// replace it with a shuffle (and vector/vector bitcast) if possible.
1508///
1509/// The source and destination vector types may have different element types.
Chris Lattner229907c2011-07-18 04:54:35 +00001510static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
Chris Lattner02b0df52010-05-08 21:50:26 +00001511 InstCombiner &IC) {
1512 // We can only do this optimization if the output is a multiple of the input
1513 // element size, or the input is a multiple of the output element size.
1514 // Convert the input type to have the same element type as the output.
Chris Lattner229907c2011-07-18 04:54:35 +00001515 VectorType *SrcTy = cast<VectorType>(InVal->getType());
Craig Topper3529aa52013-01-24 05:22:40 +00001516
Chris Lattner02b0df52010-05-08 21:50:26 +00001517 if (SrcTy->getElementType() != DestTy->getElementType()) {
1518 // The input types don't need to be identical, but for now they must be the
1519 // same size. There is no specific reason we couldn't handle things like
1520 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
Craig Topper3529aa52013-01-24 05:22:40 +00001521 // there yet.
Chris Lattner02b0df52010-05-08 21:50:26 +00001522 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1523 DestTy->getElementType()->getPrimitiveSizeInBits())
1524 return 0;
Craig Topper3529aa52013-01-24 05:22:40 +00001525
Chris Lattner02b0df52010-05-08 21:50:26 +00001526 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1527 InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1528 }
Craig Topper3529aa52013-01-24 05:22:40 +00001529
Chris Lattner02b0df52010-05-08 21:50:26 +00001530 // Now that the element types match, get the shuffle mask and RHS of the
1531 // shuffle to use, which depends on whether we're increasing or decreasing the
1532 // size of the input.
Chris Lattner8213c8a2012-02-06 21:56:39 +00001533 SmallVector<uint32_t, 16> ShuffleMask;
Chris Lattner02b0df52010-05-08 21:50:26 +00001534 Value *V2;
Craig Topper3529aa52013-01-24 05:22:40 +00001535
Chris Lattner02b0df52010-05-08 21:50:26 +00001536 if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1537 // If we're shrinking the number of elements, just shuffle in the low
1538 // elements from the input and use undef as the second shuffle input.
1539 V2 = UndefValue::get(SrcTy);
1540 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
Chris Lattner8213c8a2012-02-06 21:56:39 +00001541 ShuffleMask.push_back(i);
Craig Topper3529aa52013-01-24 05:22:40 +00001542
Chris Lattner02b0df52010-05-08 21:50:26 +00001543 } else {
1544 // If we're increasing the number of elements, shuffle in all of the
1545 // elements from InVal and fill the rest of the result elements with zeros
1546 // from a constant zero.
1547 V2 = Constant::getNullValue(SrcTy);
1548 unsigned SrcElts = SrcTy->getNumElements();
1549 for (unsigned i = 0, e = SrcElts; i != e; ++i)
Chris Lattner8213c8a2012-02-06 21:56:39 +00001550 ShuffleMask.push_back(i);
Chris Lattner02b0df52010-05-08 21:50:26 +00001551
1552 // The excess elements reference the first element of the zero input.
Chris Lattner8213c8a2012-02-06 21:56:39 +00001553 for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i)
1554 ShuffleMask.push_back(SrcElts);
Chris Lattner02b0df52010-05-08 21:50:26 +00001555 }
Craig Topper3529aa52013-01-24 05:22:40 +00001556
Chris Lattner8213c8a2012-02-06 21:56:39 +00001557 return new ShuffleVectorInst(InVal, V2,
1558 ConstantDataVector::get(V2->getContext(),
1559 ShuffleMask));
Chris Lattner02b0df52010-05-08 21:50:26 +00001560}
1561
Chris Lattner229907c2011-07-18 04:54:35 +00001562static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
Chris Lattnerdd660102010-08-28 01:20:38 +00001563 return Value % Ty->getPrimitiveSizeInBits() == 0;
1564}
1565
Chris Lattner229907c2011-07-18 04:54:35 +00001566static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
Chris Lattnerdd660102010-08-28 01:20:38 +00001567 return Value / Ty->getPrimitiveSizeInBits();
1568}
1569
1570/// CollectInsertionElements - V is a value which is inserted into a vector of
1571/// VecEltTy. Look through the value to see if we can decompose it into
1572/// insertions into the vector. See the example in the comment for
1573/// OptimizeIntegerToVectorInsertions for the pattern this handles.
1574/// The type of V is always a non-zero multiple of VecEltTy's size.
Richard Sandifordfeb34712013-08-12 07:26:09 +00001575/// Shift is the number of bits between the lsb of V and the lsb of
1576/// the vector.
Chris Lattnerdd660102010-08-28 01:20:38 +00001577///
1578/// This returns false if the pattern can't be matched or true if it can,
1579/// filling in Elements with the elements found here.
Richard Sandifordfeb34712013-08-12 07:26:09 +00001580static bool CollectInsertionElements(Value *V, unsigned Shift,
Chris Lattnerdd660102010-08-28 01:20:38 +00001581 SmallVectorImpl<Value*> &Elements,
Richard Sandifordfeb34712013-08-12 07:26:09 +00001582 Type *VecEltTy, InstCombiner &IC) {
1583 assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
1584 "Shift should be a multiple of the element type size");
1585
Chris Lattner50df36a2010-08-28 03:36:51 +00001586 // Undef values never contribute useful bits to the result.
1587 if (isa<UndefValue>(V)) return true;
Craig Topper3529aa52013-01-24 05:22:40 +00001588
Chris Lattnerdd660102010-08-28 01:20:38 +00001589 // If we got down to a value of the right type, we win, try inserting into the
1590 // right element.
1591 if (V->getType() == VecEltTy) {
Chris Lattnerd0214f32010-08-28 01:50:57 +00001592 // Inserting null doesn't actually insert any elements.
1593 if (Constant *C = dyn_cast<Constant>(V))
1594 if (C->isNullValue())
1595 return true;
Craig Topper3529aa52013-01-24 05:22:40 +00001596
Richard Sandifordfeb34712013-08-12 07:26:09 +00001597 unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
1598 if (IC.getDataLayout()->isBigEndian())
1599 ElementIndex = Elements.size() - ElementIndex - 1;
1600
Chris Lattnerdd660102010-08-28 01:20:38 +00001601 // Fail if multiple elements are inserted into this slot.
Richard Sandifordfeb34712013-08-12 07:26:09 +00001602 if (Elements[ElementIndex] != 0)
Chris Lattnerdd660102010-08-28 01:20:38 +00001603 return false;
Craig Topper3529aa52013-01-24 05:22:40 +00001604
Chris Lattnerdd660102010-08-28 01:20:38 +00001605 Elements[ElementIndex] = V;
1606 return true;
1607 }
Craig Topper3529aa52013-01-24 05:22:40 +00001608
Chris Lattnerd0214f32010-08-28 01:50:57 +00001609 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerdd660102010-08-28 01:20:38 +00001610 // Figure out the # elements this provides, and bitcast it or slice it up
1611 // as required.
Chris Lattnerd0214f32010-08-28 01:50:57 +00001612 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1613 VecEltTy);
1614 // If the constant is the size of a vector element, we just need to bitcast
1615 // it to the right type so it gets properly inserted.
1616 if (NumElts == 1)
1617 return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
Richard Sandifordfeb34712013-08-12 07:26:09 +00001618 Shift, Elements, VecEltTy, IC);
Craig Topper3529aa52013-01-24 05:22:40 +00001619
Chris Lattnerd0214f32010-08-28 01:50:57 +00001620 // Okay, this is a constant that covers multiple elements. Slice it up into
1621 // pieces and insert each element-sized piece into the vector.
1622 if (!isa<IntegerType>(C->getType()))
1623 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1624 C->getType()->getPrimitiveSizeInBits()));
1625 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +00001626 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
Craig Topper3529aa52013-01-24 05:22:40 +00001627
Chris Lattnerd0214f32010-08-28 01:50:57 +00001628 for (unsigned i = 0; i != NumElts; ++i) {
Richard Sandifordfeb34712013-08-12 07:26:09 +00001629 unsigned ShiftI = Shift+i*ElementSize;
Chris Lattnerd0214f32010-08-28 01:50:57 +00001630 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
Richard Sandifordfeb34712013-08-12 07:26:09 +00001631 ShiftI));
Chris Lattnerd0214f32010-08-28 01:50:57 +00001632 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
Richard Sandifordfeb34712013-08-12 07:26:09 +00001633 if (!CollectInsertionElements(Piece, ShiftI, Elements, VecEltTy, IC))
Chris Lattnerd0214f32010-08-28 01:50:57 +00001634 return false;
1635 }
1636 return true;
1637 }
Craig Topper3529aa52013-01-24 05:22:40 +00001638
Chris Lattnerdd660102010-08-28 01:20:38 +00001639 if (!V->hasOneUse()) return false;
Craig Topper3529aa52013-01-24 05:22:40 +00001640
Chris Lattnerdd660102010-08-28 01:20:38 +00001641 Instruction *I = dyn_cast<Instruction>(V);
1642 if (I == 0) return false;
1643 switch (I->getOpcode()) {
1644 default: return false; // Unhandled case.
1645 case Instruction::BitCast:
Richard Sandifordfeb34712013-08-12 07:26:09 +00001646 return CollectInsertionElements(I->getOperand(0), Shift,
1647 Elements, VecEltTy, IC);
Chris Lattnerdd660102010-08-28 01:20:38 +00001648 case Instruction::ZExt:
1649 if (!isMultipleOfTypeSize(
1650 I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1651 VecEltTy))
1652 return false;
Richard Sandifordfeb34712013-08-12 07:26:09 +00001653 return CollectInsertionElements(I->getOperand(0), Shift,
1654 Elements, VecEltTy, IC);
Chris Lattnerdd660102010-08-28 01:20:38 +00001655 case Instruction::Or:
Richard Sandifordfeb34712013-08-12 07:26:09 +00001656 return CollectInsertionElements(I->getOperand(0), Shift,
1657 Elements, VecEltTy, IC) &&
1658 CollectInsertionElements(I->getOperand(1), Shift,
1659 Elements, VecEltTy, IC);
Chris Lattnerdd660102010-08-28 01:20:38 +00001660 case Instruction::Shl: {
1661 // Must be shifting by a constant that is a multiple of the element size.
1662 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
1663 if (CI == 0) return false;
Richard Sandifordfeb34712013-08-12 07:26:09 +00001664 Shift += CI->getZExtValue();
1665 if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
1666 return CollectInsertionElements(I->getOperand(0), Shift,
1667 Elements, VecEltTy, IC);
Chris Lattnerdd660102010-08-28 01:20:38 +00001668 }
Craig Topper3529aa52013-01-24 05:22:40 +00001669
Chris Lattnerdd660102010-08-28 01:20:38 +00001670 }
1671}
1672
1673
1674/// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
1675/// may be doing shifts and ors to assemble the elements of the vector manually.
1676/// Try to rip the code out and replace it with insertelements. This is to
1677/// optimize code like this:
1678///
1679/// %tmp37 = bitcast float %inc to i32
1680/// %tmp38 = zext i32 %tmp37 to i64
1681/// %tmp31 = bitcast float %inc5 to i32
1682/// %tmp32 = zext i32 %tmp31 to i64
1683/// %tmp33 = shl i64 %tmp32, 32
1684/// %ins35 = or i64 %tmp33, %tmp38
1685/// %tmp43 = bitcast i64 %ins35 to <2 x float>
1686///
1687/// Into two insertelements that do "buildvector{%inc, %inc5}".
1688static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
1689 InstCombiner &IC) {
Richard Sandifordfeb34712013-08-12 07:26:09 +00001690 // We need to know the target byte order to perform this optimization.
1691 if (!IC.getDataLayout()) return 0;
1692
Chris Lattner229907c2011-07-18 04:54:35 +00001693 VectorType *DestVecTy = cast<VectorType>(CI.getType());
Chris Lattnerdd660102010-08-28 01:20:38 +00001694 Value *IntInput = CI.getOperand(0);
1695
1696 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1697 if (!CollectInsertionElements(IntInput, 0, Elements,
Richard Sandifordfeb34712013-08-12 07:26:09 +00001698 DestVecTy->getElementType(), IC))
Chris Lattnerdd660102010-08-28 01:20:38 +00001699 return 0;
1700
1701 // If we succeeded, we know that all of the element are specified by Elements
1702 // or are zero if Elements has a null entry. Recast this as a set of
1703 // insertions.
1704 Value *Result = Constant::getNullValue(CI.getType());
1705 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
1706 if (Elements[i] == 0) continue; // Unset element.
Craig Topper3529aa52013-01-24 05:22:40 +00001707
Chris Lattnerdd660102010-08-28 01:20:38 +00001708 Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1709 IC.Builder->getInt32(i));
1710 }
Craig Topper3529aa52013-01-24 05:22:40 +00001711
Chris Lattnerdd660102010-08-28 01:20:38 +00001712 return Result;
1713}
1714
1715
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001716/// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
1717/// bitcast. The various long double bitcasts can't get in here.
Chris Lattnerbfd22282010-08-26 22:14:59 +00001718static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
Ulrich Weigand8a51d8e2013-03-26 15:36:14 +00001719 // We need to know the target byte order to perform this optimization.
1720 if (!IC.getDataLayout()) return 0;
1721
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001722 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001723 Type *DestTy = CI.getType();
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001724
1725 // If this is a bitcast from int to float, check to see if the int is an
1726 // extraction from a vector.
1727 Value *VecInput = 0;
Chris Lattnerbfd22282010-08-26 22:14:59 +00001728 // bitcast(trunc(bitcast(somevector)))
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001729 if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
1730 isa<VectorType>(VecInput->getType())) {
Chris Lattner229907c2011-07-18 04:54:35 +00001731 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattnerbfd22282010-08-26 22:14:59 +00001732 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1733
1734 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
1735 // If the element type of the vector doesn't match the result type,
1736 // bitcast it to be a vector type we can extract from.
1737 if (VecTy->getElementType() != DestTy) {
1738 VecTy = VectorType::get(DestTy,
1739 VecTy->getPrimitiveSizeInBits() / DestWidth);
1740 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1741 }
Craig Topper3529aa52013-01-24 05:22:40 +00001742
Ulrich Weigand8a51d8e2013-03-26 15:36:14 +00001743 unsigned Elt = 0;
1744 if (IC.getDataLayout()->isBigEndian())
1745 Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1;
1746 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
Chris Lattnerbfd22282010-08-26 22:14:59 +00001747 }
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001748 }
Craig Topper3529aa52013-01-24 05:22:40 +00001749
Chris Lattnerbfd22282010-08-26 22:14:59 +00001750 // bitcast(trunc(lshr(bitcast(somevector), cst))
1751 ConstantInt *ShAmt = 0;
1752 if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
1753 m_ConstantInt(ShAmt)))) &&
1754 isa<VectorType>(VecInput->getType())) {
Chris Lattner229907c2011-07-18 04:54:35 +00001755 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattnerbfd22282010-08-26 22:14:59 +00001756 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1757 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
1758 ShAmt->getZExtValue() % DestWidth == 0) {
1759 // If the element type of the vector doesn't match the result type,
1760 // bitcast it to be a vector type we can extract from.
1761 if (VecTy->getElementType() != DestTy) {
1762 VecTy = VectorType::get(DestTy,
1763 VecTy->getPrimitiveSizeInBits() / DestWidth);
1764 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1765 }
Craig Topper3529aa52013-01-24 05:22:40 +00001766
Chris Lattnerbfd22282010-08-26 22:14:59 +00001767 unsigned Elt = ShAmt->getZExtValue() / DestWidth;
Ulrich Weigand8a51d8e2013-03-26 15:36:14 +00001768 if (IC.getDataLayout()->isBigEndian())
1769 Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1 - Elt;
Chris Lattnerbfd22282010-08-26 22:14:59 +00001770 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
1771 }
1772 }
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001773 return 0;
1774}
Chris Lattner02b0df52010-05-08 21:50:26 +00001775
Chris Lattner2b295a02010-01-04 07:53:58 +00001776Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1777 // If the operands are integer typed then apply the integer transforms,
1778 // otherwise just apply the common ones.
1779 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001780 Type *SrcTy = Src->getType();
1781 Type *DestTy = CI.getType();
Chris Lattner2b295a02010-01-04 07:53:58 +00001782
Chris Lattner2b295a02010-01-04 07:53:58 +00001783 // Get rid of casts from one type to the same type. These are useless and can
1784 // be replaced by the operand.
1785 if (DestTy == Src->getType())
1786 return ReplaceInstUsesWith(CI, Src);
1787
Chris Lattner229907c2011-07-18 04:54:35 +00001788 if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1789 PointerType *SrcPTy = cast<PointerType>(SrcTy);
1790 Type *DstElTy = DstPTy->getElementType();
1791 Type *SrcElTy = SrcPTy->getElementType();
Craig Topper3529aa52013-01-24 05:22:40 +00001792
Chris Lattner2b295a02010-01-04 07:53:58 +00001793 // If we are casting a alloca to a pointer to a type of the same
1794 // size, rewrite the allocation instruction to allocate the "right" type.
1795 // There is no need to modify malloc calls because it is their bitcast that
1796 // needs to be cleaned up.
1797 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1798 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1799 return V;
Craig Topper3529aa52013-01-24 05:22:40 +00001800
Chris Lattner2b295a02010-01-04 07:53:58 +00001801 // If the source and destination are pointers, and this cast is equivalent
1802 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1803 // This can enhance SROA and other transforms that want type-safe pointers.
1804 Constant *ZeroUInt =
1805 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1806 unsigned NumZeros = 0;
Craig Topper3529aa52013-01-24 05:22:40 +00001807 while (SrcElTy != DstElTy &&
Duncan Sands19d0b472010-02-16 11:11:14 +00001808 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
Chris Lattner2b295a02010-01-04 07:53:58 +00001809 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1810 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1811 ++NumZeros;
1812 }
1813
1814 // If we found a path from the src to dest, create the getelementptr now.
1815 if (SrcElTy == DstElTy) {
1816 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Jay Foadd1b78492011-07-25 09:48:08 +00001817 return GetElementPtrInst::CreateInBounds(Src, Idxs);
Chris Lattner2b295a02010-01-04 07:53:58 +00001818 }
1819 }
Craig Topper3529aa52013-01-24 05:22:40 +00001820
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001821 // Try to optimize int -> float bitcasts.
1822 if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
1823 if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
1824 return I;
Chris Lattner2b295a02010-01-04 07:53:58 +00001825
Chris Lattner229907c2011-07-18 04:54:35 +00001826 if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Duncan Sands19d0b472010-02-16 11:11:14 +00001827 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001828 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1829 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2b295a02010-01-04 07:53:58 +00001830 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner2b295a02010-01-04 07:53:58 +00001831 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1832 }
Craig Topper3529aa52013-01-24 05:22:40 +00001833
Chris Lattnerdd660102010-08-28 01:20:38 +00001834 if (isa<IntegerType>(SrcTy)) {
1835 // If this is a cast from an integer to vector, check to see if the input
1836 // is a trunc or zext of a bitcast from vector. If so, we can replace all
1837 // the casts with a shuffle and (potentially) a bitcast.
1838 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
1839 CastInst *SrcCast = cast<CastInst>(Src);
1840 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1841 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1842 if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
Chris Lattner02b0df52010-05-08 21:50:26 +00001843 cast<VectorType>(DestTy), *this))
Chris Lattnerdd660102010-08-28 01:20:38 +00001844 return I;
1845 }
Craig Topper3529aa52013-01-24 05:22:40 +00001846
Chris Lattnerdd660102010-08-28 01:20:38 +00001847 // If the input is an 'or' instruction, we may be doing shifts and ors to
1848 // assemble the elements of the vector manually. Try to rip the code out
1849 // and replace it with insertelements.
1850 if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
1851 return ReplaceInstUsesWith(CI, V);
Chris Lattner02b0df52010-05-08 21:50:26 +00001852 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001853 }
1854
Chris Lattner229907c2011-07-18 04:54:35 +00001855 if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Michael Ilseman74a6da92013-02-11 21:41:44 +00001856 if (SrcVTy->getNumElements() == 1) {
1857 // If our destination is not a vector, then make this a straight
1858 // scalar-scalar cast.
1859 if (!DestTy->isVectorTy()) {
1860 Value *Elem =
1861 Builder->CreateExtractElement(Src,
1862 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1863 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1864 }
1865
1866 // Otherwise, see if our source is an insert. If so, then use the scalar
1867 // component directly.
1868 if (InsertElementInst *IEI =
1869 dyn_cast<InsertElementInst>(CI.getOperand(0)))
1870 return CastInst::Create(Instruction::BitCast, IEI->getOperand(1),
1871 DestTy);
Chris Lattner2b295a02010-01-04 07:53:58 +00001872 }
1873 }
1874
1875 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001876 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
Dan Gohmaneb7111b2010-04-07 23:22:42 +00001877 // a bitcast to a vector with the same # elts.
Craig Topper3529aa52013-01-24 05:22:40 +00001878 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
Matt Arsenaultfc00f7e2013-08-14 00:24:34 +00001879 DestTy->getVectorNumElements() == SVI->getType()->getNumElements() &&
Chris Lattnera93c63c2010-01-05 22:21:18 +00001880 SVI->getType()->getNumElements() ==
Matt Arsenaultfc00f7e2013-08-14 00:24:34 +00001881 SVI->getOperand(0)->getType()->getVectorNumElements()) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001882 BitCastInst *Tmp;
1883 // If either of the operands is a cast from CI.getType(), then
1884 // evaluating the shuffle in the casted destination's type will allow
1885 // us to eliminate at least one cast.
Craig Topper3529aa52013-01-24 05:22:40 +00001886 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
Chris Lattnera93c63c2010-01-05 22:21:18 +00001887 Tmp->getOperand(0)->getType() == DestTy) ||
Craig Topper3529aa52013-01-24 05:22:40 +00001888 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
Chris Lattnera93c63c2010-01-05 22:21:18 +00001889 Tmp->getOperand(0)->getType() == DestTy)) {
1890 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1891 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1892 // Return a new shuffle vector. Use the same element ID's, as we
1893 // know the vector types match #elts.
1894 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner2b295a02010-01-04 07:53:58 +00001895 }
1896 }
1897 }
Craig Topper3529aa52013-01-24 05:22:40 +00001898
Duncan Sands19d0b472010-02-16 11:11:14 +00001899 if (SrcTy->isPointerTy())
Chris Lattnera93c63c2010-01-05 22:21:18 +00001900 return commonPointerCastTransforms(CI);
1901 return commonCastTransforms(CI);
Chris Lattner2b295a02010-01-04 07:53:58 +00001902}
Matt Arsenaulta9e95ab2013-11-15 05:45:08 +00001903
1904Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
Matt Arsenault2d353d12014-01-14 20:00:45 +00001905 return commonPointerCastTransforms(CI);
Matt Arsenaulta9e95ab2013-11-15 05:45:08 +00001906}