blob: aec06f2b746105569d0d88cd34c33e391f3a6cb6 [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 Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/DataLayout.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000017#include "llvm/IR/PatternMatch.h"
Anna Thomas9ad45ad2016-07-08 22:15:08 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
Chris Lattner2b295a02010-01-04 07:53:58 +000019using namespace llvm;
20using namespace PatternMatch;
21
Chandler Carruth964daaa2014-04-22 02:55:47 +000022#define DEBUG_TYPE "instcombine"
23
Sanjay Patel2fbab9d82015-09-09 14:34:26 +000024/// Analyze 'Val', seeing if it is a simple linear expression.
25/// If so, decompose it, returning some value X, such that Val is
Chris Lattner59d95742010-01-04 07:59:07 +000026/// X*Scale+Offset.
27///
Sanjay Patele2834412015-09-09 14:54:29 +000028static Value *decomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Dan Gohman05a65552010-05-28 04:33:04 +000029 uint64_t &Offset) {
Chris Lattner59d95742010-01-04 07:59:07 +000030 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
31 Offset = CI->getZExtValue();
32 Scale = 0;
Dan Gohman05a65552010-05-28 04:33:04 +000033 return ConstantInt::get(Val->getType(), 0);
Chris Lattneraaccc8d2010-01-05 20:57:30 +000034 }
Craig Topper3529aa52013-01-24 05:22:40 +000035
Chris Lattneraaccc8d2010-01-05 20:57:30 +000036 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
Bob Wilson3c68b622011-07-08 22:09:33 +000037 // Cannot look past anything that might overflow.
38 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
Stepan Dyatkovskiycb2a1a32012-05-05 07:09:40 +000039 if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) {
Bob Wilson3c68b622011-07-08 22:09:33 +000040 Scale = 1;
41 Offset = 0;
42 return Val;
43 }
44
Chris Lattner59d95742010-01-04 07:59:07 +000045 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
46 if (I->getOpcode() == Instruction::Shl) {
47 // This is a value scaled by '1 << the shift amt'.
Dan Gohman05a65552010-05-28 04:33:04 +000048 Scale = UINT64_C(1) << RHS->getZExtValue();
Chris Lattner59d95742010-01-04 07:59:07 +000049 Offset = 0;
50 return I->getOperand(0);
Chris Lattneraaccc8d2010-01-05 20:57:30 +000051 }
Craig Topper3529aa52013-01-24 05:22:40 +000052
Chris Lattneraaccc8d2010-01-05 20:57:30 +000053 if (I->getOpcode() == Instruction::Mul) {
Chris Lattner59d95742010-01-04 07:59:07 +000054 // This value is scaled by 'RHS'.
55 Scale = RHS->getZExtValue();
56 Offset = 0;
57 return I->getOperand(0);
Chris Lattneraaccc8d2010-01-05 20:57:30 +000058 }
Craig Topper3529aa52013-01-24 05:22:40 +000059
Chris Lattneraaccc8d2010-01-05 20:57:30 +000060 if (I->getOpcode() == Instruction::Add) {
Craig Topper3529aa52013-01-24 05:22:40 +000061 // We have X+C. Check to see if we really have (X*C2)+C1,
Chris Lattner59d95742010-01-04 07:59:07 +000062 // where C1 is divisible by C2.
63 unsigned SubScale;
Craig Topper3529aa52013-01-24 05:22:40 +000064 Value *SubVal =
Sanjay Patele2834412015-09-09 14:54:29 +000065 decomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
Chris Lattner59d95742010-01-04 07:59:07 +000066 Offset += RHS->getZExtValue();
67 Scale = SubScale;
68 return SubVal;
69 }
70 }
71 }
72
73 // Otherwise, we can't look past this.
74 Scale = 1;
75 Offset = 0;
76 return Val;
77}
78
Sanjay Patel2fbab9d82015-09-09 14:34:26 +000079/// If we find a cast of an allocation instruction, try to eliminate the cast by
80/// moving the type information into the alloc.
Chris Lattner59d95742010-01-04 07:59:07 +000081Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
82 AllocaInst &AI) {
Chris Lattner229907c2011-07-18 04:54:35 +000083 PointerType *PTy = cast<PointerType>(CI.getType());
Craig Topper3529aa52013-01-24 05:22:40 +000084
Chris Lattner59d95742010-01-04 07:59:07 +000085 BuilderTy AllocaBuilder(*Builder);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +000086 AllocaBuilder.SetInsertPoint(&AI);
Chris Lattner59d95742010-01-04 07:59:07 +000087
88 // Get the type really allocated and the type casted to.
Chris Lattner229907c2011-07-18 04:54:35 +000089 Type *AllocElTy = AI.getAllocatedType();
90 Type *CastElTy = PTy->getElementType();
Craig Topperf40110f2014-04-25 05:29:35 +000091 if (!AllocElTy->isSized() || !CastElTy->isSized()) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +000092
Mehdi Aminia28d91d2015-03-10 02:37:25 +000093 unsigned AllocElTyAlign = DL.getABITypeAlignment(AllocElTy);
94 unsigned CastElTyAlign = DL.getABITypeAlignment(CastElTy);
Craig Topperf40110f2014-04-25 05:29:35 +000095 if (CastElTyAlign < AllocElTyAlign) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +000096
97 // If the allocation has multiple uses, only promote it if we are strictly
98 // increasing the alignment of the resultant allocation. If we keep it the
Devang Patelfbb482b2011-03-08 22:12:11 +000099 // same, we open the door to infinite loops of various kinds.
Craig Topperf40110f2014-04-25 05:29:35 +0000100 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +0000101
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000102 uint64_t AllocElTySize = DL.getTypeAllocSize(AllocElTy);
103 uint64_t CastElTySize = DL.getTypeAllocSize(CastElTy);
Craig Topperf40110f2014-04-25 05:29:35 +0000104 if (CastElTySize == 0 || AllocElTySize == 0) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +0000105
Jim Grosbach95d2eb92013-03-06 05:44:53 +0000106 // If the allocation has multiple uses, only promote it if we're not
107 // shrinking the amount of memory being allocated.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000108 uint64_t AllocElTyStoreSize = DL.getTypeStoreSize(AllocElTy);
109 uint64_t CastElTyStoreSize = DL.getTypeStoreSize(CastElTy);
Craig Topperf40110f2014-04-25 05:29:35 +0000110 if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return nullptr;
Jim Grosbach95d2eb92013-03-06 05:44:53 +0000111
Chris Lattner59d95742010-01-04 07:59:07 +0000112 // See if we can satisfy the modulus by pulling a scale out of the array
113 // size argument.
114 unsigned ArraySizeScale;
Dan Gohman05a65552010-05-28 04:33:04 +0000115 uint64_t ArrayOffset;
Chris Lattner59d95742010-01-04 07:59:07 +0000116 Value *NumElements = // See if the array size is a decomposable linear expr.
Sanjay Patele2834412015-09-09 14:54:29 +0000117 decomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
Craig Topper3529aa52013-01-24 05:22:40 +0000118
Chris Lattner59d95742010-01-04 07:59:07 +0000119 // If we can now satisfy the modulus, by using a non-1 scale, we really can
120 // do the xform.
121 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
Craig Topperf40110f2014-04-25 05:29:35 +0000122 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +0000123
124 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
Craig Topperf40110f2014-04-25 05:29:35 +0000125 Value *Amt = nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +0000126 if (Scale == 1) {
127 Amt = NumElements;
128 } else {
Dan Gohman05a65552010-05-28 04:33:04 +0000129 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
Chris Lattner59d95742010-01-04 07:59:07 +0000130 // Insert before the alloca, not before the cast.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000131 Amt = AllocaBuilder.CreateMul(Amt, NumElements);
Chris Lattner59d95742010-01-04 07:59:07 +0000132 }
Craig Topper3529aa52013-01-24 05:22:40 +0000133
Dan Gohman05a65552010-05-28 04:33:04 +0000134 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
135 Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
Chris Lattner59d95742010-01-04 07:59:07 +0000136 Offset, true);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000137 Amt = AllocaBuilder.CreateAdd(Amt, Off);
Chris Lattner59d95742010-01-04 07:59:07 +0000138 }
Craig Topper3529aa52013-01-24 05:22:40 +0000139
Chris Lattner59d95742010-01-04 07:59:07 +0000140 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
141 New->setAlignment(AI.getAlignment());
142 New->takeName(&AI);
Hans Wennborge36e1162014-04-28 17:40:03 +0000143 New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
Craig Topper3529aa52013-01-24 05:22:40 +0000144
Chris Lattner59d95742010-01-04 07:59:07 +0000145 // If the allocation has multiple real uses, insert a cast and change all
146 // things that used it to use the new cast. This will also hack on CI, but it
147 // will die soon.
Devang Patelfbb482b2011-03-08 22:12:11 +0000148 if (!AI.hasOneUse()) {
Chris Lattner59d95742010-01-04 07:59:07 +0000149 // New is the allocation instruction, pointer typed. AI is the original
150 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
151 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Sanjay Patel4b198802016-02-01 22:23:39 +0000152 replaceInstUsesWith(AI, NewCast);
Chris Lattner59d95742010-01-04 07:59:07 +0000153 }
Sanjay Patel4b198802016-02-01 22:23:39 +0000154 return replaceInstUsesWith(CI, New);
Chris Lattner59d95742010-01-04 07:59:07 +0000155}
156
Sanjay Patel2fbab9d82015-09-09 14:34:26 +0000157/// Given an expression that CanEvaluateTruncated or CanEvaluateSExtd returns
158/// true for, actually insert the code to evaluate the expression.
Craig Topper3529aa52013-01-24 05:22:40 +0000159Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
Chris Lattner92be2ad2010-01-04 07:54:59 +0000160 bool isSigned) {
Chris Lattner9242ae02010-01-08 19:28:47 +0000161 if (Constant *C = dyn_cast<Constant>(V)) {
162 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000163 // If we got a constantexpr back, try to simplify it with DL info.
Justin Bogner99798402016-08-05 01:06:44 +0000164 if (Constant *FoldedC = ConstantFoldConstant(C, DL, &TLI))
David Majnemerd536f232016-07-29 03:27:26 +0000165 C = FoldedC;
Chris Lattner9242ae02010-01-08 19:28:47 +0000166 return C;
167 }
Chris Lattner92be2ad2010-01-04 07:54:59 +0000168
169 // Otherwise, it must be an instruction.
170 Instruction *I = cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000171 Instruction *Res = nullptr;
Chris Lattner92be2ad2010-01-04 07:54:59 +0000172 unsigned Opc = I->getOpcode();
173 switch (Opc) {
174 case Instruction::Add:
175 case Instruction::Sub:
176 case Instruction::Mul:
177 case Instruction::And:
178 case Instruction::Or:
179 case Instruction::Xor:
180 case Instruction::AShr:
181 case Instruction::LShr:
182 case Instruction::Shl:
183 case Instruction::UDiv:
184 case Instruction::URem: {
185 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
186 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
187 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
188 break;
Craig Topper3529aa52013-01-24 05:22:40 +0000189 }
Chris Lattner92be2ad2010-01-04 07:54:59 +0000190 case Instruction::Trunc:
191 case Instruction::ZExt:
192 case Instruction::SExt:
193 // If the source type of the cast is the type we're trying for then we can
194 // just return the source. There's no need to insert it because it is not
195 // new.
196 if (I->getOperand(0)->getType() == Ty)
197 return I->getOperand(0);
Craig Topper3529aa52013-01-24 05:22:40 +0000198
Chris Lattner92be2ad2010-01-04 07:54:59 +0000199 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner39d2daa2010-01-10 20:25:54 +0000200 // This also handles the case of zext(trunc(x)) -> zext(x).
201 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
202 Opc == Instruction::SExt);
Chris Lattner92be2ad2010-01-04 07:54:59 +0000203 break;
204 case Instruction::Select: {
205 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
206 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
207 Res = SelectInst::Create(I->getOperand(0), True, False);
208 break;
209 }
210 case Instruction::PHI: {
211 PHINode *OPN = cast<PHINode>(I);
Jay Foad52131342011-03-30 11:28:46 +0000212 PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
Chris Lattner92be2ad2010-01-04 07:54:59 +0000213 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000214 Value *V =
215 EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
Chris Lattner92be2ad2010-01-04 07:54:59 +0000216 NPN->addIncoming(V, OPN->getIncomingBlock(i));
217 }
218 Res = NPN;
219 break;
220 }
Craig Topper3529aa52013-01-24 05:22:40 +0000221 default:
Chris Lattner92be2ad2010-01-04 07:54:59 +0000222 // TODO: Can handle more cases here.
223 llvm_unreachable("Unreachable!");
Chris Lattner92be2ad2010-01-04 07:54:59 +0000224 }
Craig Topper3529aa52013-01-24 05:22:40 +0000225
Chris Lattner92be2ad2010-01-04 07:54:59 +0000226 Res->takeName(I);
Eli Friedman35211c62011-05-27 00:19:40 +0000227 return InsertNewInstWith(Res, *I);
Chris Lattner92be2ad2010-01-04 07:54:59 +0000228}
Chris Lattner2b295a02010-01-04 07:53:58 +0000229
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000230Instruction::CastOps InstCombiner::isEliminableCastPair(const CastInst *CI1,
231 const CastInst *CI2) {
232 Type *SrcTy = CI1->getSrcTy();
233 Type *MidTy = CI1->getDestTy();
234 Type *DstTy = CI2->getDestTy();
Chris Lattner2b295a02010-01-04 07:53:58 +0000235
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000236 Instruction::CastOps firstOp = Instruction::CastOps(CI1->getOpcode());
237 Instruction::CastOps secondOp = Instruction::CastOps(CI2->getOpcode());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000238 Type *SrcIntPtrTy =
239 SrcTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(SrcTy) : nullptr;
240 Type *MidIntPtrTy =
241 MidTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(MidTy) : nullptr;
242 Type *DstIntPtrTy =
243 DstTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(DstTy) : nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +0000244 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Duncan Sandse2395dc2012-10-30 16:03:32 +0000245 DstTy, SrcIntPtrTy, MidIntPtrTy,
246 DstIntPtrTy);
Micah Villmow12d91272012-10-24 15:52:52 +0000247
Chris Lattner2b295a02010-01-04 07:53:58 +0000248 // We don't want to form an inttoptr or ptrtoint that converts to an integer
249 // type that differs from the pointer size.
Duncan Sandse2395dc2012-10-30 16:03:32 +0000250 if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
251 (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
Chris Lattner2b295a02010-01-04 07:53:58 +0000252 Res = 0;
Craig Topper3529aa52013-01-24 05:22:40 +0000253
Chris Lattner2b295a02010-01-04 07:53:58 +0000254 return Instruction::CastOps(Res);
255}
256
Chris Lattner2b295a02010-01-04 07:53:58 +0000257/// @brief Implement the transforms common to all CastInst visitors.
258Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
259 Value *Src = CI.getOperand(0);
260
261 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
262 // eliminate it now.
263 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Craig Topper3529aa52013-01-24 05:22:40 +0000264 if (Instruction::CastOps opc =
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000265 isEliminableCastPair(CSrc, &CI)) {
Chris Lattner2b295a02010-01-04 07:53:58 +0000266 // The first cast (CSrc) is eliminable so we need to fix up or replace
267 // the second cast (CI). CSrc will then have a good chance of being dead.
268 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
269 }
270 }
271
272 // If we are casting a select then fold the cast into the select
273 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
274 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
275 return NV;
276
277 // If we are casting a PHI then fold the cast into the PHI
278 if (isa<PHINode>(Src)) {
279 // We don't do this if this would create a PHI node with an illegal type if
280 // it is currently legal.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000281 if (!Src->getType()->isIntegerTy() || !CI.getType()->isIntegerTy() ||
Chris Lattner2b295a02010-01-04 07:53:58 +0000282 ShouldChangeType(CI.getType(), Src->getType()))
283 if (Instruction *NV = FoldOpIntoPhi(CI))
284 return NV;
285 }
Craig Topper3529aa52013-01-24 05:22:40 +0000286
Craig Topperf40110f2014-04-25 05:29:35 +0000287 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +0000288}
289
Sanjay Patel2fbab9d82015-09-09 14:34:26 +0000290/// Return true if we can evaluate the specified expression tree as type Ty
291/// instead of its larger type, and arrive with the same value.
292/// This is used by code that tries to eliminate truncates.
Chris Lattnerc3aca382010-01-10 00:58:42 +0000293///
294/// Ty will always be a type smaller than V. We should return true if trunc(V)
295/// can be computed by computing V in the smaller type. If V is an instruction,
296/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
297/// makes sense if x and y can be efficiently truncated.
298///
Chris Lattner172630a2010-01-11 02:43:35 +0000299/// This function works on both vectors and scalars.
300///
Sanjay Patele2834412015-09-09 14:54:29 +0000301static bool canEvaluateTruncated(Value *V, Type *Ty, InstCombiner &IC,
Hal Finkel60db0582014-09-07 18:57:58 +0000302 Instruction *CxtI) {
Chris Lattnerc3aca382010-01-10 00:58:42 +0000303 // We can always evaluate constants in another type.
304 if (isa<Constant>(V))
305 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000306
Chris Lattnerc3aca382010-01-10 00:58:42 +0000307 Instruction *I = dyn_cast<Instruction>(V);
308 if (!I) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000309
Chris Lattner229907c2011-07-18 04:54:35 +0000310 Type *OrigTy = V->getType();
Craig Topper3529aa52013-01-24 05:22:40 +0000311
Chris Lattnera6b13562010-01-11 22:45:25 +0000312 // If this is an extension from the dest type, we can eliminate it, even if it
313 // has multiple uses.
Craig Topper3529aa52013-01-24 05:22:40 +0000314 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
Chris Lattnerc3aca382010-01-10 00:58:42 +0000315 I->getOperand(0)->getType() == Ty)
316 return true;
317
318 // We can't extend or shrink something that has multiple uses: doing so would
319 // require duplicating the instruction in general, which isn't profitable.
320 if (!I->hasOneUse()) return false;
321
322 unsigned Opc = I->getOpcode();
323 switch (Opc) {
324 case Instruction::Add:
325 case Instruction::Sub:
326 case Instruction::Mul:
327 case Instruction::And:
328 case Instruction::Or:
329 case Instruction::Xor:
330 // These operators can all arbitrarily be extended or truncated.
Sanjay Patele2834412015-09-09 14:54:29 +0000331 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
332 canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000333
334 case Instruction::UDiv:
335 case Instruction::URem: {
336 // UDiv and URem can be truncated if all the truncated bits are zero.
337 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
338 uint32_t BitWidth = Ty->getScalarSizeInBits();
339 if (BitWidth < OrigBitWidth) {
340 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
Hal Finkel60db0582014-09-07 18:57:58 +0000341 if (IC.MaskedValueIsZero(I->getOperand(0), Mask, 0, CxtI) &&
342 IC.MaskedValueIsZero(I->getOperand(1), Mask, 0, CxtI)) {
Sanjay Patele2834412015-09-09 14:54:29 +0000343 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
344 canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000345 }
346 }
347 break;
348 }
349 case Instruction::Shl:
350 // If we are truncating the result of this SHL, and if it's a shift of a
351 // constant amount, we can always perform a SHL in a smaller type.
352 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
353 uint32_t BitWidth = Ty->getScalarSizeInBits();
354 if (CI->getLimitedValue(BitWidth) < BitWidth)
Sanjay Patele2834412015-09-09 14:54:29 +0000355 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000356 }
357 break;
358 case Instruction::LShr:
359 // If this is a truncate of a logical shr, we can truncate it to a smaller
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000360 // lshr iff we know that the bits we would otherwise be shifting in are
Chris Lattnerc3aca382010-01-10 00:58:42 +0000361 // already zeros.
362 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
363 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
364 uint32_t BitWidth = Ty->getScalarSizeInBits();
Hal Finkel60db0582014-09-07 18:57:58 +0000365 if (IC.MaskedValueIsZero(I->getOperand(0),
366 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth), 0, CxtI) &&
Chris Lattnerc3aca382010-01-10 00:58:42 +0000367 CI->getLimitedValue(BitWidth) < BitWidth) {
Sanjay Patele2834412015-09-09 14:54:29 +0000368 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000369 }
370 }
371 break;
372 case Instruction::Trunc:
373 // trunc(trunc(x)) -> trunc(x)
374 return true;
Chris Lattner73984342010-08-27 20:32:06 +0000375 case Instruction::ZExt:
376 case Instruction::SExt:
377 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
378 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
379 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000380 case Instruction::Select: {
381 SelectInst *SI = cast<SelectInst>(I);
Sanjay Patele2834412015-09-09 14:54:29 +0000382 return canEvaluateTruncated(SI->getTrueValue(), Ty, IC, CxtI) &&
383 canEvaluateTruncated(SI->getFalseValue(), Ty, IC, CxtI);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000384 }
385 case Instruction::PHI: {
386 // We can change a phi if we can change all operands. Note that we never
387 // get into trouble with cyclic PHIs here because we only consider
388 // instructions with a single use.
389 PHINode *PN = cast<PHINode>(I);
Pete Cooper833f34d2015-05-12 20:05:31 +0000390 for (Value *IncValue : PN->incoming_values())
Sanjay Patele2834412015-09-09 14:54:29 +0000391 if (!canEvaluateTruncated(IncValue, Ty, IC, CxtI))
Chris Lattnerc3aca382010-01-10 00:58:42 +0000392 return false;
393 return true;
394 }
395 default:
396 // TODO: Can handle more cases here.
397 break;
398 }
Craig Topper3529aa52013-01-24 05:22:40 +0000399
Chris Lattnerc3aca382010-01-10 00:58:42 +0000400 return false;
401}
402
Sanjay Patelf727e382015-12-14 16:16:54 +0000403/// Given a vector that is bitcast to an integer, optionally logically
404/// right-shifted, and truncated, convert it to an extractelement.
405/// Example (big endian):
406/// trunc (lshr (bitcast <4 x i32> %X to i128), 32) to i32
407/// --->
408/// extractelement <4 x i32> %X, 1
409static Instruction *foldVecTruncToExtElt(TruncInst &Trunc, InstCombiner &IC,
410 const DataLayout &DL) {
411 Value *TruncOp = Trunc.getOperand(0);
412 Type *DestType = Trunc.getType();
413 if (!TruncOp->hasOneUse() || !isa<IntegerType>(DestType))
414 return nullptr;
415
416 Value *VecInput = nullptr;
417 ConstantInt *ShiftVal = nullptr;
418 if (!match(TruncOp, m_CombineOr(m_BitCast(m_Value(VecInput)),
419 m_LShr(m_BitCast(m_Value(VecInput)),
420 m_ConstantInt(ShiftVal)))) ||
421 !isa<VectorType>(VecInput->getType()))
422 return nullptr;
423
424 VectorType *VecType = cast<VectorType>(VecInput->getType());
425 unsigned VecWidth = VecType->getPrimitiveSizeInBits();
426 unsigned DestWidth = DestType->getPrimitiveSizeInBits();
427 unsigned ShiftAmount = ShiftVal ? ShiftVal->getZExtValue() : 0;
428
429 if ((VecWidth % DestWidth != 0) || (ShiftAmount % DestWidth != 0))
430 return nullptr;
431
432 // If the element type of the vector doesn't match the result type,
433 // bitcast it to a vector type that we can extract from.
434 unsigned NumVecElts = VecWidth / DestWidth;
435 if (VecType->getElementType() != DestType) {
436 VecType = VectorType::get(DestType, NumVecElts);
437 VecInput = IC.Builder->CreateBitCast(VecInput, VecType, "bc");
438 }
439
440 unsigned Elt = ShiftAmount / DestWidth;
441 if (DL.isBigEndian())
442 Elt = NumVecElts - 1 - Elt;
443
444 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
445}
446
Chris Lattnerc3aca382010-01-10 00:58:42 +0000447Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner883550a2010-01-10 01:00:46 +0000448 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattnerc3aca382010-01-10 00:58:42 +0000449 return Result;
Craig Topper3529aa52013-01-24 05:22:40 +0000450
James Molloy2b21a7c2015-05-20 18:41:25 +0000451 // Test if the trunc is the user of a select which is part of a
452 // minimum or maximum operation. If so, don't do any more simplification.
453 // Even simplifying demanded bits can break the canonical form of a
454 // min/max.
455 Value *LHS, *RHS;
456 if (SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0)))
James Molloy134bec22015-08-11 09:12:57 +0000457 if (matchSelectPattern(SI, LHS, RHS).Flavor != SPF_UNKNOWN)
James Molloy2b21a7c2015-05-20 18:41:25 +0000458 return nullptr;
459
Craig Topper3529aa52013-01-24 05:22:40 +0000460 // See if we can simplify any instructions used by the input whose sole
Chris Lattner883550a2010-01-10 01:00:46 +0000461 // purpose is to compute bits we don't care about.
462 if (SimplifyDemandedInstructionBits(CI))
463 return &CI;
Craig Topper3529aa52013-01-24 05:22:40 +0000464
Chris Lattnerc3aca382010-01-10 00:58:42 +0000465 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000466 Type *DestTy = CI.getType(), *SrcTy = Src->getType();
Craig Topper3529aa52013-01-24 05:22:40 +0000467
Chris Lattnerc3aca382010-01-10 00:58:42 +0000468 // Attempt to truncate the entire input expression tree to the destination
469 // type. Only do this if the dest type is a simple type, don't convert the
Chris Lattner2b295a02010-01-04 07:53:58 +0000470 // expression tree to something weird like i93 unless the source is also
471 // strange.
Duncan Sands19d0b472010-02-16 11:11:14 +0000472 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Sanjay Patele2834412015-09-09 14:54:29 +0000473 canEvaluateTruncated(Src, DestTy, *this, &CI)) {
Craig Topper3529aa52013-01-24 05:22:40 +0000474
Chris Lattner2b295a02010-01-04 07:53:58 +0000475 // If this cast is a truncate, evaluting in a different type always
Chris Lattner8600dd32010-01-05 23:00:30 +0000476 // eliminates the cast, so it is always a win.
Chris Lattner3057c372010-01-07 23:41:00 +0000477 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
Dan Gohmana4abd032010-05-25 21:50:35 +0000478 " to avoid cast: " << CI << '\n');
Chris Lattner3057c372010-01-07 23:41:00 +0000479 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
480 assert(Res->getType() == DestTy);
Sanjay Patel4b198802016-02-01 22:23:39 +0000481 return replaceInstUsesWith(CI, Res);
Chris Lattner3057c372010-01-07 23:41:00 +0000482 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000483
Chris Lattnera93c63c2010-01-05 22:21:18 +0000484 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
485 if (DestTy->getScalarSizeInBits() == 1) {
Sanjay Patelf09d1bf2015-11-17 18:37:23 +0000486 Constant *One = ConstantInt::get(SrcTy, 1);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000487 Src = Builder->CreateAnd(Src, One);
Chris Lattner2b295a02010-01-04 07:53:58 +0000488 Value *Zero = Constant::getNullValue(Src->getType());
489 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
490 }
Craig Topper3529aa52013-01-24 05:22:40 +0000491
Chris Lattner90cd7462010-08-27 18:31:05 +0000492 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
Craig Topperf40110f2014-04-25 05:29:35 +0000493 Value *A = nullptr; ConstantInt *Cst = nullptr;
Chris Lattner9c10d582011-01-15 06:32:33 +0000494 if (Src->hasOneUse() &&
495 match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
Chris Lattner90cd7462010-08-27 18:31:05 +0000496 // We have three types to worry about here, the type of A, the source of
497 // the truncate (MidSize), and the destination of the truncate. We know that
498 // ASize < MidSize and MidSize > ResultSize, but don't know the relation
499 // between ASize and ResultSize.
500 unsigned ASize = A->getType()->getPrimitiveSizeInBits();
Craig Topper3529aa52013-01-24 05:22:40 +0000501
Chris Lattner90cd7462010-08-27 18:31:05 +0000502 // If the shift amount is larger than the size of A, then the result is
503 // known to be zero because all the input bits got shifted out.
504 if (Cst->getZExtValue() >= ASize)
Sanjay Patel4b198802016-02-01 22:23:39 +0000505 return replaceInstUsesWith(CI, Constant::getNullValue(DestTy));
Chris Lattner90cd7462010-08-27 18:31:05 +0000506
507 // Since we're doing an lshr and a zero extend, and know that the shift
508 // amount is smaller than ASize, it is always safe to do the shift in A's
509 // type, then zero extend or truncate to the result.
510 Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
511 Shift->takeName(Src);
Sanjay Patelf09d1bf2015-11-17 18:37:23 +0000512 return CastInst::CreateIntegerCast(Shift, DestTy, false);
Chris Lattner90cd7462010-08-27 18:31:05 +0000513 }
Craig Topper3529aa52013-01-24 05:22:40 +0000514
Jakub Kuderski58ea4ee2015-09-10 11:31:20 +0000515 // Transform trunc(lshr (sext A), Cst) to ashr A, Cst to eliminate type
516 // conversion.
517 // It works because bits coming from sign extension have the same value as
Sanjay Patel1de794a2015-11-17 18:46:56 +0000518 // the sign bit of the original value; performing ashr instead of lshr
Jakub Kuderski58ea4ee2015-09-10 11:31:20 +0000519 // generates bits of the same value as the sign bit.
520 if (Src->hasOneUse() &&
521 match(Src, m_LShr(m_SExt(m_Value(A)), m_ConstantInt(Cst))) &&
522 cast<Instruction>(Src)->getOperand(0)->hasOneUse()) {
523 const unsigned ASize = A->getType()->getPrimitiveSizeInBits();
524 // This optimization can be only performed when zero bits generated by
525 // the original lshr aren't pulled into the value after truncation, so we
Sanjay Patel1de794a2015-11-17 18:46:56 +0000526 // can only shift by values smaller than the size of destination type (in
Jakub Kuderski58ea4ee2015-09-10 11:31:20 +0000527 // bits).
528 if (Cst->getValue().ult(ASize)) {
529 Value *Shift = Builder->CreateAShr(A, Cst->getZExtValue());
530 Shift->takeName(Src);
531 return CastInst::CreateIntegerCast(Shift, CI.getType(), true);
532 }
533 }
534
Chris Lattner9c10d582011-01-15 06:32:33 +0000535 // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
536 // type isn't non-native.
Sanjay Patelf09d1bf2015-11-17 18:37:23 +0000537 if (Src->hasOneUse() && isa<IntegerType>(SrcTy) &&
Matt Arsenault8fd59782016-06-17 23:36:38 +0000538 ShouldChangeType(SrcTy, DestTy) &&
539 match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
540 Value *NewTrunc = Builder->CreateTrunc(A, DestTy, A->getName() + ".tr");
541 return BinaryOperator::CreateAnd(NewTrunc,
542 ConstantExpr::getTrunc(Cst, DestTy));
Chris Lattner9c10d582011-01-15 06:32:33 +0000543 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000544
Sanjay Patelf727e382015-12-14 16:16:54 +0000545 if (Instruction *I = foldVecTruncToExtElt(CI, *this, DL))
546 return I;
547
Craig Topperf40110f2014-04-25 05:29:35 +0000548 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +0000549}
550
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000551Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, ZExtInst &CI,
552 bool DoTransform) {
Chris Lattner2b295a02010-01-04 07:53:58 +0000553 // If we are just checking for a icmp eq of a single bit and zext'ing it
554 // to an integer, then shift the bit to the appropriate place and then
555 // cast to integer to avoid the comparison.
556 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
557 const APInt &Op1CV = Op1C->getValue();
Craig Topper3529aa52013-01-24 05:22:40 +0000558
Chris Lattner2b295a02010-01-04 07:53:58 +0000559 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
560 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
561 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Sanjay Patel16395dd2015-12-30 18:31:30 +0000562 (ICI->getPredicate() == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000563 if (!DoTransform) return ICI;
Chris Lattner2b295a02010-01-04 07:53:58 +0000564
565 Value *In = ICI->getOperand(0);
566 Value *Sh = ConstantInt::get(In->getType(),
Sanjay Patel16395dd2015-12-30 18:31:30 +0000567 In->getType()->getScalarSizeInBits() - 1);
568 In = Builder->CreateLShr(In, Sh, In->getName() + ".lobit");
Chris Lattner2b295a02010-01-04 07:53:58 +0000569 if (In->getType() != CI.getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000570 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner2b295a02010-01-04 07:53:58 +0000571
572 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
573 Constant *One = ConstantInt::get(In->getType(), 1);
Sanjay Patel16395dd2015-12-30 18:31:30 +0000574 In = Builder->CreateXor(In, One, In->getName() + ".not");
Chris Lattner2b295a02010-01-04 07:53:58 +0000575 }
576
Sanjay Patel4b198802016-02-01 22:23:39 +0000577 return replaceInstUsesWith(CI, In);
Chris Lattner2b295a02010-01-04 07:53:58 +0000578 }
Chad Rosier385d9f62011-11-30 01:59:59 +0000579
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000580 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
581 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
582 // zext (X == 1) to i32 --> X iff X has only the low bit set.
583 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
584 // zext (X != 0) to i32 --> X iff X has only the low bit set.
585 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
586 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
587 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Craig Topper3529aa52013-01-24 05:22:40 +0000588 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
Chris Lattner2b295a02010-01-04 07:53:58 +0000589 // This only works for EQ and NE
590 ICI->isEquality()) {
591 // If Op1C some other power of two, convert:
592 uint32_t BitWidth = Op1C->getType()->getBitWidth();
593 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +0000594 computeKnownBits(ICI->getOperand(0), KnownZero, KnownOne, 0, &CI);
Craig Topper3529aa52013-01-24 05:22:40 +0000595
Chris Lattner2b295a02010-01-04 07:53:58 +0000596 APInt KnownZeroMask(~KnownZero);
597 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000598 if (!DoTransform) return ICI;
Chris Lattner2b295a02010-01-04 07:53:58 +0000599
600 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
601 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
602 // (X&4) == 2 --> false
603 // (X&4) != 2 --> true
604 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
605 isNE);
606 Res = ConstantExpr::getZExt(Res, CI.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +0000607 return replaceInstUsesWith(CI, Res);
Chris Lattner2b295a02010-01-04 07:53:58 +0000608 }
Craig Topper3529aa52013-01-24 05:22:40 +0000609
Sanjay Patel16395dd2015-12-30 18:31:30 +0000610 uint32_t ShAmt = KnownZeroMask.logBase2();
Chris Lattner2b295a02010-01-04 07:53:58 +0000611 Value *In = ICI->getOperand(0);
Sanjay Patel16395dd2015-12-30 18:31:30 +0000612 if (ShAmt) {
Chris Lattner2b295a02010-01-04 07:53:58 +0000613 // Perform a logical shr by shiftamt.
614 // Insert the shift to put the result in the low bit.
Sanjay Patel16395dd2015-12-30 18:31:30 +0000615 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(), ShAmt),
616 In->getName() + ".lobit");
Chris Lattner2b295a02010-01-04 07:53:58 +0000617 }
Craig Topper3529aa52013-01-24 05:22:40 +0000618
Chris Lattner2b295a02010-01-04 07:53:58 +0000619 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
620 Constant *One = ConstantInt::get(In->getType(), 1);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000621 In = Builder->CreateXor(In, One);
Chris Lattner2b295a02010-01-04 07:53:58 +0000622 }
Craig Topper3529aa52013-01-24 05:22:40 +0000623
Chris Lattner2b295a02010-01-04 07:53:58 +0000624 if (CI.getType() == In->getType())
Sanjay Patel4b198802016-02-01 22:23:39 +0000625 return replaceInstUsesWith(CI, In);
Tobias Grosser8757e382016-08-03 19:30:35 +0000626
627 Value *IntCast = Builder->CreateIntCast(In, CI.getType(), false);
628 return replaceInstUsesWith(CI, IntCast);
Chris Lattner2b295a02010-01-04 07:53:58 +0000629 }
630 }
631 }
632
633 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
634 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
635 // may lead to additional simplifications.
636 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000637 if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
Chris Lattner2b295a02010-01-04 07:53:58 +0000638 uint32_t BitWidth = ITy->getBitWidth();
639 Value *LHS = ICI->getOperand(0);
640 Value *RHS = ICI->getOperand(1);
641
642 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
643 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +0000644 computeKnownBits(LHS, KnownZeroLHS, KnownOneLHS, 0, &CI);
645 computeKnownBits(RHS, KnownZeroRHS, KnownOneRHS, 0, &CI);
Chris Lattner2b295a02010-01-04 07:53:58 +0000646
647 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
648 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
649 APInt UnknownBit = ~KnownBits;
650 if (UnknownBit.countPopulation() == 1) {
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000651 if (!DoTransform) return ICI;
Chris Lattner2b295a02010-01-04 07:53:58 +0000652
653 Value *Result = Builder->CreateXor(LHS, RHS);
654
655 // Mask off any bits that are set and won't be shifted away.
656 if (KnownOneLHS.uge(UnknownBit))
657 Result = Builder->CreateAnd(Result,
658 ConstantInt::get(ITy, UnknownBit));
659
660 // Shift the bit we're testing down to the lsb.
661 Result = Builder->CreateLShr(
662 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
663
664 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
665 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
666 Result->takeName(ICI);
Sanjay Patel4b198802016-02-01 22:23:39 +0000667 return replaceInstUsesWith(CI, Result);
Chris Lattner2b295a02010-01-04 07:53:58 +0000668 }
669 }
670 }
671 }
672
Craig Topperf40110f2014-04-25 05:29:35 +0000673 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +0000674}
675
Sanjay Patel2fbab9d82015-09-09 14:34:26 +0000676/// Determine if the specified value can be computed in the specified wider type
677/// and produce the same low bits. If not, return false.
Chris Lattner172630a2010-01-11 02:43:35 +0000678///
Chris Lattner12bd8992010-01-11 03:32:00 +0000679/// If this function returns true, it can also return a non-zero number of bits
680/// (in BitsToClear) which indicates that the value it computes is correct for
681/// the zero extend, but that the additional BitsToClear bits need to be zero'd
682/// out. For example, to promote something like:
683///
684/// %B = trunc i64 %A to i32
685/// %C = lshr i32 %B, 8
686/// %E = zext i32 %C to i64
687///
688/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
689/// set to 8 to indicate that the promoted value needs to have bits 24-31
690/// cleared in addition to bits 32-63. Since an 'and' will be generated to
691/// clear the top bits anyway, doing this has no extra cost.
692///
Chris Lattner172630a2010-01-11 02:43:35 +0000693/// This function works on both vectors and scalars.
Sanjay Patele2834412015-09-09 14:54:29 +0000694static bool canEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear,
Hal Finkel60db0582014-09-07 18:57:58 +0000695 InstCombiner &IC, Instruction *CxtI) {
Chris Lattner12bd8992010-01-11 03:32:00 +0000696 BitsToClear = 0;
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000697 if (isa<Constant>(V))
698 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000699
Chris Lattnerc3aca382010-01-10 00:58:42 +0000700 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000701 if (!I) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000702
Chris Lattnerc3aca382010-01-10 00:58:42 +0000703 // If the input is a truncate from the destination type, we can trivially
Jakob Stoklund Olesenc5c4e962012-06-22 16:36:43 +0000704 // eliminate it.
705 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000706 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000707
Chris Lattnerc3aca382010-01-10 00:58:42 +0000708 // We can't extend or shrink something that has multiple uses: doing so would
709 // require duplicating the instruction in general, which isn't profitable.
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000710 if (!I->hasOneUse()) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000711
Chris Lattner12bd8992010-01-11 03:32:00 +0000712 unsigned Opc = I->getOpcode(), Tmp;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000713 switch (Opc) {
Chris Lattner39d2daa2010-01-10 20:25:54 +0000714 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
715 case Instruction::SExt: // zext(sext(x)) -> sext(x).
716 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
717 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000718 case Instruction::And:
Chris Lattnerc3aca382010-01-10 00:58:42 +0000719 case Instruction::Or:
720 case Instruction::Xor:
Chris Lattnerc3aca382010-01-10 00:58:42 +0000721 case Instruction::Add:
722 case Instruction::Sub:
723 case Instruction::Mul:
Sanjay Patele2834412015-09-09 14:54:29 +0000724 if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI) ||
725 !canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI))
Chris Lattner12bd8992010-01-11 03:32:00 +0000726 return false;
727 // These can all be promoted if neither operand has 'bits to clear'.
728 if (BitsToClear == 0 && Tmp == 0)
729 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000730
Chris Lattner0a854202010-01-11 04:05:13 +0000731 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
732 // other side, BitsToClear is ok.
733 if (Tmp == 0 &&
734 (Opc == Instruction::And || Opc == Instruction::Or ||
735 Opc == Instruction::Xor)) {
736 // We use MaskedValueIsZero here for generality, but the case we care
737 // about the most is constant RHS.
738 unsigned VSize = V->getType()->getScalarSizeInBits();
Hal Finkel60db0582014-09-07 18:57:58 +0000739 if (IC.MaskedValueIsZero(I->getOperand(1),
740 APInt::getHighBitsSet(VSize, BitsToClear),
741 0, CxtI))
Chris Lattner0a854202010-01-11 04:05:13 +0000742 return true;
743 }
Craig Topper3529aa52013-01-24 05:22:40 +0000744
Chris Lattner0a854202010-01-11 04:05:13 +0000745 // Otherwise, we don't know how to analyze this BitsToClear case yet.
Chris Lattner12bd8992010-01-11 03:32:00 +0000746 return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000747
Benjamin Kramer14e915f2013-05-10 16:26:37 +0000748 case Instruction::Shl:
749 // We can promote shl(x, cst) if we can promote x. Since shl overwrites the
750 // upper bits we can reduce BitsToClear by the shift amount.
751 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
Sanjay Patele2834412015-09-09 14:54:29 +0000752 if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
Benjamin Kramer14e915f2013-05-10 16:26:37 +0000753 return false;
754 uint64_t ShiftAmt = Amt->getZExtValue();
755 BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
756 return true;
757 }
758 return false;
Chris Lattner12bd8992010-01-11 03:32:00 +0000759 case Instruction::LShr:
760 // We can promote lshr(x, cst) if we can promote x. This requires the
761 // ultimate 'and' to clear out the high zero bits we're clearing out though.
762 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
Sanjay Patele2834412015-09-09 14:54:29 +0000763 if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
Chris Lattner12bd8992010-01-11 03:32:00 +0000764 return false;
765 BitsToClear += Amt->getZExtValue();
766 if (BitsToClear > V->getType()->getScalarSizeInBits())
767 BitsToClear = V->getType()->getScalarSizeInBits();
768 return true;
769 }
770 // Cannot promote variable LSHR.
771 return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000772 case Instruction::Select:
Sanjay Patele2834412015-09-09 14:54:29 +0000773 if (!canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI) ||
774 !canEvaluateZExtd(I->getOperand(2), Ty, BitsToClear, IC, CxtI) ||
Chris Lattner0a854202010-01-11 04:05:13 +0000775 // TODO: If important, we could handle the case when the BitsToClear are
776 // known zero in the disagreeing side.
Chris Lattner12bd8992010-01-11 03:32:00 +0000777 Tmp != BitsToClear)
778 return false;
779 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000780
Chris Lattnerc3aca382010-01-10 00:58:42 +0000781 case Instruction::PHI: {
782 // We can change a phi if we can change all operands. Note that we never
783 // get into trouble with cyclic PHIs here because we only consider
784 // instructions with a single use.
785 PHINode *PN = cast<PHINode>(I);
Sanjay Patele2834412015-09-09 14:54:29 +0000786 if (!canEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear, IC, CxtI))
Chris Lattner12bd8992010-01-11 03:32:00 +0000787 return false;
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000788 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
Sanjay Patele2834412015-09-09 14:54:29 +0000789 if (!canEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) ||
Chris Lattner0a854202010-01-11 04:05:13 +0000790 // TODO: If important, we could handle the case when the BitsToClear
791 // are known zero in the disagreeing input.
Chris Lattner12bd8992010-01-11 03:32:00 +0000792 Tmp != BitsToClear)
793 return false;
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000794 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000795 }
796 default:
797 // TODO: Can handle more cases here.
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000798 return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000799 }
800}
801
Chris Lattner2b295a02010-01-04 07:53:58 +0000802Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Nick Lewycky80ea0032013-01-14 20:56:10 +0000803 // If this zero extend is only used by a truncate, let the truncate be
Chris Lattner49d2c972010-01-10 02:39:31 +0000804 // eliminated before we try to optimize this zext.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000805 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
Craig Topperf40110f2014-04-25 05:29:35 +0000806 return nullptr;
Craig Topper3529aa52013-01-24 05:22:40 +0000807
Chris Lattner2b295a02010-01-04 07:53:58 +0000808 // If one of the common conversion will work, do it.
Chris Lattner883550a2010-01-10 01:00:46 +0000809 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner2b295a02010-01-04 07:53:58 +0000810 return Result;
811
Craig Topper3529aa52013-01-24 05:22:40 +0000812 // See if we can simplify any instructions used by the input whose sole
Chris Lattner883550a2010-01-10 01:00:46 +0000813 // purpose is to compute bits we don't care about.
814 if (SimplifyDemandedInstructionBits(CI))
815 return &CI;
Craig Topper3529aa52013-01-24 05:22:40 +0000816
Chris Lattner883550a2010-01-10 01:00:46 +0000817 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000818 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Craig Topper3529aa52013-01-24 05:22:40 +0000819
Chris Lattnerc3aca382010-01-10 00:58:42 +0000820 // Attempt to extend the entire input expression tree to the destination
821 // type. Only do this if the dest type is a simple type, don't convert the
822 // expression tree to something weird like i93 unless the source is also
823 // strange.
Chris Lattner12bd8992010-01-11 03:32:00 +0000824 unsigned BitsToClear;
Duncan Sands19d0b472010-02-16 11:11:14 +0000825 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Sanjay Patele2834412015-09-09 14:54:29 +0000826 canEvaluateZExtd(Src, DestTy, BitsToClear, *this, &CI)) {
Chris Lattner12bd8992010-01-11 03:32:00 +0000827 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
828 "Unreasonable BitsToClear");
Craig Topper3529aa52013-01-24 05:22:40 +0000829
Chris Lattner49d2c972010-01-10 02:39:31 +0000830 // Okay, we can transform this! Insert the new expression now.
831 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
Weiming Zhao24fbef52015-12-17 19:53:41 +0000832 " to avoid zero extend: " << CI << '\n');
Chris Lattner49d2c972010-01-10 02:39:31 +0000833 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
834 assert(Res->getType() == DestTy);
Craig Topper3529aa52013-01-24 05:22:40 +0000835
Chris Lattner12bd8992010-01-11 03:32:00 +0000836 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
837 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Craig Topper3529aa52013-01-24 05:22:40 +0000838
Chris Lattner49d2c972010-01-10 02:39:31 +0000839 // If the high bits are already filled with zeros, just replace this
840 // cast with the result.
Hal Finkel60db0582014-09-07 18:57:58 +0000841 if (MaskedValueIsZero(Res,
842 APInt::getHighBitsSet(DestBitSize,
843 DestBitSize-SrcBitsKept),
844 0, &CI))
Sanjay Patel4b198802016-02-01 22:23:39 +0000845 return replaceInstUsesWith(CI, Res);
Craig Topper3529aa52013-01-24 05:22:40 +0000846
Chris Lattner49d2c972010-01-10 02:39:31 +0000847 // We need to emit an AND to clear the high bits.
Chris Lattner39d2daa2010-01-10 20:25:54 +0000848 Constant *C = ConstantInt::get(Res->getType(),
Chris Lattner12bd8992010-01-11 03:32:00 +0000849 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
Chris Lattner49d2c972010-01-10 02:39:31 +0000850 return BinaryOperator::CreateAnd(Res, C);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000851 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000852
853 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
854 // types and if the sizes are just right we can convert this into a logical
855 // 'and' which will be much cheaper than the pair of casts.
856 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
Chris Lattnerd8509422010-01-10 07:08:30 +0000857 // TODO: Subsume this into EvaluateInDifferentType.
Craig Topper3529aa52013-01-24 05:22:40 +0000858
Chris Lattner2b295a02010-01-04 07:53:58 +0000859 // Get the sizes of the types involved. We know that the intermediate type
860 // will be smaller than A or C, but don't know the relation between A and C.
861 Value *A = CSrc->getOperand(0);
862 unsigned SrcSize = A->getType()->getScalarSizeInBits();
863 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
864 unsigned DstSize = CI.getType()->getScalarSizeInBits();
865 // If we're actually extending zero bits, then if
866 // SrcSize < DstSize: zext(a & mask)
867 // SrcSize == DstSize: a & mask
868 // SrcSize > DstSize: trunc(a) & mask
869 if (SrcSize < DstSize) {
870 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
871 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
872 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
873 return new ZExtInst(And, CI.getType());
874 }
Craig Topper3529aa52013-01-24 05:22:40 +0000875
Chris Lattner2b295a02010-01-04 07:53:58 +0000876 if (SrcSize == DstSize) {
877 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
878 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
879 AndValue));
880 }
881 if (SrcSize > DstSize) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000882 Value *Trunc = Builder->CreateTrunc(A, CI.getType());
Chris Lattner2b295a02010-01-04 07:53:58 +0000883 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Craig Topper3529aa52013-01-24 05:22:40 +0000884 return BinaryOperator::CreateAnd(Trunc,
Chris Lattner2b295a02010-01-04 07:53:58 +0000885 ConstantInt::get(Trunc->getType(),
Chris Lattnerd8509422010-01-10 07:08:30 +0000886 AndValue));
Chris Lattner2b295a02010-01-04 07:53:58 +0000887 }
888 }
889
890 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
891 return transformZExtICmp(ICI, CI);
892
893 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
894 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
Tobias Grosser8757e382016-08-03 19:30:35 +0000895 // zext (or icmp, icmp) -> or (zext icmp), (zext icmp) if at least one
896 // of the (zext icmp) can be eliminated. If so, immediately perform the
897 // according elimination.
Chris Lattner2b295a02010-01-04 07:53:58 +0000898 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
899 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
900 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
901 (transformZExtICmp(LHS, CI, false) ||
902 transformZExtICmp(RHS, CI, false))) {
Tobias Grosser8757e382016-08-03 19:30:35 +0000903 // zext (or icmp, icmp) -> or (zext icmp), (zext icmp)
Chris Lattner2b295a02010-01-04 07:53:58 +0000904 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
905 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Tobias Grosser8757e382016-08-03 19:30:35 +0000906 BinaryOperator *Or = BinaryOperator::Create(Instruction::Or, LCast, RCast);
907
908 // Perform the elimination.
909 if (auto *LZExt = dyn_cast<ZExtInst>(LCast))
910 transformZExtICmp(LHS, *LZExt);
911 if (auto *RZExt = dyn_cast<ZExtInst>(RCast))
912 transformZExtICmp(RHS, *RZExt);
913
914 return Or;
Chris Lattner2b295a02010-01-04 07:53:58 +0000915 }
916 }
917
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000918 // zext(trunc(X) & C) -> (X & zext(C)).
919 Constant *C;
920 Value *X;
921 if (SrcI &&
922 match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) &&
923 X->getType() == CI.getType())
924 return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType()));
Chris Lattner2b295a02010-01-04 07:53:58 +0000925
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000926 // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)).
927 Value *And;
928 if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) &&
929 match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) &&
930 X->getType() == CI.getType()) {
931 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
932 return BinaryOperator::CreateXor(Builder->CreateAnd(X, ZC), ZC);
933 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000934
Craig Topperf40110f2014-04-25 05:29:35 +0000935 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +0000936}
937
Sanjay Patel2fbab9d82015-09-09 14:34:26 +0000938/// Transform (sext icmp) to bitwise / integer operations to eliminate the icmp.
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000939Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
940 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
941 ICmpInst::Predicate Pred = ICI->getPredicate();
942
David Majnemerc8bdd232014-10-27 05:47:49 +0000943 // Don't bother if Op1 isn't of vector or integer type.
944 if (!Op1->getType()->isIntOrIntVectorTy())
945 return nullptr;
946
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000947 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Benjamin Kramer8b94c292011-04-01 22:29:18 +0000948 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative
949 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000950 if ((Pred == ICmpInst::ICMP_SLT && Op1C->isNullValue()) ||
Sanjay Patel5e4c46d2016-03-02 01:04:09 +0000951 (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000952
953 Value *Sh = ConstantInt::get(Op0->getType(),
Sanjay Patel5e4c46d2016-03-02 01:04:09 +0000954 Op0->getType()->getScalarSizeInBits()-1);
955 Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000956 if (In->getType() != CI.getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000957 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000958
Sanjay Patel5e4c46d2016-03-02 01:04:09 +0000959 if (Pred == ICmpInst::ICMP_SGT)
960 In = Builder->CreateNot(In, In->getName()+".not");
Sanjay Patel4b198802016-02-01 22:23:39 +0000961 return replaceInstUsesWith(CI, In);
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000962 }
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000963 }
Benjamin Kramerd1217652011-04-01 20:09:10 +0000964
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000965 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Benjamin Kramerd1217652011-04-01 20:09:10 +0000966 // If we know that only one bit of the LHS of the icmp can be set and we
967 // have an equality comparison with zero or a power of 2, we can transform
968 // the icmp and sext into bitwise/integer operations.
Benjamin Kramer5cad4532011-04-01 22:22:11 +0000969 if (ICI->hasOneUse() &&
970 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
Benjamin Kramerd1217652011-04-01 20:09:10 +0000971 unsigned BitWidth = Op1C->getType()->getBitWidth();
972 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +0000973 computeKnownBits(Op0, KnownZero, KnownOne, 0, &CI);
Benjamin Kramerd1217652011-04-01 20:09:10 +0000974
Benjamin Kramerac2d5652011-04-01 20:15:16 +0000975 APInt KnownZeroMask(~KnownZero);
976 if (KnownZeroMask.isPowerOf2()) {
Benjamin Kramerd1217652011-04-01 20:09:10 +0000977 Value *In = ICI->getOperand(0);
978
Benjamin Kramer50a281a2011-04-02 18:50:58 +0000979 // If the icmp tests for a known zero bit we can constant fold it.
980 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
981 Value *V = Pred == ICmpInst::ICMP_NE ?
982 ConstantInt::getAllOnesValue(CI.getType()) :
983 ConstantInt::getNullValue(CI.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +0000984 return replaceInstUsesWith(CI, V);
Benjamin Kramer50a281a2011-04-02 18:50:58 +0000985 }
Benjamin Kramer5cad4532011-04-01 22:22:11 +0000986
Benjamin Kramerd1217652011-04-01 20:09:10 +0000987 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
988 // sext ((x & 2^n) == 0) -> (x >> n) - 1
989 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
990 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
991 // Perform a right shift to place the desired bit in the LSB.
992 if (ShiftAmt)
993 In = Builder->CreateLShr(In,
994 ConstantInt::get(In->getType(), ShiftAmt));
995
996 // At this point "In" is either 1 or 0. Subtract 1 to turn
997 // {1, 0} -> {0, -1}.
998 In = Builder->CreateAdd(In,
999 ConstantInt::getAllOnesValue(In->getType()),
1000 "sext");
1001 } else {
1002 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramer5cad4532011-04-01 22:22:11 +00001003 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramerd1217652011-04-01 20:09:10 +00001004 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
1005 // Perform a left shift to place the desired bit in the MSB.
1006 if (ShiftAmt)
1007 In = Builder->CreateShl(In,
1008 ConstantInt::get(In->getType(), ShiftAmt));
1009
1010 // Distribute the bit over the whole bit width.
1011 In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
1012 BitWidth - 1), "sext");
1013 }
1014
1015 if (CI.getType() == In->getType())
Sanjay Patel4b198802016-02-01 22:23:39 +00001016 return replaceInstUsesWith(CI, In);
Benjamin Kramerd1217652011-04-01 20:09:10 +00001017 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
1018 }
1019 }
Benjamin Kramer398b8c52011-04-01 20:09:03 +00001020 }
1021
Craig Topperf40110f2014-04-25 05:29:35 +00001022 return nullptr;
Benjamin Kramer398b8c52011-04-01 20:09:03 +00001023}
1024
Sanjay Patel2fbab9d82015-09-09 14:34:26 +00001025/// Return true if we can take the specified value and return it as type Ty
1026/// without inserting any new casts and without changing the value of the common
1027/// low bits. This is used by code that tries to promote integer operations to
1028/// a wider types will allow us to eliminate the extension.
Chris Lattnerc3aca382010-01-10 00:58:42 +00001029///
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001030/// This function works on both vectors and scalars.
Chris Lattnerc3aca382010-01-10 00:58:42 +00001031///
Sanjay Patele2834412015-09-09 14:54:29 +00001032static bool canEvaluateSExtd(Value *V, Type *Ty) {
Chris Lattnerc3aca382010-01-10 00:58:42 +00001033 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
1034 "Can't sign extend type to a smaller type");
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001035 // If this is a constant, it can be trivially promoted.
1036 if (isa<Constant>(V))
1037 return true;
Craig Topper3529aa52013-01-24 05:22:40 +00001038
Chris Lattnerc3aca382010-01-10 00:58:42 +00001039 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001040 if (!I) return false;
Craig Topper3529aa52013-01-24 05:22:40 +00001041
Jakob Stoklund Olesenc5c4e962012-06-22 16:36:43 +00001042 // If this is a truncate from the dest type, we can trivially eliminate it.
1043 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001044 return true;
Craig Topper3529aa52013-01-24 05:22:40 +00001045
Chris Lattnerc3aca382010-01-10 00:58:42 +00001046 // We can't extend or shrink something that has multiple uses: doing so would
1047 // require duplicating the instruction in general, which isn't profitable.
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001048 if (!I->hasOneUse()) return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +00001049
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001050 switch (I->getOpcode()) {
Chris Lattner7dd540e2010-01-10 20:30:41 +00001051 case Instruction::SExt: // sext(sext(x)) -> sext(x)
1052 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
1053 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1054 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +00001055 case Instruction::And:
1056 case Instruction::Or:
1057 case Instruction::Xor:
Chris Lattnerc3aca382010-01-10 00:58:42 +00001058 case Instruction::Add:
1059 case Instruction::Sub:
Chris Lattnerc3aca382010-01-10 00:58:42 +00001060 case Instruction::Mul:
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001061 // These operators can all arbitrarily be extended if their inputs can.
Sanjay Patele2834412015-09-09 14:54:29 +00001062 return canEvaluateSExtd(I->getOperand(0), Ty) &&
1063 canEvaluateSExtd(I->getOperand(1), Ty);
Craig Topper3529aa52013-01-24 05:22:40 +00001064
Chris Lattnerc3aca382010-01-10 00:58:42 +00001065 //case Instruction::Shl: TODO
1066 //case Instruction::LShr: TODO
Craig Topper3529aa52013-01-24 05:22:40 +00001067
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001068 case Instruction::Select:
Sanjay Patele2834412015-09-09 14:54:29 +00001069 return canEvaluateSExtd(I->getOperand(1), Ty) &&
1070 canEvaluateSExtd(I->getOperand(2), Ty);
Craig Topper3529aa52013-01-24 05:22:40 +00001071
Chris Lattnerc3aca382010-01-10 00:58:42 +00001072 case Instruction::PHI: {
1073 // We can change a phi if we can change all operands. Note that we never
1074 // get into trouble with cyclic PHIs here because we only consider
1075 // instructions with a single use.
1076 PHINode *PN = cast<PHINode>(I);
Pete Cooper833f34d2015-05-12 20:05:31 +00001077 for (Value *IncValue : PN->incoming_values())
Sanjay Patele2834412015-09-09 14:54:29 +00001078 if (!canEvaluateSExtd(IncValue, Ty)) return false;
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001079 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +00001080 }
1081 default:
1082 // TODO: Can handle more cases here.
1083 break;
1084 }
Craig Topper3529aa52013-01-24 05:22:40 +00001085
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001086 return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +00001087}
1088
Chris Lattner2b295a02010-01-04 07:53:58 +00001089Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Arnaud A. de Grandmaison2e4df4f2013-02-13 00:19:19 +00001090 // If this sign extend is only used by a truncate, let the truncate be
1091 // eliminated before we try to optimize this sext.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001092 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
Craig Topperf40110f2014-04-25 05:29:35 +00001093 return nullptr;
Craig Topper3529aa52013-01-24 05:22:40 +00001094
Chris Lattner883550a2010-01-10 01:00:46 +00001095 if (Instruction *I = commonCastTransforms(CI))
Chris Lattner2b295a02010-01-04 07:53:58 +00001096 return I;
Craig Topper3529aa52013-01-24 05:22:40 +00001097
1098 // See if we can simplify any instructions used by the input whose sole
Chris Lattner883550a2010-01-10 01:00:46 +00001099 // purpose is to compute bits we don't care about.
1100 if (SimplifyDemandedInstructionBits(CI))
1101 return &CI;
Craig Topper3529aa52013-01-24 05:22:40 +00001102
Chris Lattner2b295a02010-01-04 07:53:58 +00001103 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001104 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Chris Lattnerc3aca382010-01-10 00:58:42 +00001105
Philip Reames9ae15202015-02-14 00:05:36 +00001106 // If we know that the value being extended is positive, we can use a zext
1107 // instead.
1108 bool KnownZero, KnownOne;
1109 ComputeSignBit(Src, KnownZero, KnownOne, 0, &CI);
1110 if (KnownZero) {
1111 Value *ZExt = Builder->CreateZExt(Src, DestTy);
Sanjay Patel4b198802016-02-01 22:23:39 +00001112 return replaceInstUsesWith(CI, ZExt);
Philip Reames9ae15202015-02-14 00:05:36 +00001113 }
1114
Chris Lattnerc3aca382010-01-10 00:58:42 +00001115 // Attempt to extend the entire input expression tree to the destination
1116 // type. Only do this if the dest type is a simple type, don't convert the
1117 // expression tree to something weird like i93 unless the source is also
1118 // strange.
Duncan Sands19d0b472010-02-16 11:11:14 +00001119 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Sanjay Patele2834412015-09-09 14:54:29 +00001120 canEvaluateSExtd(Src, DestTy)) {
Chris Lattner2fff10c2010-01-10 07:40:50 +00001121 // Okay, we can transform this! Insert the new expression now.
1122 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
Weiming Zhao24fbef52015-12-17 19:53:41 +00001123 " to avoid sign extend: " << CI << '\n');
Chris Lattner2fff10c2010-01-10 07:40:50 +00001124 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1125 assert(Res->getType() == DestTy);
1126
Chris Lattnerc3aca382010-01-10 00:58:42 +00001127 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1128 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Chris Lattner2fff10c2010-01-10 07:40:50 +00001129
1130 // If the high bits are already filled with sign bit, just replace this
1131 // cast with the result.
Hal Finkel60db0582014-09-07 18:57:58 +00001132 if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize)
Sanjay Patel4b198802016-02-01 22:23:39 +00001133 return replaceInstUsesWith(CI, Res);
Craig Topper3529aa52013-01-24 05:22:40 +00001134
Chris Lattner2fff10c2010-01-10 07:40:50 +00001135 // We need to emit a shl + ashr to do the sign extend.
1136 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1137 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
1138 ShAmt);
Chris Lattnerc3aca382010-01-10 00:58:42 +00001139 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001140
Chris Lattner43f2fa62010-01-18 22:19:16 +00001141 // If this input is a trunc from our destination, then turn sext(trunc(x))
1142 // into shifts.
1143 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1144 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1145 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1146 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Craig Topper3529aa52013-01-24 05:22:40 +00001147
Chris Lattner43f2fa62010-01-18 22:19:16 +00001148 // We need to emit a shl + ashr to do the sign extend.
1149 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1150 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1151 return BinaryOperator::CreateAShr(Res, ShAmt);
1152 }
Nate Begeman7aa18bf2010-12-17 23:12:19 +00001153
Benjamin Kramer398b8c52011-04-01 20:09:03 +00001154 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1155 return transformSExtICmp(ICI, CI);
Bill Wendling5e360552010-12-17 23:27:41 +00001156
Chris Lattner2b295a02010-01-04 07:53:58 +00001157 // If the input is a shl/ashr pair of a same constant, then this is a sign
1158 // extension from a smaller value. If we could trust arbitrary bitwidth
1159 // integers, we could turn this into a truncate to the smaller bit and then
1160 // use a sext for the whole extension. Since we don't, look deeper and check
1161 // for a truncate. If the source and dest are the same type, eliminate the
1162 // trunc and extend and just do shifts. For example, turn:
1163 // %a = trunc i32 %i to i8
1164 // %b = shl i8 %a, 6
1165 // %c = ashr i8 %b, 6
1166 // %d = sext i8 %c to i32
1167 // into:
1168 // %a = shl i32 %i, 30
1169 // %d = ashr i32 %a, 30
Craig Topperf40110f2014-04-25 05:29:35 +00001170 Value *A = nullptr;
Chris Lattnerc95a7a22010-01-10 01:04:31 +00001171 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
Craig Topperf40110f2014-04-25 05:29:35 +00001172 ConstantInt *BA = nullptr, *CA = nullptr;
Chris Lattnerc95a7a22010-01-10 01:04:31 +00001173 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
Chris Lattner2b295a02010-01-04 07:53:58 +00001174 m_ConstantInt(CA))) &&
Chris Lattnerc95a7a22010-01-10 01:04:31 +00001175 BA == CA && A->getType() == CI.getType()) {
1176 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1177 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1178 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1179 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1180 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1181 return BinaryOperator::CreateAShr(A, ShAmtV);
Chris Lattner2b295a02010-01-04 07:53:58 +00001182 }
Craig Topper3529aa52013-01-24 05:22:40 +00001183
Craig Topperf40110f2014-04-25 05:29:35 +00001184 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +00001185}
1186
1187
Sanjay Patel2fbab9d82015-09-09 14:34:26 +00001188/// Return a Constant* for the specified floating-point constant if it fits
Chris Lattner2b295a02010-01-04 07:53:58 +00001189/// in the specified FP type without changing its value.
Sanjay Patele2834412015-09-09 14:54:29 +00001190static Constant *fitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattner2b295a02010-01-04 07:53:58 +00001191 bool losesInfo;
1192 APFloat F = CFP->getValueAPF();
1193 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1194 if (!losesInfo)
1195 return ConstantFP::get(CFP->getContext(), F);
Craig Topperf40110f2014-04-25 05:29:35 +00001196 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +00001197}
1198
Sanjay Patel2fbab9d82015-09-09 14:34:26 +00001199/// If this is a floating-point extension instruction, look
Chris Lattner2b295a02010-01-04 07:53:58 +00001200/// through it until we get the source value.
Sanjay Patele2834412015-09-09 14:54:29 +00001201static Value *lookThroughFPExtensions(Value *V) {
Chris Lattner2b295a02010-01-04 07:53:58 +00001202 if (Instruction *I = dyn_cast<Instruction>(V))
1203 if (I->getOpcode() == Instruction::FPExt)
Sanjay Patele2834412015-09-09 14:54:29 +00001204 return lookThroughFPExtensions(I->getOperand(0));
Craig Topper3529aa52013-01-24 05:22:40 +00001205
Chris Lattner2b295a02010-01-04 07:53:58 +00001206 // If this value is a constant, return the constant in the smallest FP type
1207 // that can accurately represent it. This allows us to turn
1208 // (float)((double)X+2.0) into x+2.0f.
1209 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1210 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1211 return V; // No constant folding of this.
Dan Gohman518cda42011-12-17 00:04:22 +00001212 // See if the value can be truncated to half and then reextended.
Sanjay Patele2834412015-09-09 14:54:29 +00001213 if (Value *V = fitsInFPType(CFP, APFloat::IEEEhalf))
Dan Gohman518cda42011-12-17 00:04:22 +00001214 return V;
Chris Lattner2b295a02010-01-04 07:53:58 +00001215 // See if the value can be truncated to float and then reextended.
Sanjay Patele2834412015-09-09 14:54:29 +00001216 if (Value *V = fitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattner2b295a02010-01-04 07:53:58 +00001217 return V;
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001218 if (CFP->getType()->isDoubleTy())
Chris Lattner2b295a02010-01-04 07:53:58 +00001219 return V; // Won't shrink.
Sanjay Patele2834412015-09-09 14:54:29 +00001220 if (Value *V = fitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattner2b295a02010-01-04 07:53:58 +00001221 return V;
1222 // Don't try to shrink to various long double types.
1223 }
Craig Topper3529aa52013-01-24 05:22:40 +00001224
Chris Lattner2b295a02010-01-04 07:53:58 +00001225 return V;
1226}
1227
1228Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1229 if (Instruction *I = commonCastTransforms(CI))
1230 return I;
Stephen Canonc4549642013-11-28 21:38:05 +00001231 // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
Sanjay Patel5a7bdc92015-11-21 16:16:29 +00001232 // simplify this expression to avoid one or more of the trunc/extend
Stephen Canonc4549642013-11-28 21:38:05 +00001233 // operations if we can do so without changing the numerical results.
1234 //
1235 // The exact manner in which the widths of the operands interact to limit
1236 // what we can and cannot do safely varies from operation to operation, and
1237 // is explained below in the various case statements.
Chris Lattner2b295a02010-01-04 07:53:58 +00001238 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1239 if (OpI && OpI->hasOneUse()) {
Sanjay Patele2834412015-09-09 14:54:29 +00001240 Value *LHSOrig = lookThroughFPExtensions(OpI->getOperand(0));
1241 Value *RHSOrig = lookThroughFPExtensions(OpI->getOperand(1));
Stephen Canonc4549642013-11-28 21:38:05 +00001242 unsigned OpWidth = OpI->getType()->getFPMantissaWidth();
1243 unsigned LHSWidth = LHSOrig->getType()->getFPMantissaWidth();
1244 unsigned RHSWidth = RHSOrig->getType()->getFPMantissaWidth();
1245 unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
1246 unsigned DstWidth = CI.getType()->getFPMantissaWidth();
Chris Lattner2b295a02010-01-04 07:53:58 +00001247 switch (OpI->getOpcode()) {
Stephen Canonc4549642013-11-28 21:38:05 +00001248 default: break;
1249 case Instruction::FAdd:
1250 case Instruction::FSub:
1251 // For addition and subtraction, the infinitely precise result can
1252 // essentially be arbitrarily wide; proving that double rounding
1253 // will not occur because the result of OpI is exact (as we will for
1254 // FMul, for example) is hopeless. However, we *can* nonetheless
1255 // frequently know that double rounding cannot occur (or that it is
Alp Tokercb402912014-01-24 17:20:08 +00001256 // innocuous) by taking advantage of the specific structure of
Stephen Canonc4549642013-11-28 21:38:05 +00001257 // infinitely-precise results that admit double rounding.
1258 //
Alp Tokercb402912014-01-24 17:20:08 +00001259 // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
Stephen Canonc4549642013-11-28 21:38:05 +00001260 // to represent both sources, we can guarantee that the double
1261 // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
1262 // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
1263 // for proof of this fact).
1264 //
1265 // Note: Figueroa does not consider the case where DstFormat !=
1266 // SrcFormat. It's possible (likely even!) that this analysis
1267 // could be tightened for those cases, but they are rare (the main
1268 // case of interest here is (float)((double)float + float)).
1269 if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
1270 if (LHSOrig->getType() != CI.getType())
1271 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1272 if (RHSOrig->getType() != CI.getType())
1273 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001274 Instruction *RI =
1275 BinaryOperator::Create(OpI->getOpcode(), LHSOrig, RHSOrig);
1276 RI->copyFastMathFlags(OpI);
1277 return RI;
Chris Lattner2b295a02010-01-04 07:53:58 +00001278 }
Stephen Canonc4549642013-11-28 21:38:05 +00001279 break;
1280 case Instruction::FMul:
1281 // For multiplication, the infinitely precise result has at most
1282 // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
1283 // that such a value can be exactly represented, then no double
1284 // rounding can possibly occur; we can safely perform the operation
1285 // in the destination format if it can represent both sources.
1286 if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
1287 if (LHSOrig->getType() != CI.getType())
1288 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1289 if (RHSOrig->getType() != CI.getType())
1290 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001291 Instruction *RI =
1292 BinaryOperator::CreateFMul(LHSOrig, RHSOrig);
1293 RI->copyFastMathFlags(OpI);
1294 return RI;
Stephen Canonc4549642013-11-28 21:38:05 +00001295 }
1296 break;
1297 case Instruction::FDiv:
1298 // For division, we use again use the bound from Figueroa's
1299 // dissertation. I am entirely certain that this bound can be
1300 // tightened in the unbalanced operand case by an analysis based on
1301 // the diophantine rational approximation bound, but the well-known
1302 // condition used here is a good conservative first pass.
1303 // TODO: Tighten bound via rigorous analysis of the unbalanced case.
1304 if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
1305 if (LHSOrig->getType() != CI.getType())
1306 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1307 if (RHSOrig->getType() != CI.getType())
1308 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001309 Instruction *RI =
1310 BinaryOperator::CreateFDiv(LHSOrig, RHSOrig);
1311 RI->copyFastMathFlags(OpI);
1312 return RI;
Stephen Canonc4549642013-11-28 21:38:05 +00001313 }
1314 break;
1315 case Instruction::FRem:
1316 // Remainder is straightforward. Remainder is always exact, so the
1317 // type of OpI doesn't enter into things at all. We simply evaluate
1318 // in whichever source type is larger, then convert to the
1319 // destination type.
Steven Wuf179d122014-12-12 18:48:37 +00001320 if (SrcWidth == OpWidth)
Steven Wu1f7402a2014-12-12 17:21:54 +00001321 break;
Steven Wu1f7402a2014-12-12 17:21:54 +00001322 if (LHSWidth < SrcWidth)
1323 LHSOrig = Builder->CreateFPExt(LHSOrig, RHSOrig->getType());
1324 else if (RHSWidth <= SrcWidth)
1325 RHSOrig = Builder->CreateFPExt(RHSOrig, LHSOrig->getType());
1326 if (LHSOrig != OpI->getOperand(0) || RHSOrig != OpI->getOperand(1)) {
1327 Value *ExactResult = Builder->CreateFRem(LHSOrig, RHSOrig);
1328 if (Instruction *RI = dyn_cast<Instruction>(ExactResult))
1329 RI->copyFastMathFlags(OpI);
1330 return CastInst::CreateFPCast(ExactResult, CI.getType());
1331 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001332 }
Owen Andersondbf0ca52013-01-10 22:06:52 +00001333
1334 // (fptrunc (fneg x)) -> (fneg (fptrunc x))
1335 if (BinaryOperator::isFNeg(OpI)) {
1336 Value *InnerTrunc = Builder->CreateFPTrunc(OpI->getOperand(1),
1337 CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001338 Instruction *RI = BinaryOperator::CreateFNeg(InnerTrunc);
1339 RI->copyFastMathFlags(OpI);
1340 return RI;
Owen Andersondbf0ca52013-01-10 22:06:52 +00001341 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001342 }
Owen Andersondbf0ca52013-01-10 22:06:52 +00001343
Owen Anderson5797bfd2013-10-03 21:08:05 +00001344 // (fptrunc (select cond, R1, Cst)) -->
1345 // (select cond, (fptrunc R1), (fptrunc Cst))
James Molloy134bec22015-08-11 09:12:57 +00001346 //
1347 // - but only if this isn't part of a min/max operation, else we'll
1348 // ruin min/max canonical form which is to have the select and
1349 // compare's operands be of the same type with no casts to look through.
1350 Value *LHS, *RHS;
Owen Anderson5797bfd2013-10-03 21:08:05 +00001351 SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0));
1352 if (SI &&
1353 (isa<ConstantFP>(SI->getOperand(1)) ||
James Molloy134bec22015-08-11 09:12:57 +00001354 isa<ConstantFP>(SI->getOperand(2))) &&
1355 matchSelectPattern(SI, LHS, RHS).Flavor == SPF_UNKNOWN) {
Owen Anderson5797bfd2013-10-03 21:08:05 +00001356 Value *LHSTrunc = Builder->CreateFPTrunc(SI->getOperand(1),
1357 CI.getType());
1358 Value *RHSTrunc = Builder->CreateFPTrunc(SI->getOperand(2),
1359 CI.getType());
1360 return SelectInst::Create(SI->getOperand(0), LHSTrunc, RHSTrunc);
1361 }
1362
Owen Andersondbf0ca52013-01-10 22:06:52 +00001363 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI.getOperand(0));
1364 if (II) {
1365 switch (II->getIntrinsicID()) {
1366 default: break;
1367 case Intrinsic::fabs: {
1368 // (fptrunc (fabs x)) -> (fabs (fptrunc x))
1369 Value *InnerTrunc = Builder->CreateFPTrunc(II->getArgOperand(0),
1370 CI.getType());
1371 Type *IntrinsicType[] = { CI.getType() };
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001372 Function *Overload = Intrinsic::getDeclaration(
1373 CI.getModule(), II->getIntrinsicID(), IntrinsicType);
Owen Andersondbf0ca52013-01-10 22:06:52 +00001374
David Majnemer231a68c2016-04-29 08:07:20 +00001375 SmallVector<OperandBundleDef, 1> OpBundles;
1376 II->getOperandBundlesAsDefs(OpBundles);
1377
Owen Andersondbf0ca52013-01-10 22:06:52 +00001378 Value *Args[] = { InnerTrunc };
David Majnemer231a68c2016-04-29 08:07:20 +00001379 return CallInst::Create(Overload, Args, OpBundles, II->getName());
Owen Andersondbf0ca52013-01-10 22:06:52 +00001380 }
1381 }
1382 }
1383
Craig Topperf40110f2014-04-25 05:29:35 +00001384 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +00001385}
1386
1387Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1388 return commonCastTransforms(CI);
1389}
1390
Mehdi Aminib9a0fa42015-02-16 21:47:54 +00001391// fpto{s/u}i({u/s}itofp(X)) --> X or zext(X) or sext(X) or trunc(X)
1392// This is safe if the intermediate type has enough bits in its mantissa to
1393// accurately represent all values of X. For example, this won't work with
1394// i64 -> float -> i64.
1395Instruction *InstCombiner::FoldItoFPtoI(Instruction &FI) {
1396 if (!isa<UIToFPInst>(FI.getOperand(0)) && !isa<SIToFPInst>(FI.getOperand(0)))
1397 return nullptr;
1398 Instruction *OpI = cast<Instruction>(FI.getOperand(0));
1399
1400 Value *SrcI = OpI->getOperand(0);
1401 Type *FITy = FI.getType();
1402 Type *OpITy = OpI->getType();
1403 Type *SrcTy = SrcI->getType();
1404 bool IsInputSigned = isa<SIToFPInst>(OpI);
1405 bool IsOutputSigned = isa<FPToSIInst>(FI);
1406
1407 // We can safely assume the conversion won't overflow the output range,
1408 // because (for example) (uint8_t)18293.f is undefined behavior.
1409
1410 // Since we can assume the conversion won't overflow, our decision as to
1411 // whether the input will fit in the float should depend on the minimum
1412 // of the input range and output range.
1413
1414 // This means this is also safe for a signed input and unsigned output, since
1415 // a negative input would lead to undefined behavior.
1416 int InputSize = (int)SrcTy->getScalarSizeInBits() - IsInputSigned;
1417 int OutputSize = (int)FITy->getScalarSizeInBits() - IsOutputSigned;
1418 int ActualSize = std::min(InputSize, OutputSize);
1419
1420 if (ActualSize <= OpITy->getFPMantissaWidth()) {
1421 if (FITy->getScalarSizeInBits() > SrcTy->getScalarSizeInBits()) {
1422 if (IsInputSigned && IsOutputSigned)
1423 return new SExtInst(SrcI, FITy);
1424 return new ZExtInst(SrcI, FITy);
1425 }
1426 if (FITy->getScalarSizeInBits() < SrcTy->getScalarSizeInBits())
1427 return new TruncInst(SrcI, FITy);
1428 if (SrcTy == FITy)
Sanjay Patel4b198802016-02-01 22:23:39 +00001429 return replaceInstUsesWith(FI, SrcI);
Mehdi Aminib9a0fa42015-02-16 21:47:54 +00001430 return new BitCastInst(SrcI, FITy);
1431 }
1432 return nullptr;
1433}
1434
Chris Lattner2b295a02010-01-04 07:53:58 +00001435Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1436 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001437 if (!OpI)
Chris Lattner2b295a02010-01-04 07:53:58 +00001438 return commonCastTransforms(FI);
1439
Mehdi Aminib9a0fa42015-02-16 21:47:54 +00001440 if (Instruction *I = FoldItoFPtoI(FI))
1441 return I;
Chris Lattner2b295a02010-01-04 07:53:58 +00001442
1443 return commonCastTransforms(FI);
1444}
1445
1446Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1447 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001448 if (!OpI)
Chris Lattner2b295a02010-01-04 07:53:58 +00001449 return commonCastTransforms(FI);
Craig Topper3529aa52013-01-24 05:22:40 +00001450
Mehdi Aminib9a0fa42015-02-16 21:47:54 +00001451 if (Instruction *I = FoldItoFPtoI(FI))
1452 return I;
Craig Topper3529aa52013-01-24 05:22:40 +00001453
Chris Lattner2b295a02010-01-04 07:53:58 +00001454 return commonCastTransforms(FI);
1455}
1456
1457Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1458 return commonCastTransforms(CI);
1459}
1460
1461Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1462 return commonCastTransforms(CI);
1463}
1464
Chris Lattner2b295a02010-01-04 07:53:58 +00001465Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Dan Gohman949458d2010-02-02 01:44:02 +00001466 // If the source integer type is not the intptr_t type for this target, do a
1467 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1468 // cast to be exposed to other transforms.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001469 unsigned AS = CI.getAddressSpace();
1470 if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
1471 DL.getPointerSizeInBits(AS)) {
1472 Type *Ty = DL.getIntPtrType(CI.getContext(), AS);
1473 if (CI.getType()->isVectorTy()) // Handle vectors of pointers.
1474 Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements());
Benjamin Kramer944e0ab2013-02-05 20:22:40 +00001475
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001476 Value *P = Builder->CreateZExtOrTrunc(CI.getOperand(0), Ty);
1477 return new IntToPtrInst(P, CI.getType());
Chris Lattner2b295a02010-01-04 07:53:58 +00001478 }
Craig Topper3529aa52013-01-24 05:22:40 +00001479
Chris Lattner2b295a02010-01-04 07:53:58 +00001480 if (Instruction *I = commonCastTransforms(CI))
1481 return I;
1482
Craig Topperf40110f2014-04-25 05:29:35 +00001483 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +00001484}
1485
Chris Lattnera93c63c2010-01-05 22:21:18 +00001486/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1487Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1488 Value *Src = CI.getOperand(0);
Craig Topper3529aa52013-01-24 05:22:40 +00001489
Chris Lattnera93c63c2010-01-05 22:21:18 +00001490 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1491 // If casting the result of a getelementptr instruction with no offset, turn
1492 // this into a cast of the original pointer!
Jingyue Wu77145d92014-06-06 21:52:55 +00001493 if (GEP->hasAllZeroIndices() &&
1494 // If CI is an addrspacecast and GEP changes the poiner type, merging
1495 // GEP into CI would undo canonicalizing addrspacecast with different
1496 // pointer types, causing infinite loops.
1497 (!isa<AddrSpaceCastInst>(CI) ||
1498 GEP->getType() == GEP->getPointerOperand()->getType())) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001499 // Changing the cast operand is usually not a good idea but it is safe
Craig Topper3529aa52013-01-24 05:22:40 +00001500 // here because the pointer operand is being replaced with another
Chris Lattnera93c63c2010-01-05 22:21:18 +00001501 // pointer operand so the opcode doesn't need to change.
1502 Worklist.Add(GEP);
1503 CI.setOperand(0, GEP->getOperand(0));
1504 return &CI;
1505 }
Chris Lattnera93c63c2010-01-05 22:21:18 +00001506 }
Craig Topper3529aa52013-01-24 05:22:40 +00001507
Chris Lattnera93c63c2010-01-05 22:21:18 +00001508 return commonCastTransforms(CI);
1509}
1510
1511Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
Dan Gohman949458d2010-02-02 01:44:02 +00001512 // If the destination integer type is not the intptr_t type for this target,
1513 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1514 // to be exposed to other transforms.
Benjamin Kramere4778752013-02-05 19:21:56 +00001515
Matt Arsenault745101d2013-08-21 19:53:10 +00001516 Type *Ty = CI.getType();
1517 unsigned AS = CI.getPointerAddressSpace();
1518
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001519 if (Ty->getScalarSizeInBits() == DL.getPointerSizeInBits(AS))
Matt Arsenault745101d2013-08-21 19:53:10 +00001520 return commonPointerCastTransforms(CI);
1521
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001522 Type *PtrTy = DL.getIntPtrType(CI.getContext(), AS);
Matt Arsenault745101d2013-08-21 19:53:10 +00001523 if (Ty->isVectorTy()) // Handle vectors of pointers.
1524 PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements());
1525
1526 Value *P = Builder->CreatePtrToInt(CI.getOperand(0), PtrTy);
1527 return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
Chris Lattnera93c63c2010-01-05 22:21:18 +00001528}
1529
Sanjay Patel2fbab9d82015-09-09 14:34:26 +00001530/// This input value (which is known to have vector type) is being zero extended
1531/// or truncated to the specified vector type.
1532/// Try to replace it with a shuffle (and vector/vector bitcast) if possible.
Chris Lattner02b0df52010-05-08 21:50:26 +00001533///
1534/// The source and destination vector types may have different element types.
Sanjay Patele2834412015-09-09 14:54:29 +00001535static Instruction *optimizeVectorResize(Value *InVal, VectorType *DestTy,
Chris Lattner02b0df52010-05-08 21:50:26 +00001536 InstCombiner &IC) {
1537 // We can only do this optimization if the output is a multiple of the input
1538 // element size, or the input is a multiple of the output element size.
1539 // Convert the input type to have the same element type as the output.
Chris Lattner229907c2011-07-18 04:54:35 +00001540 VectorType *SrcTy = cast<VectorType>(InVal->getType());
Craig Topper3529aa52013-01-24 05:22:40 +00001541
Chris Lattner02b0df52010-05-08 21:50:26 +00001542 if (SrcTy->getElementType() != DestTy->getElementType()) {
1543 // The input types don't need to be identical, but for now they must be the
1544 // same size. There is no specific reason we couldn't handle things like
1545 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
Craig Topper3529aa52013-01-24 05:22:40 +00001546 // there yet.
Chris Lattner02b0df52010-05-08 21:50:26 +00001547 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1548 DestTy->getElementType()->getPrimitiveSizeInBits())
Craig Topperf40110f2014-04-25 05:29:35 +00001549 return nullptr;
Craig Topper3529aa52013-01-24 05:22:40 +00001550
Chris Lattner02b0df52010-05-08 21:50:26 +00001551 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1552 InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1553 }
Craig Topper3529aa52013-01-24 05:22:40 +00001554
Chris Lattner02b0df52010-05-08 21:50:26 +00001555 // Now that the element types match, get the shuffle mask and RHS of the
1556 // shuffle to use, which depends on whether we're increasing or decreasing the
1557 // size of the input.
Chris Lattner8213c8a2012-02-06 21:56:39 +00001558 SmallVector<uint32_t, 16> ShuffleMask;
Chris Lattner02b0df52010-05-08 21:50:26 +00001559 Value *V2;
Craig Topper3529aa52013-01-24 05:22:40 +00001560
Chris Lattner02b0df52010-05-08 21:50:26 +00001561 if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1562 // If we're shrinking the number of elements, just shuffle in the low
1563 // elements from the input and use undef as the second shuffle input.
1564 V2 = UndefValue::get(SrcTy);
1565 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
Chris Lattner8213c8a2012-02-06 21:56:39 +00001566 ShuffleMask.push_back(i);
Craig Topper3529aa52013-01-24 05:22:40 +00001567
Chris Lattner02b0df52010-05-08 21:50:26 +00001568 } else {
1569 // If we're increasing the number of elements, shuffle in all of the
1570 // elements from InVal and fill the rest of the result elements with zeros
1571 // from a constant zero.
1572 V2 = Constant::getNullValue(SrcTy);
1573 unsigned SrcElts = SrcTy->getNumElements();
1574 for (unsigned i = 0, e = SrcElts; i != e; ++i)
Chris Lattner8213c8a2012-02-06 21:56:39 +00001575 ShuffleMask.push_back(i);
Chris Lattner02b0df52010-05-08 21:50:26 +00001576
1577 // The excess elements reference the first element of the zero input.
Chris Lattner8213c8a2012-02-06 21:56:39 +00001578 for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i)
1579 ShuffleMask.push_back(SrcElts);
Chris Lattner02b0df52010-05-08 21:50:26 +00001580 }
Craig Topper3529aa52013-01-24 05:22:40 +00001581
Chris Lattner8213c8a2012-02-06 21:56:39 +00001582 return new ShuffleVectorInst(InVal, V2,
1583 ConstantDataVector::get(V2->getContext(),
1584 ShuffleMask));
Chris Lattner02b0df52010-05-08 21:50:26 +00001585}
1586
Chris Lattner229907c2011-07-18 04:54:35 +00001587static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
Chris Lattnerdd660102010-08-28 01:20:38 +00001588 return Value % Ty->getPrimitiveSizeInBits() == 0;
1589}
1590
Chris Lattner229907c2011-07-18 04:54:35 +00001591static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
Chris Lattnerdd660102010-08-28 01:20:38 +00001592 return Value / Ty->getPrimitiveSizeInBits();
1593}
1594
Sanjay Patel2fbab9d82015-09-09 14:34:26 +00001595/// V is a value which is inserted into a vector of VecEltTy.
1596/// Look through the value to see if we can decompose it into
Chris Lattnerdd660102010-08-28 01:20:38 +00001597/// insertions into the vector. See the example in the comment for
1598/// OptimizeIntegerToVectorInsertions for the pattern this handles.
1599/// The type of V is always a non-zero multiple of VecEltTy's size.
Richard Sandifordfeb34712013-08-12 07:26:09 +00001600/// Shift is the number of bits between the lsb of V and the lsb of
1601/// the vector.
Chris Lattnerdd660102010-08-28 01:20:38 +00001602///
1603/// This returns false if the pattern can't be matched or true if it can,
1604/// filling in Elements with the elements found here.
Sanjay Patele2834412015-09-09 14:54:29 +00001605static bool collectInsertionElements(Value *V, unsigned Shift,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001606 SmallVectorImpl<Value *> &Elements,
1607 Type *VecEltTy, bool isBigEndian) {
Richard Sandifordfeb34712013-08-12 07:26:09 +00001608 assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
1609 "Shift should be a multiple of the element type size");
1610
Chris Lattner50df36a2010-08-28 03:36:51 +00001611 // Undef values never contribute useful bits to the result.
1612 if (isa<UndefValue>(V)) return true;
Craig Topper3529aa52013-01-24 05:22:40 +00001613
Chris Lattnerdd660102010-08-28 01:20:38 +00001614 // If we got down to a value of the right type, we win, try inserting into the
1615 // right element.
1616 if (V->getType() == VecEltTy) {
Chris Lattnerd0214f32010-08-28 01:50:57 +00001617 // Inserting null doesn't actually insert any elements.
1618 if (Constant *C = dyn_cast<Constant>(V))
1619 if (C->isNullValue())
1620 return true;
Craig Topper3529aa52013-01-24 05:22:40 +00001621
Richard Sandifordfeb34712013-08-12 07:26:09 +00001622 unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001623 if (isBigEndian)
Richard Sandifordfeb34712013-08-12 07:26:09 +00001624 ElementIndex = Elements.size() - ElementIndex - 1;
1625
Chris Lattnerdd660102010-08-28 01:20:38 +00001626 // Fail if multiple elements are inserted into this slot.
Craig Topperf40110f2014-04-25 05:29:35 +00001627 if (Elements[ElementIndex])
Chris Lattnerdd660102010-08-28 01:20:38 +00001628 return false;
Craig Topper3529aa52013-01-24 05:22:40 +00001629
Chris Lattnerdd660102010-08-28 01:20:38 +00001630 Elements[ElementIndex] = V;
1631 return true;
1632 }
Craig Topper3529aa52013-01-24 05:22:40 +00001633
Chris Lattnerd0214f32010-08-28 01:50:57 +00001634 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerdd660102010-08-28 01:20:38 +00001635 // Figure out the # elements this provides, and bitcast it or slice it up
1636 // as required.
Chris Lattnerd0214f32010-08-28 01:50:57 +00001637 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1638 VecEltTy);
1639 // If the constant is the size of a vector element, we just need to bitcast
1640 // it to the right type so it gets properly inserted.
1641 if (NumElts == 1)
Sanjay Patele2834412015-09-09 14:54:29 +00001642 return collectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001643 Shift, Elements, VecEltTy, isBigEndian);
Craig Topper3529aa52013-01-24 05:22:40 +00001644
Chris Lattnerd0214f32010-08-28 01:50:57 +00001645 // Okay, this is a constant that covers multiple elements. Slice it up into
1646 // pieces and insert each element-sized piece into the vector.
1647 if (!isa<IntegerType>(C->getType()))
1648 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1649 C->getType()->getPrimitiveSizeInBits()));
1650 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +00001651 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
Craig Topper3529aa52013-01-24 05:22:40 +00001652
Chris Lattnerd0214f32010-08-28 01:50:57 +00001653 for (unsigned i = 0; i != NumElts; ++i) {
Richard Sandifordfeb34712013-08-12 07:26:09 +00001654 unsigned ShiftI = Shift+i*ElementSize;
Chris Lattnerd0214f32010-08-28 01:50:57 +00001655 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
Richard Sandifordfeb34712013-08-12 07:26:09 +00001656 ShiftI));
Chris Lattnerd0214f32010-08-28 01:50:57 +00001657 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
Sanjay Patele2834412015-09-09 14:54:29 +00001658 if (!collectInsertionElements(Piece, ShiftI, Elements, VecEltTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001659 isBigEndian))
Chris Lattnerd0214f32010-08-28 01:50:57 +00001660 return false;
1661 }
1662 return true;
1663 }
Craig Topper3529aa52013-01-24 05:22:40 +00001664
Chris Lattnerdd660102010-08-28 01:20:38 +00001665 if (!V->hasOneUse()) return false;
Craig Topper3529aa52013-01-24 05:22:40 +00001666
Chris Lattnerdd660102010-08-28 01:20:38 +00001667 Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +00001668 if (!I) return false;
Chris Lattnerdd660102010-08-28 01:20:38 +00001669 switch (I->getOpcode()) {
1670 default: return false; // Unhandled case.
1671 case Instruction::BitCast:
Sanjay Patele2834412015-09-09 14:54:29 +00001672 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001673 isBigEndian);
Chris Lattnerdd660102010-08-28 01:20:38 +00001674 case Instruction::ZExt:
1675 if (!isMultipleOfTypeSize(
1676 I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1677 VecEltTy))
1678 return false;
Sanjay Patele2834412015-09-09 14:54:29 +00001679 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001680 isBigEndian);
Chris Lattnerdd660102010-08-28 01:20:38 +00001681 case Instruction::Or:
Sanjay Patele2834412015-09-09 14:54:29 +00001682 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001683 isBigEndian) &&
Sanjay Patele2834412015-09-09 14:54:29 +00001684 collectInsertionElements(I->getOperand(1), Shift, Elements, VecEltTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001685 isBigEndian);
Chris Lattnerdd660102010-08-28 01:20:38 +00001686 case Instruction::Shl: {
1687 // Must be shifting by a constant that is a multiple of the element size.
1688 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +00001689 if (!CI) return false;
Richard Sandifordfeb34712013-08-12 07:26:09 +00001690 Shift += CI->getZExtValue();
1691 if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
Sanjay Patele2834412015-09-09 14:54:29 +00001692 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001693 isBigEndian);
Chris Lattnerdd660102010-08-28 01:20:38 +00001694 }
Craig Topper3529aa52013-01-24 05:22:40 +00001695
Chris Lattnerdd660102010-08-28 01:20:38 +00001696 }
1697}
1698
1699
Sanjay Patel2fbab9d82015-09-09 14:34:26 +00001700/// If the input is an 'or' instruction, we may be doing shifts and ors to
1701/// assemble the elements of the vector manually.
Chris Lattnerdd660102010-08-28 01:20:38 +00001702/// Try to rip the code out and replace it with insertelements. This is to
1703/// optimize code like this:
1704///
1705/// %tmp37 = bitcast float %inc to i32
1706/// %tmp38 = zext i32 %tmp37 to i64
1707/// %tmp31 = bitcast float %inc5 to i32
1708/// %tmp32 = zext i32 %tmp31 to i64
1709/// %tmp33 = shl i64 %tmp32, 32
1710/// %ins35 = or i64 %tmp33, %tmp38
1711/// %tmp43 = bitcast i64 %ins35 to <2 x float>
1712///
1713/// Into two insertelements that do "buildvector{%inc, %inc5}".
Sanjay Patele2834412015-09-09 14:54:29 +00001714static Value *optimizeIntegerToVectorInsertions(BitCastInst &CI,
Chris Lattnerdd660102010-08-28 01:20:38 +00001715 InstCombiner &IC) {
Chris Lattner229907c2011-07-18 04:54:35 +00001716 VectorType *DestVecTy = cast<VectorType>(CI.getType());
Chris Lattnerdd660102010-08-28 01:20:38 +00001717 Value *IntInput = CI.getOperand(0);
1718
1719 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
Sanjay Patele2834412015-09-09 14:54:29 +00001720 if (!collectInsertionElements(IntInput, 0, Elements,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001721 DestVecTy->getElementType(),
1722 IC.getDataLayout().isBigEndian()))
Craig Topperf40110f2014-04-25 05:29:35 +00001723 return nullptr;
Chris Lattnerdd660102010-08-28 01:20:38 +00001724
1725 // If we succeeded, we know that all of the element are specified by Elements
1726 // or are zero if Elements has a null entry. Recast this as a set of
1727 // insertions.
1728 Value *Result = Constant::getNullValue(CI.getType());
1729 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +00001730 if (!Elements[i]) continue; // Unset element.
Craig Topper3529aa52013-01-24 05:22:40 +00001731
Chris Lattnerdd660102010-08-28 01:20:38 +00001732 Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1733 IC.Builder->getInt32(i));
1734 }
Craig Topper3529aa52013-01-24 05:22:40 +00001735
Chris Lattnerdd660102010-08-28 01:20:38 +00001736 return Result;
1737}
1738
Sanjay Patel1d49fc92015-12-12 16:44:48 +00001739/// Canonicalize scalar bitcasts of extracted elements into a bitcast of the
1740/// vector followed by extract element. The backend tends to handle bitcasts of
1741/// vectors better than bitcasts of scalars because vector registers are
1742/// usually not type-specific like scalar integer or scalar floating-point.
1743static Instruction *canonicalizeBitCastExtElt(BitCastInst &BitCast,
1744 InstCombiner &IC,
1745 const DataLayout &DL) {
Sanjay Patelc83fd952015-12-10 17:09:28 +00001746 // TODO: Create and use a pattern matcher for ExtractElementInst.
1747 auto *ExtElt = dyn_cast<ExtractElementInst>(BitCast.getOperand(0));
1748 if (!ExtElt || !ExtElt->hasOneUse())
1749 return nullptr;
1750
Sanjay Patel1d49fc92015-12-12 16:44:48 +00001751 // The bitcast must be to a vectorizable type, otherwise we can't make a new
1752 // type to extract from.
1753 Type *DestType = BitCast.getType();
1754 if (!VectorType::isValidElementType(DestType))
Sanjay Patelc83fd952015-12-10 17:09:28 +00001755 return nullptr;
1756
Sanjay Patel1d49fc92015-12-12 16:44:48 +00001757 unsigned NumElts = ExtElt->getVectorOperandType()->getNumElements();
1758 auto *NewVecType = VectorType::get(DestType, NumElts);
1759 auto *NewBC = IC.Builder->CreateBitCast(ExtElt->getVectorOperand(),
1760 NewVecType, "bc");
1761 return ExtractElementInst::Create(NewBC, ExtElt->getIndexOperand());
Sanjay Patelc83fd952015-12-10 17:09:28 +00001762}
1763
Chris Lattner2b295a02010-01-04 07:53:58 +00001764Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1765 // If the operands are integer typed then apply the integer transforms,
1766 // otherwise just apply the common ones.
1767 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001768 Type *SrcTy = Src->getType();
1769 Type *DestTy = CI.getType();
Chris Lattner2b295a02010-01-04 07:53:58 +00001770
Chris Lattner2b295a02010-01-04 07:53:58 +00001771 // Get rid of casts from one type to the same type. These are useless and can
1772 // be replaced by the operand.
1773 if (DestTy == Src->getType())
Sanjay Patel4b198802016-02-01 22:23:39 +00001774 return replaceInstUsesWith(CI, Src);
Chris Lattner2b295a02010-01-04 07:53:58 +00001775
Chris Lattner229907c2011-07-18 04:54:35 +00001776 if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1777 PointerType *SrcPTy = cast<PointerType>(SrcTy);
1778 Type *DstElTy = DstPTy->getElementType();
1779 Type *SrcElTy = SrcPTy->getElementType();
Craig Topper3529aa52013-01-24 05:22:40 +00001780
Chris Lattner2b295a02010-01-04 07:53:58 +00001781 // If we are casting a alloca to a pointer to a type of the same
1782 // size, rewrite the allocation instruction to allocate the "right" type.
1783 // There is no need to modify malloc calls because it is their bitcast that
1784 // needs to be cleaned up.
1785 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1786 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1787 return V;
Craig Topper3529aa52013-01-24 05:22:40 +00001788
Gerolf Hoflehner00e70922016-05-23 19:23:17 +00001789 // When the type pointed to is not sized the cast cannot be
1790 // turned into a gep.
1791 Type *PointeeType =
1792 cast<PointerType>(Src->getType()->getScalarType())->getElementType();
1793 if (!PointeeType->isSized())
1794 return nullptr;
1795
Chris Lattner2b295a02010-01-04 07:53:58 +00001796 // If the source and destination are pointers, and this cast is equivalent
1797 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1798 // This can enhance SROA and other transforms that want type-safe pointers.
Chris Lattner2b295a02010-01-04 07:53:58 +00001799 unsigned NumZeros = 0;
Craig Topper3529aa52013-01-24 05:22:40 +00001800 while (SrcElTy != DstElTy &&
Duncan Sands19d0b472010-02-16 11:11:14 +00001801 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
Chris Lattner2b295a02010-01-04 07:53:58 +00001802 SrcElTy->getNumContainedTypes() /* not "{}" */) {
Benjamin Kramer2a7404a2015-04-18 16:52:08 +00001803 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(0U);
Chris Lattner2b295a02010-01-04 07:53:58 +00001804 ++NumZeros;
1805 }
1806
1807 // If we found a path from the src to dest, create the getelementptr now.
1808 if (SrcElTy == DstElTy) {
Benjamin Kramer2a7404a2015-04-18 16:52:08 +00001809 SmallVector<Value *, 8> Idxs(NumZeros + 1, Builder->getInt32(0));
Jay Foadd1b78492011-07-25 09:48:08 +00001810 return GetElementPtrInst::CreateInBounds(Src, Idxs);
Chris Lattner2b295a02010-01-04 07:53:58 +00001811 }
1812 }
Craig Topper3529aa52013-01-24 05:22:40 +00001813
Chris Lattner229907c2011-07-18 04:54:35 +00001814 if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Duncan Sands19d0b472010-02-16 11:11:14 +00001815 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001816 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1817 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2b295a02010-01-04 07:53:58 +00001818 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner2b295a02010-01-04 07:53:58 +00001819 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1820 }
Craig Topper3529aa52013-01-24 05:22:40 +00001821
Chris Lattnerdd660102010-08-28 01:20:38 +00001822 if (isa<IntegerType>(SrcTy)) {
1823 // If this is a cast from an integer to vector, check to see if the input
1824 // is a trunc or zext of a bitcast from vector. If so, we can replace all
1825 // the casts with a shuffle and (potentially) a bitcast.
1826 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
1827 CastInst *SrcCast = cast<CastInst>(Src);
1828 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1829 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
Sanjay Patele2834412015-09-09 14:54:29 +00001830 if (Instruction *I = optimizeVectorResize(BCIn->getOperand(0),
Chris Lattner02b0df52010-05-08 21:50:26 +00001831 cast<VectorType>(DestTy), *this))
Chris Lattnerdd660102010-08-28 01:20:38 +00001832 return I;
1833 }
Craig Topper3529aa52013-01-24 05:22:40 +00001834
Chris Lattnerdd660102010-08-28 01:20:38 +00001835 // If the input is an 'or' instruction, we may be doing shifts and ors to
1836 // assemble the elements of the vector manually. Try to rip the code out
1837 // and replace it with insertelements.
Sanjay Patele2834412015-09-09 14:54:29 +00001838 if (Value *V = optimizeIntegerToVectorInsertions(CI, *this))
Sanjay Patel4b198802016-02-01 22:23:39 +00001839 return replaceInstUsesWith(CI, V);
Chris Lattner02b0df52010-05-08 21:50:26 +00001840 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001841 }
1842
Chris Lattner229907c2011-07-18 04:54:35 +00001843 if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Michael Ilseman74a6da92013-02-11 21:41:44 +00001844 if (SrcVTy->getNumElements() == 1) {
1845 // If our destination is not a vector, then make this a straight
1846 // scalar-scalar cast.
1847 if (!DestTy->isVectorTy()) {
1848 Value *Elem =
1849 Builder->CreateExtractElement(Src,
1850 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1851 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1852 }
1853
1854 // Otherwise, see if our source is an insert. If so, then use the scalar
1855 // component directly.
1856 if (InsertElementInst *IEI =
1857 dyn_cast<InsertElementInst>(CI.getOperand(0)))
1858 return CastInst::Create(Instruction::BitCast, IEI->getOperand(1),
1859 DestTy);
Chris Lattner2b295a02010-01-04 07:53:58 +00001860 }
1861 }
1862
1863 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001864 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
Dan Gohmaneb7111b2010-04-07 23:22:42 +00001865 // a bitcast to a vector with the same # elts.
Craig Topper3529aa52013-01-24 05:22:40 +00001866 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
Matt Arsenaultfc00f7e2013-08-14 00:24:34 +00001867 DestTy->getVectorNumElements() == SVI->getType()->getNumElements() &&
Chris Lattnera93c63c2010-01-05 22:21:18 +00001868 SVI->getType()->getNumElements() ==
Matt Arsenaultfc00f7e2013-08-14 00:24:34 +00001869 SVI->getOperand(0)->getType()->getVectorNumElements()) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001870 BitCastInst *Tmp;
1871 // If either of the operands is a cast from CI.getType(), then
1872 // evaluating the shuffle in the casted destination's type will allow
1873 // us to eliminate at least one cast.
Craig Topper3529aa52013-01-24 05:22:40 +00001874 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
Chris Lattnera93c63c2010-01-05 22:21:18 +00001875 Tmp->getOperand(0)->getType() == DestTy) ||
Craig Topper3529aa52013-01-24 05:22:40 +00001876 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
Chris Lattnera93c63c2010-01-05 22:21:18 +00001877 Tmp->getOperand(0)->getType() == DestTy)) {
1878 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1879 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1880 // Return a new shuffle vector. Use the same element ID's, as we
1881 // know the vector types match #elts.
1882 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner2b295a02010-01-04 07:53:58 +00001883 }
1884 }
1885 }
Craig Topper3529aa52013-01-24 05:22:40 +00001886
Sanjay Patel1d49fc92015-12-12 16:44:48 +00001887 if (Instruction *I = canonicalizeBitCastExtElt(CI, *this, DL))
Sanjay Patelc83fd952015-12-10 17:09:28 +00001888 return I;
1889
Duncan Sands19d0b472010-02-16 11:11:14 +00001890 if (SrcTy->isPointerTy())
Chris Lattnera93c63c2010-01-05 22:21:18 +00001891 return commonPointerCastTransforms(CI);
1892 return commonCastTransforms(CI);
Chris Lattner2b295a02010-01-04 07:53:58 +00001893}
Matt Arsenaulta9e95ab2013-11-15 05:45:08 +00001894
1895Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
Manuel Jacobb4db99c2014-07-16 01:34:21 +00001896 // If the destination pointer element type is not the same as the source's
1897 // first do a bitcast to the destination type, and then the addrspacecast.
1898 // This allows the cast to be exposed to other transforms.
Jingyue Wu77145d92014-06-06 21:52:55 +00001899 Value *Src = CI.getOperand(0);
1900 PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType());
1901 PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType());
1902
1903 Type *DestElemTy = DestTy->getElementType();
1904 if (SrcTy->getElementType() != DestElemTy) {
1905 Type *MidTy = PointerType::get(DestElemTy, SrcTy->getAddressSpace());
Jingyue Wubaabe502014-06-15 21:40:57 +00001906 if (VectorType *VT = dyn_cast<VectorType>(CI.getType())) {
1907 // Handle vectors of pointers.
1908 MidTy = VectorType::get(MidTy, VT->getNumElements());
1909 }
Jingyue Wu77145d92014-06-06 21:52:55 +00001910
1911 Value *NewBitCast = Builder->CreateBitCast(Src, MidTy);
1912 return new AddrSpaceCastInst(NewBitCast, CI.getType());
1913 }
1914
Matt Arsenault2d353d12014-01-14 20:00:45 +00001915 return commonPointerCastTransforms(CI);
Matt Arsenaulta9e95ab2013-11-15 05:45:08 +00001916}